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.utilesignbaoSve = system.getObject("service.utilesignbaoSve");

    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 appKey = this.trim(obj.appKey);
      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,
          account_biz_id: accountId,
          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",
          appKey: appKey
        },
      });
      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: false
      });
    } catch (e) {
      console.log("innerApi-autoSign error", e.stack);
      return this.errorTip(e.name);
    } finally {
      if (key && val) {
        // 解锁
        await this.redisLock.unLock(key, val);
      }
    }
  }

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

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

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

      await this.redisLock.lock(key, val, 20);

      // 3. 签约
      let res = await this.dkcontractSve.appHandSign({
        ecid: etemplateBusi.template_id,
        usereaccountId: accountId,
        forceFace: false,
        notifyUrl: notifyUrl,
        noticeUrl: "https://bpohhr.gongsibao.com/api/innerApi/appHandSignNotice",
        callbackUrl: obj.callbackUrl || "https://bpohhr.gongsibao.com/blank",
        appKey: appKey
      });

      if (res.status === 0) {
        let contract = res.data.contract;
        return system.getResult2({
          contractId: contract.id,
          accountId: accountId,
          mchtId: mchtId,
          signUrl: contract.esignUrl
        });
      }
      return res;
    } 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 testNotifyUrl(params) {
    console.log("----------------testNotifyUrl----------------", params);
  }

  async appHandSignNotice(params) {
    if (!this.checkNoticeParams(params)) {
      return;
    }
    try {
      // 更新合同状态
      let contract = await this.dkcontractSve.updateCallbackStatus(params);
      // 归档
      await this.utilesignbaoSve.archiveProcess(params, "innerApi.appHandSignNotice");

      // 推送
      if (contract.notify_url) {
        try {
          let notifyResult = await axios({
            method: 'post',
            url: contract.notify_url,
            headers: {
              'XAPPKEY': "8cf88fdf-86f2-4f21-8799-acb4eda9d207",
              'x-app-key': "8cf88fdf-86f2-4f21-8799-acb4eda9d207",
            },
            data: {
              contractId: contract.id,
              accountId: contract.usereaccount_id,
              eflowstatus: contract.eflowstatus,
            },
          });
          console.log(`-----innerApi.appHandSignNotice.notify_url---------`, contract.id, notifyResult);
        } catch (e) {
          console.log(`-----innerApi.appHandSignNotice.notify_url--exception-------`, contract.id, e.stack);
        }
      }
      console.log(params);
    } catch (e) {
      console.log(`------innerApi.js----appHandSignNotice----exception-----`, e.stack);
    }

    // {
    //   "action": "SIGN_FLOW_UPDATE",
    //   "flowId": "002d788293274f168400138920b7a710",
    //   "accountId": "120853bb59d74496b01ae03a7dbaeaf7",
    //   "signTime": "2020-09-30 13:37:51",
    //   "signResult": 2,
    //   "serialNumber": "dk_4218",
    //   "thirdOrderNo": "dk_4218",
    //   "resultDescription": "执行成功"
    // }
  }

  checkNoticeParams(params) {
    let actions = ['SIGN_FLOW_UPDATE', "SIGN_FLOW_FINISH"];
    console.log(`------------innerApi.js--------------checkNoticeParams-------------${params.action}----------params--`);
    if (actions.indexOf(params.action) == -1) {
      console.log(`------------innerApi--------------checkNoticeParams-------------${params.action}----------action错误--`);
      return 0;
    }
    if (!params.flowId) {
      console.log(`------------innerApi--------------checkNoticeParams-------------${params.flowId}----------flowId错误--`);
      return 0;
    }
    if (!params.thirdOrderNo) {
      console.log(`------------innerApi--------------checkNoticeParams-------------${params.thirdOrderNo}----------thirdOrderNo错误--`);
      return 0;
    }
    return 1;
  }

  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;