var system = require("../../system")
const http = require("http")
const querystring = require('querystring');
var settings = require("../../../config/settings");
const CtlBase = require("../ctl.base");
const logCtl = system.getObject("web.oplogCtl");
const md5 = require("MD5");
const crypto = require('crypto');

class UserCtl extends CtlBase {
  constructor() {
    super(CtlBase.getServiceName(UserCtl));
    //this.loginS=system.getObject("service.userSve");
    this.restS = system.getObject("util.restClient");
    this.smsS = system.getObject("util.smsClient");
    this.accountDao = system.getObject("db.accountDao");
    this.productDao = system.getObject("db.productDao");
    this.accountSve = system.getObject("service.accountSve");
    this.appSve = system.getObject("service.appSve");
    this.productSve = system.getObject("service.productSve");
    this.randomS = system.getObject("service.orderSve");
    this.utilesignbaoSve = system.getObject("service.utilesignbaoSve");
    this.usereaccountSve = system.getObject("service.usereaccountSve");
    this.ecompanySve = system.getObject("service.ecompanySve");
    this.channelSve = system.getObject("service.channelSve");
    this.servicesitemSve = system.getObject("service.servicesitemSve");
  }
  //  async update(ueryobj,qobj,req){
  //    if(qobj.ecompany_id && qobj.ecompany_id!=""){
  //      //为了实现下个页面的跳转获取参数
  //      if(req.session){
  //        req.session.ecompany_id=qobj.ecompany_id;
  //      }
  //    }
  //    var results=await super.update(ueryobj,qobj,req);
  //    return results;
  //  }
  async loginUser(qobj, pobj, req) {
    return super.findById(req.session.user.id);
  }
  async findbymobile(qobj, pobj, req) {
    var result = await this.service.findOne(pobj);
    console.log(result);
    return result;
  }
  async loginByMobile(qobj, pobj, req) {
    var user = await this.service.findOne(pobj);
    console.log("-------ctl--------loginByMobile---------");
    console.log(user);
    if (user != null) {
      req.session.user = user;
      req.session.app = user.app_id;
      return system.getResult2({});
    } else {
      return system.getResult2(null);
    }
  }
  //获取验证码，发送给指定手机
  async fetchVcode(qobj, pobj, req) {
    var mobile = pobj.mobile;
    //生成一个验证码，发送
    var vcode = await this.randomS.getUidStr(6, 10);
    await this.smsS.sendMsg(mobile, vcode);
    return system.getResult2({
      vcodestr: vcode
    });
  }
  async checkLogin(qobj, req) {
    var accountBalance = await this.accountSve.getAccountBalance(req.session.user.account_id, req.session.user.app_id);
    try {
      var user = await this.service.getUserByOpenId(req.session.user.openId, req.session.app.appid);
      req.session.user = user; //.get({plain:true});
    } catch (e) {
      var x = {
        status: -99,
        msg: "no login"
      };
      req.session.user = null;
      req.session.destroy();
      console.log(e.stack);
      return system.getResult2(x, req);
    }
    var tmp = {
      id: req.session.user.id,
      appid: req.session.user.app_id,
      nickName: req.session.user.nickName,
      imgUrl: req.session.user.headUrl,
      accountBalance: accountBalance,
      appkey: req.session.app.appid,
      appname: req.session.app.name,
      sex: req.session.user.sex,
      mobile: req.session.user.mobile,
      tm_company_id: req.session.user.tm_company_id,
      tm_copmpany_name: req.session.user.tm_copmpany_name,
    }
    if (req.session.isNewUser && req.session.isNewUser == 1) {
      tmp.isNewUser = 1;
      await this.cacheManager.buildCacheMap();
      const initGiftNum = await this.cacheManager["InitGiftCache"].cacheGlobalVal();
      this.notify(req, `赠送${initGiftNum}宝币，开启效能之旅...`);
      req.session.isNewUser = null;
    } else {
      tmp.isNewUser = 0;
    }
    if (req.session.originTarget != null) {
      //检查如果有值就传到客户端，然后清空
      tmp.originTarget = req.session.originTarget;
      req.session.originTarget = null;
    }

    if (req.session.user.partnerinfo == null) {
      tmp.isPartner = 0;
    } else {
      tmp.isPartner = 1;
    }
    console.log(".......check login.......................");
    return system.getResult2(tmp, req);
  }
  async exit(qobj, req) {
    var u = req.session.user;
    var x = u.app_id + "￥" + u.id + "￥" + u.nickName + "￥" + u.headUrl;
    await this.cacheManager["VisitCountCache"].exit(null, x);
    req.session.user = null;
    req.session.app = null;
    req.session.destroy();
    return system.getResult2("exit");
  }
  async login(code, state, req) {
    var tHomePage = null;
    try {
      //state进行处理，来解决排单交付，state="@"分隔
      var isiwant = false;
      var afterval = null;
      if (state && state.indexOf("@") >= 0) {
        afterval = state.split("@")[1];
        state = state.split("@")[0];
        isiwant = true;
      }
      if (code.indexOf("ebedbyc") >= 0) {
        console.log("---------------------------------------------ebedbyc----------------------------------------------------------------");
        console.log(code);
        var arraystr = code.split("|");
        var username = arraystr[1];
        var openpage = arraystr[2];
        var appkey = "wxe49ea352795cea4c";
        var existedUser = await this.service.getUserByUsername(username, appkey);
        if (existedUser != null) {
          console.log(existedUser);
          req.session.user = existedUser;
          req.session.app = existedUser.app;
          if (openpage == "openbycsearch") {
            var tminput = req.query.tminput;
            if (tminput) {
              var urlstr = existedUser.app.homePage + "?" + "&tminput=" + tminput;
            } else {
              var urlstr = existedUser.app.homePage + "?" + openpage;
            }
          }
          if (openpage == "openbycjk") {
            var urlstr = existedUser.app.homePage + "?" + openpage;
          }
          return urlstr;
        } else {
          var wxUserInfo = {
            nickName: username,
            description: "",
            openId: "",
            unionId: "",
            onlyCode: "",
            userName: username,
            headUrl: "",
            appKey: appkey,
          }
          existedUser = await this.service.loginbyc(wxUserInfo);
          req.session.user = existedUser;
          //返回要跳转的具体应用的地址
          var app = await this.appSve.getApp(appkey);
          req.session.app = app;
          if (openpage == "openbycsearch") {
            var tminput = req.query.tminput;
            if (tminput) {
              var urlstr = app.homePage + "?" + "tminput=" + tminput;
            } else {
              var urlstr = app.homePage + "?" + openpage;
            }
          }
          if (openpage == "openbycjk") {
            var urlstr = app.homePage + "?" + openpage;
          }
          return urlstr;

        }

      }

      //按照来源code是否含有embed code=embed|openid,state=appkeyid
      if (code.indexOf("embed") >= 0) {
        console.log("yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy");
        console.log(state);
        //甚至默认进入的子页面
        var action = "";
        if (state) {
          action = state + "?from=mobile";
        }
        var arraystr = code.split("|");
        if (arraystr.length > 5) {
          return;
        }

        var openid = arraystr[1];
        //设置默认来源应用为合伙人
        var appkey = "wxda6eab8429128ccd";
        if (arraystr.length >= 3 && arraystr[2]) {
          appkey = arraystr[2];
        }

        var onlyCode = "";
        if (arraystr.length == 5) {
          var embedType = openid;
          // 3 公司名称
          var companyName = arraystr[3];
          // 4 业务id
          var uid = arraystr[4];
          if (!uid) {
            return;
          }

          var ecompany = await this.ecompanySve.findOne({
            name: companyName
          });
          //甚至默认进入的子页面
          action = "?from=mobile";
          if (ecompany) {
            action = action + "&ecid=" + ecompany.id;
          }

          onlyCode = uid + "_" + embedType;
          var token = md5(onlyCode);
          token = token.substring(8, 20);
          openid = onlyCode + "_" + token;
        }

        var existedUser = await this.service.getUserByOpenId(openid, appkey);
        if (existedUser != null) {
          console.log(existedUser);
          req.session.user = existedUser;
          req.session.app = existedUser.app;
          var urlstr = existedUser.app.homePage + action;
          return urlstr;
        } else {
          //
          var wxUserInfo = {
            nickName: "",
            description: "",
            openId: openid,
            unionId: openid,
            onlyCode: onlyCode,
            userName: "",
            headUrl: "",
            appKey: appkey,
          }
          existedUser = await this.service.loginWithoutGift(wxUserInfo);
          req.session.user = existedUser;
          //返回要跳转的具体应用的地址
          var app = await this.appSve.getApp(appkey);
          req.session.app = app;
          if (arraystr.length == 5) {
            return app.homePage + action;
          } else {
            return app.homePage;
          }
        }
      }
      //先按照openid 检查是否已经存在注册用户
      if (settings.env == "dev") {
        if (!state || state == "") {
          state = "wx76a324c5d201d1a4|msgs";
        }
      }
      //以|分隔state，标示app和来源动作
      var stateArry = state.split("|");
      state = stateArry[0];
      var originTarget = null;
      if (stateArry.length == 2) {
        originTarget = stateArry[1];
        req.session.originTarget = originTarget;
      } else {
        req.session.originTarget = null;
      }
      var tokenObj = await this.getToken(code, req, state);
      var openid = tokenObj.openid;
      var unionid = tokenObj.unionid;
      var accessToken = tokenObj.access_token;
      //state为p_app表中appkey
      var existedUser = await this.service.getUserByOpenId(openid, state);
      if (existedUser != null) {
        // console.log("already existed.................................................db...........................login......");
        // console.log(existedUser);
        req.session.user = existedUser;
        req.session.app = existedUser.app;
        req.session.isNewUser = 0;
        var urlstrtmp = "";
        if (isiwant) {
          if (afterval == "zhixincloud") {
            urlstrtmp = "https://zhixincloud.gongsibao.com/";
          } else {
            urlstrtmp = existedUser.app.homePage.split("|")[1];
          }

        } else {
          if (existedUser.app.homePage.indexOf("|") >= 0) {
            urlstrtmp = existedUser.app.homePage.split("|")[0];
          } else {
            urlstrtmp = existedUser.app.homePage;
          }
        }

        return urlstrtmp;
      } else {
        var wxUserInfo = null;
        if (settings.env == "dev") {
          wxUserInfo = {
            nickName: "dev",
            description: "dev test",
            openId: "testopenid",
            unionId: "testunionid",
            onlyCode: "testunionid",
            userName: "testunionid",
            headUrl: "/imgs/logo.png",
            sex: 'male',
            from: "山东,潍坊,高密",
            appKey: state,
            isAdmin: true,
          }
        } else {
          //按照accessToken获取用户信息
          const userInfo = await this.getUserInfo(accessToken, openid);
          console.log("get userinfo...............");
          console.log(userInfo);
          wxUserInfo = {
            nickName: userInfo.nickname,
            description: userInfo.country + "-" + userInfo.province + "-" + userInfo.city,
            openId: userInfo.openid,
            unionId: userInfo.unionid,
            onlyCode: userInfo.unionid,
            userName: userInfo.nickname,
            headUrl: userInfo.headimgurl,
            sex: userInfo.sex == 1 ? "male" : "female",
            from: userInfo.province + "," + userInfo.city + "," + userInfo.country,
            appKey: state,
          }
        }
        //创建用户信息

        var userRisgered = null;
        //如果是智薪云或者我要那么就走
        if (state == "wxdc08c441c9fdb7a7" || state == "wx4c91e81bbb6039cd") {
          userRisgered = await this.service.loginWithoutGift(wxUserInfo);
        } else {
          userRisgered = await this.service.login(wxUserInfo);
        }

        console.log("....userCtl...........................................userRisgered**************************************************************************************");
        console.log(userRisgered);
        userRisgered.partnerinfo = null;
        req.session.user = userRisgered;
        req.session.isNewUser = 1;
        //返回要跳转的具体应用的地址
        var app = await this.appSve.getApp(state);
        req.session.app = app;
        var urlstrtmp = "";
        if (isiwant) {
          if (afterval == "zhixincloud") { //为了解决智薪云的税务查，没有添加新的应用
            urlstrtmp = "https://zhixincloud.gongsibao.com/";
          } else {
            urlstrtmp = app.homePage.split("|")[1];
          }
        } else {
          if (app.homePage.indexOf("|") >= 0) {
            urlstrtmp = app.homePage.split("|")[0];
          } else {
            urlstrtmp = app.homePage;
          }
        }
        return urlstrtmp;
      }
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "userCtl--login异常错误error",
        op: "base/controller/impl/userCtl/login",
        content: e.stack,
        clientIp: system.get_client_ip(req)
      });
    }
    return tHomePage;
  }
  async getUserInfo(accessToken, openId) {
    let reqUrl = 'https://api.weixin.qq.com/sns/userinfo';
    let params = {
      access_token: accessToken,
      openid: openId,
      lang: 'zh_CN'
    };

    var data = querystring.stringify(params);
    var rtn = await this.restS.execGet(data, reqUrl);
    return JSON.parse(rtn.stdout);
  }
  async update(queryobj, qobj, req) {
    // if(req && req.session && req.session.user){
    //   qobj.onlyCode=req.session.user.unionId;
    // }
    if (req.codepath) {
      qobj.codepath = req.codepath;
    }
    var rd = await this.service.update(qobj);
    return system.getResult2(rd, null);
  }
  async getToken(code, req, state) {
    if (settings.env == "prod") {
      let reqUrl = 'https://api.weixin.qq.com/sns/oauth2/access_token';
      console.log(state);
      var appobj = await this.cacheManager["AppCache"].cacheApp(state);
      console.log(appobj);
      let params = {
        appid: appobj.appid,
        secret: appobj.secret,
        code: code,
        grant_type: 'authorization_code'
      };
      var data = querystring.stringify(params);
      var rtn = await this.restS.execGet(data, reqUrl);
      return JSON.parse(rtn.stdout);
    } else {
      var rtn = {
        "access_token": "ACCESS_TOKEN",
        "expires_in": 7200,
        "refresh_token": "REFRESH_TOKEN",
        "openid": "xxyy",
        "scope": "SCOPE",
        "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
      }
      return rtn;
    }
  }
  async checkAccountBalance(qobj, req) {
    var productId = qobj.productId;
    var user = req.session.user;
    var accountId = user.account_id;
    var product = await this.productDao.model.findOne({
      where: {
        id: productId
      }
    });
    var account = await this.accountDao.model.findOne({
      where: {
        id: accountId
      }
    });
    return account.baoBalance - product.price > 0;
  };
  async checkAccountBalanceByCode(qobj, req) {
    var productCode = qobj.productCode;
    var user = req.session.user;
    var accountId = user.account_id;
    var product = await this.productSve.findOneByCode(productCode);
    var account = await this.accountSve.findById(accountId);
    return account.baoBalance - product.price > 0;
  };
  async getUidStr(len, radix) {
    var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
    var uuid = [],
      i;
    radix = radix || chars.length;
    if (len) {
      for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
    } else {
      var r;
      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
      uuid[14] = '4';
      for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
          r = 0 | Math.random() * 16;
          uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
        }
      }
    }
    return uuid.join('');
  }
  async updateSigner(qobj, pobj, req) {
    if (req && req.session && req.session.user) {
      pobj.onlyCode = req.session.user.unionId;
      pobj.id = req.session.user.id;
    }
    if (req.codepath) {
      pobj.codepath = req.codepath;
    }
    var loginUser = await this.service.findById(req.session.user.id);
    // 获取该身份证帐号信息
    var eaccount = await this.usereaccountSve.findOne({
      user_id: req.session.user.id,
      personsSign: pobj.personsSign
    });
    console.log(eaccount, "---------------------------------------------------------eaccount------- ");
    var bool = false;

    if (!eaccount || (eaccount.userName != pobj.userName || eaccount.personsSign != pobj.personsSign || eaccount.bankno != pobj.bankno)) {
      var bankthreeParams = {
        name: pobj.userName,//姓名 必填
        idno: pobj.personsSign,//身份证 必填
        cardno: pobj.bankno //银行卡 必填
      };
      var tt = await this.utilesignbaoSve.bankthree(bankthreeParams, "bankinfoAuth");
      // {"code":-110,"message":"手机号格式错误","data":{}}
      //1成功,-110提示验证信息有误，-120亲，提供的信息不正确，请验证后再试！
      console.log("tt-----------------------------", tt);
      if (!tt || tt.code == -120) {
        return system.getErrResult2("银行三要素验证失败，请检查姓名、身份证、银行卡号是否正确");
      }
      if (tt.code == -110) {
        return system.getErrResult2(tt.message);
      }
    }

    if (!eaccount) {
      eaccount = {
        mobile: pobj.mobile,
        userName: pobj.userName,
        personsSign: pobj.personsSign,
        bankno: pobj.bankno,
        eaccountid: "",
        email: "",
        user_id: req.session.user.id
      };
      eaccount = await this.usereaccountSve.create(eaccount);
    } else {
      bool = true;
    }

    var params = {
      thirdId: eaccount.eaccountid,
      name: pobj.userName,
      idNo: pobj.personsSign,
      idType: 19,
      mobile: pobj.mobile
    };
    console.log(eaccount.userName, pobj.userName, eaccount.mobile, pobj.mobile, eaccount.personsSign, pobj.personsSign, "--------------------------------------eaccount, pobj-------------------------- ");
    var isNeedCreate = !params.thirdId || eaccount.userName != pobj.userName || eaccount.mobile != pobj.mobile || eaccount.personsSign != pobj.personsSign;
    if (isNeedCreate) {
      params.thirdId = pobj.onlyCode + await this.getUidStr(8, 36); //咱们的唯一码-onlycode
    }

    if (bool) {
      eaccount.mobile = pobj.mobile;
      eaccount.userName = pobj.userName;
      eaccount.personsSign = pobj.personsSign;
      eaccount.bankno = pobj.bankno;
      await eaccount.save();
    }

    if (isNeedCreate) {
      // 通过手机号，姓名，身份证，获取e签宝 accountid
      var tt = await this.utilesignbaoSve.createAccountId(params, "userCtl");
      console.log(tt, "----------------------------------------------------tt------------ ");
      if (tt && tt.code == 1 && tt.data) {
        console.log(tt.code, "----------------------------------------tt.code------------------------ ");
        eaccount.eaccountid = tt.data.accountId;
        await eaccount.save();
      }
    }

    logCtl.info({
      optitle: "电子签更新用户",
      op: "base/controller/impl/userCtl.js",
      content: "params=" + JSON.stringify(params) + "，eaccount=" + JSON.stringify(eaccount) + ", isNeedCreate=" + isNeedCreate,
      clientIp: ""
    });

    return system.getResult2(eaccount);
  };

  async accountList(qobj, pobj, req) {
    var list = await this.usereaccountSve.findAll({
      user_id: req.session.user.id
    });
    return system.getResult2(list);
  }

  async updateMobile(qobj, pobj, req) {
    var userId = req.session.user.id;
    var mobile = pobj.mobile;
    let user = await this.service.findById(userId);
    user.mobile = mobile;
    user.save();
    return system.getResult2(user);
  }
  //处理渠道自动提报帐号登录
  async checkUserInfo(qobj, pobj, req) {
    //必须参数------结束
    try {
      var verifyResult = await this.verifyData(pobj);
      if (verifyResult.code != 1) {
        return { status: -1, msg: verifyResult.message };
      }
      // var user = req.session.user;
      // var app = req.session.app;
      // var account = req.session.account;
      // if (!user || !app || !account) {
      await this.opUserInfo(req, pobj, verifyResult);
      // }
      var user = req.session.user;

      //有值，但是mobile为空，则进行更新mobile
      var setParams = {};
      if (user && !user.userName && pobj.username) {
        user.userName = pobj.username;
        user.nickName = pobj.username;
        setParams.nickName = pobj.username;
        setParams.userName = pobj.username;
      }
      if (user && !user.mobile && pobj.mobile) {
        user.mobile = pobj.mobile;
        setParams.mobile = pobj.mobile;
      }
      var setKeys = Object.keys(setParams);
      if (setKeys.length > 0) {
        this.service.updateByWhere(setParams, { where: { id: user.id } });
      }
      var tUser = {
        id: req.session.user.id,
        appid: req.session.user.app_id,
        nickName: req.session.user.nickName,
        imgUrl: req.session.user.headUrl,
        appkey: req.session.app ? req.session.app.appid : null,
        appname: req.session.app ? req.session.app.name : null,
        sex: req.session.user.sex,
        mobile: req.session.user.mobile,
        tm_company_id: req.session.user.tm_company_id,
        tm_copmpany_name: req.session.user.tm_copmpany_name,
      };
      return system.getResult2(tUser, req);
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "userCtl--login用户信息异常............>error",
        op: "/fqboss/app/base/controller/impl/userCtl/checkUserInfo",
        content: e.stack,
        clientIp: system.get_client_ip(req)
      });
      console.log(e.stack, "用户信息异常.......................>");
      return { status: -200, msg: "用户信息异常" };
    }
  }
  async opUserInfo(req, pobj, verifyResult) {
    var openid = "ar_" + pobj.openid + "_gsb_zcsubmit";
    var user = await this.service.getUserByOpenId(openid, verifyResult.data.app_key);
    if (!user) {
      var name = await this.getUidStr(8, 62);
      if (pobj.username) {
        name = pobj.username;
      }
      user = {
        app_id: verifyResult.data.app_id,//应用id
        nickName: name,
        openId: openid,
        unionId: openid,
        onlyCode: openid,
        mobile: pobj.mobile || "",
        userName: name,
        headUrl: "",
        appKey: verifyResult.data.app_key,
      };
      user["description"] = verifyResult.data.product_desc;// "自动提报:" + product.name + product.id;
      await this.service.loginWithoutGift(user);
      user = await this.service.getUserByOpenId(openid, verifyResult.data.app_key);
    }
    req.session.user = user;
    req.session.app = user.app;
    req.session.account = user.account;
  }
  async verifyData(pobj) {
    var result = {
      code: 1,
      message: "success",
      data: {}//{app_id,app_key,product_desc-"自动提报:" + product.name + product.id,}
    }
    var appcode = pobj.appCode;//应用编码
    var sign = pobj.sign;//签名信息
    if (!pobj.appCode) {
      result.code = -1;
      result.message = "appCode参数错误";
      return result;
    }
    if (!pobj.channelCode) {
      result.code = -1;
      result.message = "channelcode参数错误";
      return result;
    }
    if (!pobj.openid) {
      result.code = -1;
      result.message = "openid参数错误";
      return result;
    }
    let applistCache = await this.cacheManager["ApplistCache"].getListByCache();
    if (applistCache == null || applistCache == "" || applistCache == "undefined") {
      result.code = -1;
      result.message = "缓存app数据有误";
      return result;
    }
    let appList = JSON.parse(applistCache);
    if (appList == null || appList.length == 0) {
      result.code = -1;
      result.message = "缓存app数据有误！！";
      return result;
    }
    var newList = appcode && sign ? appList.filter(item => item.app_code == appcode)
      : appList.filter(item => item.app_code == appcode);//没有签名则用渠道自动提报

    if (newList == null || newList.length == 0) {
      result.code = -1;
      result.message = "通过缓存获取app数据有误";
      return result;
    }
    let appItem = newList[0];
    if (appcode && sign) { // 验证签名
      var signResult = await this.paramsSign(pobj, appItem.secret);
      if (signResult.code != 1) {
        result.code = -1;
        result.message = "签名错误，请重试";
        return result;
      }
    }
    var channel = await this.channelSve.getChannelItem(pobj.channelCode);
    if (!channel) {
      result.code = -1;
      result.message = "渠道错误";
      return result;
    }
    if (pobj.itemCode) {
      var product = await this.servicesitemSve.findOne({ code: pobj.itemCode, channelCode: pobj.channelCode });
      if (!product) {
        result.code = -1;
        result.message = "渠道产品不存在";
        return result;
      }
      result.data["product_desc"] = "自动提报:" + product.name + product.id;
    }
    else {
      result.data["product_desc"] = "自动提报首页产品展示";
    }
    result.data["app_id"] = appItem.id;
    result.data["app_key"] = appItem.appid;
    result.data["app_secret"] = appItem.secret;

    return result;
  }

  async paramsSign(pobj, app_key) {//进行验签校验
    var rtnResult = { code: 1, msg: "SUCCESS" };
    if (!pobj) {
      rtnResult.code = -310;
      rtnResult.msg = "请求参数为空";
      return rtnResult;
    }
    if (!pobj.sign) {
      rtnResult.code = -320;
      rtnResult.msg = "请求参数sign为空";
      return rtnResult;
    }
    var signArr = [];
    var keys = Object.keys(pobj).sort();
    if (keys.length == 0) {
      rtnResult.code = -330;
      rtnResult.msg = "请求参数信息为空";
      return rtnResult;
    }
    for (let k = 0; k < keys.length; k++) {
      const tKey = keys[k];
      if (tKey != "sign" && pobj[tKey]) {
        signArr.push(tKey + "=" + pobj[tKey]);
      }
    }
    if (signArr.length == 0) {
      rtnResult.code = -350;
      rtnResult.msg = "请求参数组装签名参数信息为空";
      return rtnResult;
    }
    var resultSignStr = signArr.join("&") + "&key=" + app_key;
    var resultTmpSign = md5(resultSignStr).toUpperCase();
    if (pobj.sign != resultTmpSign) {
      rtnResult.code = -380;
      rtnResult.msg = "返回值签名验证失败";
      return rtnResult;
    }
    return rtnResult;
  }
}
module.exports = UserCtl;
