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 uuidv4 = require('uuid/v4')
class UserCtl extends CtlBase {
  constructor() {
    super(CtlBase.getServiceName(UserCtl));
    this.cacheManager = system.getObject("db.cacheManager");

    this.restS = system.getObject("util.restClient");
    this.smsS = system.getObject("util.smsClient");
    this.bankthreelogSve = system.getObject("service.bankthreelogSve");
    this.ecompanySve = system.getObject("service.ecompanySve");
    this.usereaccountSve = system.getObject("service.usereaccountSve");
    this.utilesignbaoSve = system.getObject("service.utilesignbaoSve");
    this.epartnerSve = system.getObject("service.epartnerSve");
    this.ejobapplySve = system.getObject("service.ejobapplySve");
    this.redisClient = system.getObject("util.redisClient");
    this.mailClient = system.getObject("util.mailClient");

    this.usereaccountextendSve = system.getObject("service.usereaccountextendSve");
  }
  async findAndCountAll(queryobj, obj, req) {
    var pageInfo = obj.pageInfo || {};
    var search = obj.search || {};
    // 1 外部用户 2内部用户 0全部
    search.isBack = 2;

    var apps = await this.service.userPage(pageInfo, search);
    if (apps && apps.rows) {
      for (var row of apps.rows) {
        row.password = "";
      }
    }
    return system.getResult2(apps, null);
  }

  async create(queryobj, qobj, req) {
    if (req.codepath) {
      qobj.codepath = req.codepath;
    }

    if (qobj.isPartner) {
      var nameUser = await this.service.findPartnerUser(qobj.userName);
      if (nameUser) {
        return system.getErrResult2("合伙人用户帐号已存在");
      }
    }

    if (qobj.isEnt) {
      var nameUser = await this.service.findEntUser(qobj.userName);
      if (nameUser) {
        return system.getErrResult2("企业用户帐号已存在");
      }
    }

    if (!qobj.isEnt && !qobj.isPartner) {
      var nameUser = await this.service.findOne({
        userName: qobj.userName
      });
      if (nameUser) {
        return system.getErrResult2("用户帐号已存在");
      }
    }

    qobj.password = this.encryptPasswd(qobj.mobile.trim().substring(qobj.mobile.trim().length - 6));
    qobj.utype = 1;
    var rd = await this.service.create(qobj);
    return system.getResult2(rd, null);
  }

  async update(queryobj, qobj, req) {
    if (req.codepath) {
      qobj.codepath = req.codepath;
    }

    if (qobj.isPartner) {
      var nameUser = await this.service.findPartnerUser(qobj.userName);
      if (nameUser && qobj.id != nameUser.id) {
        return system.getErrResult2("合伙人用户帐号已存在");
      }
    }

    if (qobj.isEnt) {
      var nameUser = await this.service.findEntUser(qobj.userName);
      if (nameUser && qobj.id != nameUser.id) {
        return system.getErrResult2("企业用户帐号已存在");
      }
    }

    if (!qobj.isEnt && !qobj.isPartner) {
      var nameUser = await this.service.findOne({
        userName: qobj.userName
      });
      if (nameUser && qobj.id != nameUser.id) {
        return system.getErrResult2("用户帐号已存在");
      }
    }

    var old = await this.service.findById(qobj.id);
    if (old.password) {
      qobj.password = old.password;
    } else {
      qobj.password = this.encryptPasswd(qobj.mobile.trim().substring(qobj.mobile.trim().length - 6));
    }
    qobj.utype = 1;
    var rd = await this.service.update(qobj);
    return system.getResult2(rd, null);
  }

  async initNewInstance(queryobj, req) {
    return system.getResult2({
      roles: []
    }, null);
  }

  async getCurrentUser(qobj, pobj, req) {
    var userid = req.headers.referer.substr(req.headers.referer.indexOf('userid') + 7);

    // var accountInfo = await this.redisClient.get("yd_user_" + userid);
    // var mobile = accountInfo.substr(accountInfo.indexOf('mobile') + 9,11);
    // var name = accountInfo.substr(accountInfo.indexOf('userName') + 11,accountInfo.indexOf('mobile')-16);
    // var personSign = accountInfo.substr(accountInfo.indexOf('personsSign') + 14,18);
    // var bankno = accountInfo.substr(accountInfo.indexOf('bankno') + 9,16);

    var accountInfoJson = await this.redisClient.get("yd_user_" + userid) || "";
    var accountInfo = {};
    if(accountInfoJson) {
        accountInfo = JSON.parse(accountInfoJson);
    }
    var mobile = accountInfo.mobile || "";
    var name = accountInfo.userName || "";
    var personSign = accountInfo.personsSign || "";
    var bankno = accountInfo.bankno || "";

    var info = {
      personsSign: personSign,
      mobile: mobile,
      userName: name,
      bankno: bankno,
    }

    var result = {
      status: 0,
      message: "success",
      data: {
        info:{}
      }
    };
    result.data.info = info;
    return result;
    //return system.getResult2(req.session.user);
  }



  async loginUser(qobj, pobj, req) {
    var u = await super.findById(req.session.user.id);
    var user = {};
    if (u) {
      for (var idx in u) {
        user[idx] = u[idx];
      }
    }
    user.isDefaultPassword = false;
    //"0"-false,"1"-true
    var ischeck = await this.redisClient.get("check_pwd_" + u.data.id);
    if (ischeck === "0" && user.data.mobile && user.data.mobile.length > 6) {
      var defaultPwd = super.encryptPasswd(user.data.mobile.substring(user.data.mobile.length - 6));
      if (user.data.password == defaultPwd) {
        user.isDefaultPassword = true;
        await this.redisClient.set("check_pwd_" + u.data.id, "1");
      }
    }
    return user;
  }

  async info(qobj, pobj, req) {
    var user = await this.service.findById(req.session.user.id);
    var tmp = {
      userName: user.userName,
      nickName: user.nickName,
      mobile: user.mobile,
      isPartner: user.isPartner,
      email: user.email,
      hasPassword: !!user.password,
      companyName: user.companyName,
      companyAddr: user.companyAddr,
    }
    return system.getResult2(tmp);
  }
  //获取验证码，发送给指定手机
  async fetchVcode(qobj, pobj, req) {
    var mobile = pobj.mobile;
    //生成一个验证码，发送
    var vcode = await this.service.getUidStr(6, 10);
    await this.smsS.sendMsg(mobile, vcode);
    return system.getResult2({
      vcodestr: vcode
    });
  }
  async checkLogin(qobj, req) {
    if (req.session.user) {
      var tmp = {
        id: req.session.user.id,
        userName: req.session.user.userName,
        nickName: req.session.user.nickName,
        mobile: req.session.user.mobile,
        isAdmin: req.session.user.isAdmin,
        statAuth: req.session.user.isBpoManager || req.session.user.isAdmin,
        roles: req.session.user.Roles,
      }
      return system.getResult2(tmp, req);
    } else {
      var referer = req.headers.referer;
      var openid = referer.substr(referer.indexOf('openid=') + 7,referer.indexOf('&appkey=') - referer.indexOf('openid=') - 7) || "";
      var appkey = referer.substr(referer.indexOf('&appkey=') + 8) || "";
      var userid = referer.substr(referer.indexOf('&userid=') + 8) || "";

      //获取redis中的数据
      var accountInfoJson = await this.redisClient.get("yd_user_" + userid);

      var accountInfo = {};
      if(accountInfoJson) {
          accountInfo = JSON.parse(accountInfoJson);
      }
      var mobile = accountInfo.mobile || "";
      var name = accountInfo.userName || "";
      var personSign = accountInfo.personsSign || "";
      var bankno = accountInfo.bankno || "";

      if(openid) {
        var existedUser = await this.service.getUserByOpenId(openid, appkey);
        if(existedUser){
          //日志记录
          logCtl.info({
            optitle: "userCtl--checkLogin 异常 error",
            op: "base/controller/impl/userCtl/loginyd",
            content: "cookie丢失,urlParam从新load," + JSON.stringify(req.query) + ",headers:"+ JSON.stringify(req.headers.referer),
            clientIp: ""
          });

          var tmp = {
            id: existedUser.id,
            userName: existedUser.userName == "" ? name : existedUser.userName,
            nickName: existedUser.nickName,
            mobile: existedUser.mobile == null ? mobile : existedUser.mobile,
            isAdmin: existedUser.isAdmin,
            statAuth: existedUser.isBpoManager || existedUser.isAdmin,
            roles: existedUser.Roles,
          }
          return system.getResult2(tmp, req);
        }
      }

      req.session.user = null;
      req.session.destroy();
      return system.getErrResult2(1);
    }
  }
  async exit(qobj, req) {
    req.session.user = null;
    req.session.destroy();
    return system.getResult2("exit");
  }
  async register(qobj, pobj, req) {
    console.log(pobj.u);
    var user = await this.service.findOne({
      userName: pobj.u.userName
    });
    if (user) {
      return system.getErrResult2("用户已存在, 请修改并重试");
    }
    pobj.u.password = super.encryptPasswd(pobj.u.password);
    pobj.u.utype = 1;
    var u = await this.service.register(pobj.u);
    //req.session.user=u;
    return system.getResult2(u);
  }
  async regCompanyUser(qobj, pobj, req) {
    var vcode = pobj.vcode || "";
    if (!vcode) {
      return system.getErrResult2("手机验证码错误, 请重试");
    }

    var mobile = pobj.mobile;
    var password = pobj.passwd;
    var passwdConfirm = pobj.passwdConfirm;
    if (!password) {
      return system.getErrResult2("请输入密码");
    }

    // if(password.length < 6) {
    //   return system.getErrResult2("您输入的密码位数太简单, 至少6位字母与数字组合");
    // }

    if (password != passwdConfirm) {
      return system.getErrResult2("两次密码输入不一致");
    }

    var code = await this.redisClient.get("mobile_" + mobile) || "";
    if (vcode.toLowerCase() != code.toLowerCase()) {
      return system.getErrResult2("手机验证码错误, 请重试");
    }

    var user = await this.service.findEntUser(mobile);
    if (user) {
      return system.getErrResult2("用户已存在, 请登录");
    }

    user = {
      userName: mobile,
      password: super.encryptPasswd(pobj.passwd),
      nickName: "",
      headUrl: "",
      onlyCode: "bpo_ent_" + mobile,
      mobile: mobile,
      isEnt: true,
      utype: 1,
    }
    user = await this.service.registerEnt(user);
    return system.getResult2(user);
  }

  async login(qobj, pobj, req) {
    //state为p_app表中appkey
    pobj.u.password = super.encryptPasswd(pobj.u.password);
    var existedUser = await this.service.getUserByUserNamePwd(pobj.u);
    if (!existedUser) {
      return system.getErrResult2("用户名或密码错误");
    }
    if (pobj.u.aggree) {
      existedUser.isAgreePartner = true;
      existedUser.save();
    }

    if (existedUser) {
      req.session.user = existedUser;
      if (existedUser.isPartner) {
        req.session.partner = await this.epartnerSve.findOne({
          user_id: existedUser.id
        });
      }
      req.session.ecompany = await this.ecompanySve.findOne({
        user_id: existedUser.id
      });
      req.session.myIds = await this.service.getMyIds(existedUser.id);
    }
    await this.redisClient.set("check_pwd_" + existedUser.id, "0");
    return system.getResult2(existedUser);
  }

  async loginhhr(qobj, pobj, req) {
    //state为p_app表中appkey
    pobj.u.password = super.encryptPasswd(pobj.u.password);
    var existedUser = await this.service.getUserByUserNamePwd(pobj.u);
    if (!existedUser) {
      return system.getErrResult2("用户名或密码错误");
    }
    if (pobj.u.aggree) {
      existedUser.isAgreePartner = true;
      existedUser.save();
    }

    if (existedUser) {
      req.session.user = existedUser;
      if (existedUser.isPartner) {
        req.session.partner = await this.epartnerSve.findOne({
          user_id: existedUser.id
        });
      }
      req.session.myIds = await this.service.getMyIds(existedUser.id);
    }
    await this.redisClient.set("check_pwd_" + existedUser.id, "0");
    return system.getResult2(existedUser);
  }

  async loginent(qobj, pobj, req) {
    //state为p_app表中appkey
    pobj.u.password = super.encryptPasswd(pobj.u.password);
    var existedUser = await this.service.getEntUserByUserNamePwd(pobj.u);
    if (!existedUser) {
      return system.getErrResult2("用户名或密码错误");
    }

    if (pobj.u.aggree) {
      existedUser.isAgreePartner = true;
      existedUser.save();
    }

    if (existedUser) {
      req.session.user = existedUser;
      req.session.ecompany = await this.ecompanySve.findOne({
        user_id: existedUser.id
      });
    }
    if (existedUser) {
      req.session.user = existedUser;
    }

    return system.getResult2(existedUser);
  }

  async loginstat(qobj, pobj, req) {
    //state为p_app表中appkey
    var u = {
      userName: this.trim(pobj.userName),
      password: super.encryptPasswd(this.trim(pobj.password))
    }
    var existedUser = await this.service.getUserByUserNamePwd(u);
    if (!existedUser) {
      return system.getErrResult2("用户名或密码错误");
    }

    if (!existedUser.isBpoManager && !existedUser.isAdmin) {
      return system.getErrResult2("您的账户无权限");
    }
    req.session.user = existedUser;
    return system.getResult2(existedUser);
  }

  async wxlogin(code, state, req) {
    var tHomePage = null;
    try {
      //state进行处理，来解决排单交付，state="@"分隔
      var afterval = null;
      if (state && state.indexOf("@") >= 0) {
        afterval = state.split("@")[1];
        state = state.split("@")[0];
      }

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

        //设置默认来源应用为合伙人
        var embedType = arraystr[1];
        var appkey = arraystr[2];
        // 3 公司名称
        var companyName = arraystr[3];
        // 4 业务id
        var uid = arraystr[4];
        if (!uid) {
          return;
        }

        var ecompany = await this.ecompanySve.findOne({
          name: companyName
        });
        //默认进入的子页面
        var action = "?from=mobile";
        if (ecompany) {
          action = action + "&ecid=" + ecompany.id;
        }
        var onlyCode = uid + "_" + embedType;
        var token = md5(onlyCode);
        token = token.substring(8, 20);
        var openid = onlyCode + "_" + token;
        var app = await this.cacheManager["AppCache"].cacheApp(appkey);

        var existedUser = await this.service.getUserByOpenId(openid, appkey);
        if (existedUser != null) {
          console.log(existedUser);
          req.session.user = existedUser;
          req.session.app = app;
          var urlstr = app.homePage + action;
          return urlstr;
        } else {
          //
          var wxUserInfo = {
            userName: "",
            nickName: "",
            password: "",
            openId: openid,
            unionId: openid,
            onlyCode: onlyCode,
            headUrl: "",
            appKey: appkey,
          }
          existedUser = await this.service.loginWithoutGift(wxUserInfo);
          req.session.user = existedUser;
          //返回要跳转的具体应用的地址
          req.session.app = app;
          if (arraystr.length == 5) {
            return;
          } else {}
        }
      }

      if (code.indexOf("dlgsigner") >= 0) {
        var app = await this.cacheManager["AppCache"].cacheApp("wxf616c0a459d66081");

        var arraystr = code.split("|");
        var applyId = Number(arraystr[1]);

        var apply = await this.ejobapplySve.findById(applyId);
        if (!apply) {
          return;
        }

        var ecid = apply.ecompany_id;
        var userId = apply.user_id;

        var existedUser = await this.service.getDLGUserById(userId);
        req.session.user = existedUser;
        console.log(app.homePage + "?from=mobile&jaid=" + applyId + "&ecompany_id=" + ecid);
        return app.homePage + "?from=mobile&jaid=" + applyId + "&ecompany_id=" + ecid;
      }

      //先按照openid 检查是否已经存在注册用户
      if (settings.env == "dev") {
        if (!state || state == "") {
          state = "wxf616c0a459d66081|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);
        var app = await this.cacheManager["AppCache"].cacheApp(existedUser.appkey);
        req.session.user = existedUser;
        req.session.app = app;
        req.session.isNewUser = 0;
        var urlstrtmp = "";

        if (app.homePage.indexOf("|") >= 0) {
          urlstrtmp = app.homePage.split("|")[0];
        } else {
          urlstrtmp = app.homePage;
        }
        return urlstrtmp;
      } else {
        var wxUserInfo = null;
        if (settings.env == "dev") {
          wxUserInfo = {
            nickName: "dev",
            password: "",
            openId: "testopenid",
            unionId: "testunionid",
            onlyCode: "testunionid",
            userName: "",
            headUrl: "/imgs/logo.png",
            appkey: state,
          }
        } else {
          //按照accessToken获取用户信息
          const userInfo = await this.getUserInfo(accessToken, openid);
          console.log("get userinfo...............");
          console.log(userInfo);

          wxUserInfo = {
            nickName: userInfo.nickname,
            password: "",
            openId: userInfo.openid,
            unionId: userInfo.unionid,
            onlyCode: userInfo.unionid,
            userName: "",
            headUrl: userInfo.headimgurl,
            sex: userInfo.sex == 1 ? "male" : "female",
            appkey: state,
          }
        }
        //创建用户信息
        var userRisgered = await this.service.loginWithoutGift(wxUserInfo);

        console.log("....userCtl...........................................userRisgered**************************************************************************************");
        console.log(userRisgered);
        userRisgered.partnerinfo = null;
        req.session.user = userRisgered;
        req.session.isNewUser = 1;
        //返回要跳转的具体应用的地址
        var app = await this.cacheManager["AppCache"].cacheApp(state);
        req.session.app = app;
        var urlstrtmp = "";

        if (app.homePage.indexOf("|") >= 0) {
          urlstrtmp = app.homePage.split("|")[0];
        } else {
          urlstrtmp = app.homePage;
        }
        return urlstrtmp;
      }
    } catch (e) {
      console.error(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 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": "testopenid",
        "scope": "SCOPE",
        "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
      }
      return rtn;
    }
  }
  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 patnerValid(qobj, pobj, req) {
    var user = await this.service.findOne({
      userName: pobj.userName
    });
    if (user && user.isPartner && !user.isAgreePartner) {
      return system.getResult2("1");
    }
    return system.getResult2("0");
  }

  async loginyd(req) {
    try {
      //日志记录
      logCtl.info({
        optitle: "userCtl--loginyD 参数信息",
        op: "base/controller/impl/userCtl/loginyd",
        content: JSON.stringify(req.query),
        clientIp: ""
      });
      // appId,userCode, branchCode
      var ecid = req.query.ecid || 0;
      var appkey = 'wxf616c0a459d66081';

      var userId = req.query.userId || "";
      var appId = req.query.appId || "";
      var userCode = req.query.userCode || "";
      var branchCode = req.query.branchCode || ecid;
      var openid3rd = req.query.openid || "";

      var userIdNo = (req.query.userIdNo || "").trim().toUpperCase();

      var accountInfo = {
        userName: decodeURI(req.query.userName || "") || "",
        mobile: req.query.userMobile || "",
        personsSign: userIdNo.toUpperCase(),
        bankno: req.query.userBankNo || "",
      }

      var domain = "http://bpohhr.gongsibao.com";
      var arr = [];
      if (!appId) {
        return domain + "/errpage?errmsg=" + encodeURIComponent(encodeURIComponent("未配置appId"));
      }

      var openId = "";
      if (userId) {
        openId = appId + "_3rduser_" + userId
      } else if (userCode && branchCode) {
        openId = appId + "_3rduser_" + userCode + "_3rduser_" + branchCode;
      } else if (userCode && !branchCode) {
        openId = appId + "_3rduser_" + userCode
      } else {
        return domain + "/errpage?errmsg=" + encodeURIComponent(encodeURIComponent("用户唯一标识未传入"));
      }

      //默认进入的子页面
      var action = "?from=ydh5";
      var app = await this.cacheManager["AppCache"].cacheApp(appkey);

      var existedUser = await this.service.getUserByOpenId(openId, appkey);
      if (existedUser) {
        var ydu = await this.service.findById(existedUser.id);
        ydu.openid3rd = openid3rd;
        await ydu.save();
        existedUser.openid3rd = openid3rd;

        req.session.user = existedUser;
        req.session.app = app;
        var accountId = await this.cache3rdAccount(existedUser.id, accountInfo);
        var url = app.homePage + action;
        if (accountId) {
          url = url + "&accid=" + accountId;
        }
        url = url + "&ecid=" + ecid;
        url = url + "&openid=" + openId + "&appkey=" + appkey;
        url = url + "&userid=" + existedUser.id;
        return url;
      }

      var wxUserInfo = {
        userName: "",
        nickName: "",
        password: "",
        openId: openId,
        unionId: openId,
        onlyCode: openId,
        headUrl: "",
        appkey: appkey,
        appId3rd: appId,
        userId3rd: userId,
        userCode3rd: userCode,
        branchCode3rd: branchCode,
        openid3rd: openid3rd,
      }
      existedUser = await this.service.loginWithoutGift(wxUserInfo);
      if (!existedUser) {
        return domain + "/errpage?errmsg=" + encodeURIComponent(encodeURIComponent("创建帐号不成功"));
      }
      req.session.user = existedUser;
      req.session.app = app;
      var accountId = await this.cache3rdAccount(existedUser.id, accountInfo);
      var url = app.homePage + action;
      if (accountId) {
        url = url + "&accid=" + accountId;
      }
      url = url + "&ecid=" + ecid;
      url = url + "&userid=" + existedUser.id;
      return url;
    } catch (e) {
      console.log(e);
      //日志记录
      logCtl.info({
        optitle: "userCtl--loginyD 异常 error",
        op: "base/controller/impl/userCtl/loginyd",
        content: e.stack,
        clientIp: ""
      });
    }
  }


  async loginyd2(req) {
    try {
      //日志记录
      logCtl.info({
        optitle: "userCtl--loginyD 参数信息",
        op: "base/controller/impl/userCtl/loginyd",
        content: JSON.stringify(req.query),
        clientIp: ""
      });
      // appId,userCode, branchCode
      var ecid = req.query.ecid || 0;
      var appkey = 'wxf616c0a459d66081';

      var userId = req.query.userId || "";
      var appId = req.query.appId || "";
      var userCode = req.query.userCode || "";
      var branchCode = req.query.branchCode || ecid;

      var userIdNo = (req.query.userIdNo || "").trim().toUpperCase();

      var accountInfo = null;
      if (userIdNo) {
        accountInfo = {
          userName: decodeURI(req.query.userName || "") || "",
          mobile: req.query.userMobile || "",
          personsSign: userIdNo.toUpperCase(),
          bankno: req.query.userBankNo || "",
        }
      }

      var domain = "http://bpohhr.gongsibao.com";
      var arr = [];
      if (!appId) {
        return domain + "/errpage?errmsg=" + encodeURIComponent(encodeURIComponent("未配置appId"));
      }

      var openId = "";
      if (userId) {
        openId = appId + "_3rduser_" + userId
      } else if (userCode && branchCode) {
        openId = appId + "_3rduser_" + userCode + "_3rduser_" + branchCode;
      } else if (userCode && !branchCode) {
        openId = appId + "_3rduser_" + userCode
      } else {
        return domain + "/errpage?errmsg=" + encodeURIComponent(encodeURIComponent("用户唯一标识未传入"));
      }

      //默认进入的子页面
      var action = "?from=ydh5";
      var app = await this.cacheManager["AppCache"].cacheApp(appkey);

      var homepage = "https://bpohhr.gongsibao.com/h5yd";
      var existedUser = await this.service.getUserByOpenId(openId, appkey);
      if (existedUser) {
        await this.cache3rdAccount(existedUser.id, accountInfo);
        var url = homePage + action;
        url = url + "&uid=" + existedUser.id + "&ecid=" + ecid;
        return url;
      }

      var wxUserInfo = {
        userName: "",
        nickName: "",
        password: "",
        openId: openId,
        unionId: openId,
        onlyCode: openId,
        headUrl: "",
        appkey: appkey,
        appId3rd: appId,
        userId3rd: userId,
        userCode3rd: userCode,
        branchCode3rd: branchCode,
      }
      existedUser = await this.service.loginWithoutGift(wxUserInfo);
      if (!existedUser) {
        return domain + "/errpage?errmsg=" + encodeURIComponent(encodeURIComponent("创建帐号不成功"));
      }
      req.session.user = existedUser;
      req.session.app = app;
      var accountId = await this.cache3rdAccount(existedUser.id, accountInfo);
      var url = app.homePage + action;
      url = url + "&uid=" + existedUser.id + "&ecid=" + ecid;
      return url;
    } catch (e) {
      //日志记录
      logCtl.info({
        optitle: "userCtl--loginyD 异常 error",
        op: "base/controller/impl/userCtl/loginyd",
        content: e.stack,
        clientIp: ""
      });
    }
  }

  async login3rd(req) {
    // appId,userCode, branchCode
    var ecid = req.query.ecid || 0;
    var appkey = 'wxf616c0a459d66081';
    var legal = req.query.legal || "";

    var userId = req.query.userId || "";
    var appId = req.query.appId || "";
    var userCode = req.query.userCode || "";
    var branchCode = req.query.branchCode || ecid;

    var userIdNo = (req.query.userIdNo || "").trim().toUpperCase();

    var accountInfo = null;
    if (userIdNo) {
      accountInfo = {
        userName: decodeURI(req.query.userName) || "",
        mobile: req.query.userMobile || "",
        personsSign: userIdNo.toUpperCase(),
        bankno: req.query.userBankNo || "",
      }
    }

    var domain = "https://bpohhr.gongsibao.com";
    var arr = [];
    if(ecid == 10460 || ecid == 10288) {
      return domain + "/errpage?errmsg=" + encodeURIComponent(encodeURIComponent("链接已失效"));
    }
    if (!appId) {
      return domain + "/errpage?errmsg=" + encodeURIComponent(encodeURIComponent("未配置appId"));
    }

    var openId = "";
    if (userId) {
      openId = appId + "_3rduser_" + userId
    } else if (userCode && branchCode) {
      openId = appId + "_3rduser_" + userCode + "_3rduser_" + branchCode;
    } else if (userCode && !branchCode) {
      openId = appId + "_3rduser_" + userCode
    } else {
      openId = appId + "_" + uuidv4();
      // return domain + "/errpage?errmsg=" + encodeURIComponent(encodeURIComponent("用户唯一标识未传入"));
    }

    var homePage = settings.apiconfig.sign3rdHomePage();
    //默认进入的子页面
    var action = "?from=3rdh5";
    var app = await this.cacheManager["AppCache"].cacheApp(appkey);

    var existedUser = await this.service.getUserByOpenId(openId, appkey);
    if (existedUser) {
      req.session.user = existedUser;
      req.session.app = app;
      var accountId = await this.cache3rdAccount(existedUser.id, accountInfo);
      var url = homePage + action;
      url = url + "&ecid=" + ecid;
      if(legal){
        url = url + "&legal="+legal;
      }
      return url;
    }

    var wxUserInfo = {
      userName: "",
      nickName: "",
      password: "",
      openId: openId,
      unionId: openId,
      onlyCode: openId,
      headUrl: "",
      appkey: appkey,
      appId3rd: appId,
      userId3rd: userId,
      userCode3rd: userCode,
      branchCode3rd: branchCode,
    }
    existedUser = await this.service.loginWithoutGift(wxUserInfo);
    req.session.user = existedUser;
    req.session.app = app;
    var accountId = await this.cache3rdAccount(existedUser.id, accountInfo);
    var url = homePage + action;
    url = url + "&ecid=" + ecid;
    if(legal){
      url = url + "&legal="+legal;
    }
    return url;
  }

  async cache3rdAccount(userId, accountInfo) {
    if (!userId || !accountInfo) {
      return "";
    }
    await this.redisClient.setWithEx("yd_user_" + userId, JSON.stringify(accountInfo), 30 * 60);
    return 1;
  }

  async get3rdAccount(qobj, pobj, req) {
    var accountInfo = await this.redisClient.get("yd_user_" + req.session.user.id);
    if (accountInfo && accountInfo != 'undefined') {
      return system.getResult2(JSON.parse(accountInfo));
    }
    return system.getResult2({});
  }

  async updateSigner(qobj, pobj, req) {
    var userid;
    if (req && req.session && req.session.user) {
      pobj.onlyCode = req.session.user.unionId;
      pobj.id = req.session.user.id;
      userid = req.session.user.id;
    }
    if (req.codepath) {
      pobj.codepath = req.codepath;
    }

    if(!userid) {
      userid = req.headers.referer.substr(req.headers.referer.indexOf('userid') + 7);
    }
    // var loginUser = await this.service.findById(userid);
    //var loginUser = await this.service.findById(req.session.user.id);
    pobj.personsSign = pobj.personsSign.toUpperCase();
    let uep = {
      personsSign: pobj.personsSign
    }
    if (userid) {
      uep.user_id = userid;
    }
    // 获取该身份证帐号信息
    var eaccount = await this.usereaccountSve.findOne(uep);
    // 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 = {
        mobile: pobj.mobile,
        userName: pobj.userName,
        personsSign: pobj.personsSign,
        bankno: pobj.bankno,
        eaccountid: "",
        email: "",
        user_id: userid,
        //user_id: req.session.user.id,
        isPush: false,
      };
      eaccount = await this.usereaccountSve.create(eaccount);

    } else {
      bool = true;
    }

    if(pobj.legal){
      var usereaccountextend = await this.usereaccountextendSve.findOne({id:eaccount.id});
      if(!usereaccountextend){
        usereaccountextend = {};
        usereaccountextend.id = eaccount.id;
        usereaccountextend.zfb_no = pobj.zfb_no;
        usereaccountextend.company_fullname = pobj.company_fullname;
        usereaccountextend.bank_fullname = pobj.bank_fullname;
        this.usereaccountextendSve.create(usereaccountextend);
      }else {
        usereaccountextend.zfb_no = pobj.zfb_no;
        usereaccountextend.company_fullname = pobj.company_fullname;
        usereaccountextend.bank_fullname = pobj.bank_fullname;
        usereaccountextend.save();
      }
    }
    if (!bool || !eaccount.eaccountid || (eaccount.userName != pobj.userName || eaccount.personsSign != pobj.personsSign || eaccount.bankno != pobj.bankno)) {
      var bankthreeParams = {
        name: pobj.userName, //姓名 必填
        idno: pobj.personsSign, //身份证 必填
        cardno: pobj.bankno //银行卡 必填
      };


      let exists = await this.bankthreelogSve.findOne({
        userName: pobj.userName,
        userIdNo: pobj.personsSign,
        userBankNo: pobj.bankno,
        result: 1,
      });

      if (!exists) {
        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);
        }

        await this.bankthreelogSve.create({
          appId: "H5_"+eaccount.id,
          userName: pobj.userName,
          userIdNo: pobj.personsSign,
          userBankNo: pobj.bankno,
          use_esign: true,
          result: 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
      eaccount.isPush = false;
    }

    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 sendEmailCode(qobj, pobj, req) {
    var email = pobj.email;
    if (!email) {
      return system.getErrResult2("邮箱错误");
    }
    var captcha = pobj.captcha || "";
    if (!captcha) {
      return system.getErrResult2("图形验证码错误");
    }

    var rcaptcha = await this.redisClient.get("captcha_" + pobj.emailKey) || "";
    if (rcaptcha.toLowerCase() != captcha.toLowerCase()) {
      await this.redisClient.delete("captcha_" + pobj.emailKey);
      return system.getErrResult2("验证码错误, 请刷新重试");
    }

    var vcode = await this.service.getUidStr(6, 10);
    await this.redisClient.setWithEx("email_" + email, vcode, 30 * 60);

    var to = email;
    var title = '薪必果验证码';
    var text = null;
    var html = '薪必果验证码为: <span style="color:red"> ' + vcode + ' </span> （30分钟有效期，切勿将验证码告知他人，请在页面中输入完成验证）';
    var cc = null;
    var bcc = null;
    var atts = [];

    try {
      console.log(to, title, text, html, cc, bcc, atts);
      var result = await this.mailClient.sendMsg(to, title, text, html, cc, bcc, atts) //发送成功后result的值:250 Data Ok: queued as freedom
      console.log(result);
      if (result.indexOf("Ok") >= 0) {
        return system.getResult2(1);
      } else {
        return system.getErrResult2("发送失败");
        logCtl.info({
          optitle: "发送邮件验证错误",
          op: "base/controller/impl/userCtl.js",
          content: "html=" + html + ", result=" + JSON.stringify(result),
          clientIp: ""
        });
      }
    } catch (e) {
      console.log(e);
      return system.getErrResult2("发送异常");
      logCtl.info({
        optitle: "发送邮件验证异常",
        op: "base/controller/impl/userCtl.js",
        content: "html=" + html,
        clientIp: ""
      });
    }
  }

  async saveEmail(qobj, pobj, req) {
    var email = pobj.email;
    if (!email) {
      return system.getErrResult2("邮箱错误");
    }
    var vcode = pobj.vcode || "";
    if (!vcode) {
      return system.getErrResult2("邮件验证码错误, 请重试");
    }
    var code = await this.redisClient.get("email_" + email) || "";
    if (vcode.toLowerCase() != code.toLowerCase()) {
      return system.getErrResult2("邮件验证码错误, 请重试");
    }

    var user = await this.service.findById(req.session.user.id);

    user.email = email;
    await user.save();

    req.session.user.email = email;
    return system.getResult2(1);
  }

  async sendSMSCode(qobj, pobj, req) {
    var mobile = pobj.mobile;
    if (!mobile) {
      return system.getErrResult2("手机号码错误");
    }
    var valid = await this.redisClient.get("mobile_send_" + mobile) || "";
    if (valid) {
      return system.getErrResult2("您验证码发送的过于频繁, 请稍后重试");
    }

    var captcha = pobj.captcha || "";
    if (!captcha) {
      return system.getErrResult2("图形验证码错误");
    }

    var rcaptcha = await this.redisClient.get("captcha_" + pobj.captchaKey) || "";
    if (rcaptcha.toLowerCase() != captcha.toLowerCase()) {
      await this.redisClient.delete("captcha_" + pobj.captchaKey);
      return system.getErrResult2("验证码错误, 请刷新重试");
    }

    var vcode = await this.service.getUidStr(6, 10);
    var message = '薪必果验证码为: ' + vcode + '（30分钟有效期，切勿将验证码告知他人，请在页面中输入完成验证）';
    await this.smsS.sendMsg(mobile, message);
    await this.redisClient.setWithEx("mobile_" + mobile, vcode, 30 * 60);
    await this.redisClient.setWithEx("mobile_send_" + mobile, "valid", 60);

    return system.getResult2(1);
  }

  async savePwd(qobj, pobj, req) {
    var mobile = pobj.mobile;
    if (!mobile) {
      return system.getErrResult2("手机号码错误");
    }

    var password = pobj.passwd;
    var passwdConfirm = pobj.passwdConfirm;
    if (!password) {
      return system.getErrResult2("请输入密码");
    }

    if (password.length < 6) {
      return system.getErrResult2("您输入的密码位数太少");
    }

    if (password != passwdConfirm) {
      return system.getErrResult2("两次密码输入不一致");
    }

    var vcode = pobj.vcode || "";
    if (!vcode) {
      return system.getErrResult2("手机验证码错误, 请重试");
    }

    var code = await this.redisClient.get("mobile_" + mobile) || "";
    if (vcode.toLowerCase() != code.toLowerCase()) {
      return system.getErrResult2("手机验证码错误, 请重试");
    }

    var user = await this.service.findById(req.session.user.id);
    user.password = this.encryptPasswd(pobj.passwd);
    await user.save();
    return system.getResult2(1);
  }

  async saveCompanyForget(qobj, pobj, req) {
    var mobile = pobj.mobile;
    if (!mobile) {
      return system.getErrResult2("手机号码错误");
    }

    var password = pobj.passwd;
    if (!password) {
      return system.getErrResult2("请输入密码");
    }

    if (password.length < 6) {
      return system.getErrResult2("您输入的密码位数太少");
    }

    var vcode = pobj.vcode || "";
    if (!vcode) {
      return system.getErrResult2("手机验证码错误, 请重试");
    }

    var code = await this.redisClient.get("mobile_" + mobile) || "";
    if (vcode.toLowerCase() != code.toLowerCase()) {
      return system.getErrResult2("手机验证码错误, 请重试");
    }

    var user = await this.service.findOne({
      mobile: mobile
    });
    if (!user) {
      return system.getErrResult2("用户不存在");
    }
    user.password = this.encryptPasswd(pobj.passwd);
    await user.save();
    return system.getResult2(1);
  }

  async rolesSuggest(qobj, pobj, req) {
    var name = this.trim(pobj.name);
    var roleCodes = pobj.roleCodes || [];
    if (!name || roleCodes.length == 0) {
      return system.getResult2([]);
    }

    try {
      var list = await this.service.suggestByRoleCodes(name, roleCodes, pobj.limit || 10);
      return system.getResult2(list);
    } catch (error) {
      console.log(error);
      return system.getResult2([]);
    }

  }
}
module.exports = UserCtl;
