const system = require("../../system")
const md5 = require("md5");
const moment = require("moment");
const axios = require("axios");

class TDEVApi {
  constructor() {

    this.cwxsignapiSve = system.getObject("service.cwxsignapiSve");
    this.redisClient = system.getObject("util.redisClient");

    this.cwxsigninfoSve = system.getObject("service.cwxsigninfoSve");

    this.utilesignbaoSve = system.getObject("service.utilesignbaoSve");

    this.ecompanySve = system.getObject("service.ecompanySve");
    this.etemplateSve = system.getObject("service.etemplateSve");
    this.econtractSve = system.getObject("service.econtractSve");

    this.dkcompanySve = system.getObject("service.dkcompanySve");
    this.dktemplateSve = system.getObject("service.dktemplateSve");
    this.dkcontractSve = system.getObject("service.dkcontractSve");
    this.redisLock = system.getObject("util.redisLock");


    this.EXCEPT_KEYS = ['sign', 'idName'];
  }

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

  async doAuth(params, api) {
    // auth_type 认证类型 0无认证 1姓名二要素 2银行卡三要素 3银行卡四要素
    let res;
    // 姓名二要素
    res = await this.bankthreelogSve.personTwo({
      appId: "sdpj_sign_" + api.app_id,
      userName: params.idName,
      userIdNo: params.idNo
    });
    return res;
  }

  async doSign3(cashInfo, params) {
    let result;
    // 专票签（三方签）
    let signParam = {
      ecid: this.trim(cashInfo.ecid),
      appId: this.trim(cashInfo.app_id),
      userId: this.trim(cashInfo.id_no),
      idName: this.trim(cashInfo.id_name),
      idNo: this.trim(cashInfo.id_no),
    };
    try {
      let key = `${cashInfo.mcthId}_${cashInfo.outTradeNo}`;
      let id = uuidv1();
      await this.redisLock.lock(key, id, 20);
      let result = await this.econtractSve.autoSignBankTwo(param);
      await this.redisLock.unLock(key, id);
      return result;
    } catch (e) {
      console.log(e, cashInfo, "-----------------------签约异常-----------------------");
      return {code: 1, msg: "签约异常"};
    }
  }

  async cashOut(cashInfo) {
    // 发起交易
    let bizContent = [];
    bizContent.push({
      "note": "提现",
      "idType": "00",
      "idName": cashInfo.id_name,
      "seqNo": cashInfo.id,
      "accNo": cashInfo.openId,
      "amt": cashInfo.amt,
      "accType": "00",
      "idNo": cashInfo.id_no
    });
    let nonceStr = await this.getUidStr(32, 36);
    let tradeTime = moment().format('YYYYMMDDHHmmss');
    var param = {
      "appId": cashInfo.appId,
      "currency": "CNY",
      "mchtId": cashInfo.mchtId,
      "nonceStr": nonceStr,
      "notityUrl": "https://bpohhr.gongsibao.com/api/econtractApi/transferNotify",
      "outTradeNo": cashInfo.outTradeNo,
      "signType": "MD5",
      "tradeTime": tradeTime,
      "bizContent": bizContent,
    }

    // now
    let signArr = [];
    signArr.push("appId=" + param.appId);
    signArr.push("currency=" + param.currency);
    signArr.push("mchtId=" + param.mchtId);
    signArr.push("nonceStr=" + param.nonceStr);
    signArr.push("notityUrl=" + param.notityUrl);
    signArr.push("outTradeNo=" + param.outTradeNo);
    signArr.push("signType=" + param.signType);
    signArr.push("tradeTime=" + param.tradeTime);
    signArr.push("key=" + mcht.secret);
    param.sign = md5(signArr.join("&")).toUpperCase();
    console.log(JSON.stringify(param));

    try {
      let rs = await axios({
        method: 'post',
        url: "https://pay.gongsibao.com/merchant/order/transfer",
        data: param,
      });
      if (rs.data.code === 0) {
        trade.trade_status = "00";
        return system.getResult2("提现成功");
      }
      console.log(rs.data);
      return system.getErrResult2(rs.data.msg);
    } catch (error) {
      console.log(error);
      // 发起失败，删除trade
    }
  }

  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('');
  }
}

module.exports = TDEVApi;
