const system = require("../../system")
const settings = require("../../../config/settings");

const uuidv4 = require('uuid/v4');
const axios = require("axios");

class innerApi {
  constructor() {
    this.redisClient = system.getObject("util.redisClient");
    this.redisLock = system.getObject("util.redisLock");


    this.userSve = system.getObject("service.userSve");
    this.usereaccountSve = system.getObject("service.usereaccountSve");

    this.idcardClient = system.getObject("util.idcardClient");
    this.esettleSve = system.getObject("service.esettleSve");
    this.dkcontractSve = system.getObject("service.dkcontractSve");
    this.etemplatebusiSve = system.getObject("service.etemplatebusiSve");
    this.bankthreelogSve = system.getObject("service.bankthreelogSve");

  }

  async valid(obj, req) {
    console.log("inner api valid", obj);
    if (obj.error == 1) {
      throw new Error("valid-error");
    }
    // if (!obj.mchtId) {
    //   throw new Error("mchtId-empty");
    // }
  }

  /**
   * 银行卡四要素验证
   * @param obj
   * @param req
   * @returns {Promise<{msg: string, data: *, status: number}>}
   */
  async bankFour(obj, req) {
    let idName, idNo, bankNo, mobile, val, key;
    try {
      await this.valid(obj, req);
      idName = this.trim(obj.idName);
      idNo = this.trim(obj.idNo);
      bankNo = this.trim(obj.bankNo);
      mobile = this.trim(obj.mobile);
      val = uuidv4();
      key = `bpo_app_1_${idNo}`;

      // 加锁
      await this.redisLock.lockNoWait(key, val, 20);

      // 封装参数
      let appId = "bpo_app_1_";

      let unionId = key;
      let userInfo = {
        unionId: unionId,
        appId: appId,
        appKey: appId,
        userName: idName,
        userIdNo: idNo,
        userBankNo: bankNo,
        userMobile: mobile,
        utype: 0,
      };
      // 1. 四要素认证
      let authRes = await this.bankthreelogSve.bankFour(userInfo);
      if (authRes.status != 0 || !authRes.data || !authRes.data.pass) {
        return system.getErrResult2("身份认证失败，请检查姓名、身份证、银行卡号、银行预留手机号是否正确");
      }

      // 2. user和user_eaccount逻辑
      let userObj = await this.userSve.userAndEaccount4InnerApi(userInfo);

      // 3. 创建e签宝账号
      let esignRes = await this.usereaccountSve.createEsignAccount({
        accountId: userObj.account.id,
        prev: `bpo_app_1_${userObj.account.user_id}_`,
        isGrantAuto: true
      });
      if (!esignRes) {
        return system.getErrResult2("创建签约账户失败, 请重试");
      }

      return system.getResult2({
        accountId: userObj.account.id,
        idName: idName,
        idNo: idNo,
        bankNo: bankNo,
        mobile: mobile,
      });
    } catch (e) {
      console.log("innerApi-bankFour error", e.stack);
      return this.errorTip(e.name);
    } finally {
      if (key && val) {
        // 解锁
        await this.redisLock.unLock(key, val);
      }
    }
  }

  /**
   * 人脸识别
   * @param obj
   * @param req
   * @returns {Promise<void>}
   */
  async appFaceAuth(obj, req) {
    try {
      let accountId = this.trim(obj.accountId);
      let account = await this.usereaccountSve.findById(accountId);
      if (!account) {
        return system.getErrResult2("账户不存在");
      }
      if (!obj.notifyUrl) {
        return system.getErrResult2("请传入notifyUrl[识别结果通知地址]");
      }
      let authRes = await axios({
        method: 'post',
        url: settings.signApi().personaAuthlFace,
        data: {
          accountId: account.eaccountid,
          callbackUrl: obj.callbackUrl || "https://bpohhr.gongsibao.com/blank",
          notifyUrl: obj.notifyUrl || "https://bpohhr.gongsibao.com/api/econtractApi/transferNotify",
          // sysNotifyUrl: "https://bpohhr.gongsibao.com/api/econtractApi/transferNotify",
          sysNotifyUrl: "https://bpohhr.gongsibao.com/api/innerApi/faceAuthNotify",
        },
      });
      authRes = authRes.data;
      if (authRes.status == 0) {
        return system.getResult2(authRes.data);
      }
      authRes.status = -1;
      return authRes;
    } catch (e) {
      console.log(e);
      return system.getErrResult2("操作异常" + e.stack);
    }
  }

  async faceAuthNotify(obj, req) {
    console.log("faceNotify---begin-------------", obj);
    if (!obj || !obj.flowId) {
      return;
    }

    let authRes = await axios({
      method: 'post',
      url: settings.signApi().personalAuthCallBack,
      data: obj,
    });
    if (authRes && authRes.data && authRes.data.status === 0) {
      let acc = authRes.data.data;
      if (!acc) {
        return system.getErrResult2("数据错误");
      }
      let eaccount = await this.usereaccountSve.findOne({eaccountid: acc.account_id});
      eaccount.face_auth_img = acc.face_img;
      await eaccount.save();
    }
    console.log("faceNotify---result-------------", authRes);
    return 1;
  }

  /**
   * 静默签
   * @param obj
   * @param req
   * @returns {Promise<{msg: string, data: *, status: number}>}
   */
  async appAutoSign(obj, req) {
    let mchtId, accountId, val, key;
    try {
      await this.valid(obj, req);
      accountId = this.trim(obj.accountId);
      mchtId = this.trim(obj.mchtId);
      key = `${mchtId}_${accountId}`;
      val = uuidv4();

      if (!accountId) {
        return system.getErrResult2("缺少accountId");
      }
      if (!mchtId) {
        return system.getErrResult2("缺少商户id");
      }

      // 1.获取签约模板id，张娇保证一个商户只有一个模板id
      let etemplateBusi = await this.etemplatebusiSve.findOne({busi_id: mchtId});
      if (!etemplateBusi || !etemplateBusi.template_id) {
        return system.getErrResult2("配置信息错误，请联系薪必果人员进行配置");
      }

      // 2. 签约
      await this.redisLock.lock(key, val, 20);

      // 3. 签约
      return await this.dkcontractSve.appAutoSign({
        ecid: etemplateBusi.template_id,
        usereaccountId: accountId,
        forceFace: true
      });
    } catch (e) {
      console.log("innerApi-autoSign error", e.stack);
      return this.errorTip(e.name);
    } finally {
      if (key && val) {
        // 解锁
        await this.redisLock.unLock(key, val);
      }
    }
  }

  async signInfo(obj, req) {
    let contract = await this.dkcontractSve.findById(obj.contractId) || {};

    return system.getResult2({
      contractId: this.trim(contract.id),
      name: this.trim(contract.name),
      fileurl: this.trim(contract.fileurl),
      eflowstatus: this.trim(contract.eflowstatus),
    });
  }

  errorTip(name) {
    if (name == 'valid-error') {
      return system.getErrResult2("权限认证失败");
    } else if (name == "mchtId-empty") {
      return system.getErrResult2("商户id为空");
    }
    return system.getErrResult2(name);
  }

  trim(o) {
    if (!o) {
      return "";
    }
    return o.toString().trim();
  }

}

module.exports = innerApi;