var system = require("../../system")
const md5 = require("md5");

class BpoSDPJApi {
  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.EXCEPT_KEYS = ['sign'];

    this.ccashinfoSve =  system.getObject("service.ccashinfoSve");
    this.ecompanybusiSve =  system.getObject("service.ecompanybusiSve");
    this.qrClient = system.getObject("util.qrClient");
    this.idcardClient = system.getObject("util.idcardClient");
    this.esettleSve = system.getObject("service.esettleSve");
    this.tdevApi = require("./tdevApi");
    let resultMap = {
      0:"操作成功",
      1:"操作失败",
      1001001:"签名失败",
      1002001:"参数错误",
      500:"接口异常",
    }




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

  /**
   * 生成二维码
   * @param obj
   * @param req
   * @returns {Promise<{msg: string, code: number}>}
   */
  async cashQRCode(obj, req) {
    // 验证合法性
    // let p = {
    //   appId: this.trim(obj.appId),
    //   nonceStr: this.trim(obj.nonceStr),
    //   ecid: Number(obj.ecid || 0),
    //   idNo: this.trim(obj.idNo),
    // };
    //
    // let keys = Object.keys(p).sort();
    // let signArr = [];
    // for (let k = 0; k < keys.length; k++) {
    //   let tKey = keys[k];
    //   if (this.EXCEPT_KEYS.indexOf(tKey) == -1 && p[tKey]) {
    //     signArr.push(tKey + "=" + p[tKey]);
    //   }
    // }
    // let signStr = signArr.join("&") + "&key=" + api.app_secret;
    // let sign = md5(signStr).toUpperCase();
    // console.log(obj.sign, signStr, sign);
    //
    // if (sign != obj.sign) {
    //   return {
    //     code: 1001001,
    //     msg: "签名失败"
    //   };
    // }
    try {
      if(!obj || !obj.outTradeNo || !obj.mchtId){
        return this.getResult(1002001,null);
      }
      //1.mchtId & ecid 进行联合查询 如果存在直接返回
      let _cCashInfo = await  this.ccashinfoSve.getBean(obj);
      console.log(`bpoSDPJApi.js -> cashQRCode -> mchtId & ecid 进行联合查询 :参数=` + JSON.stringify(obj) + "  _cCashInfo = " + JSON.stringify(_cCashInfo));
      if(_cCashInfo){
        return this.getResult(1002001,null);
      }
      //2.检验所有参数是否完整 如果出现非法参数直接返回
      if(!obj.ecid || !obj.appId ||!obj.idNo || !obj.idName || !obj.amt){
        return this.getResult(1002001,null);
      }
      //3.获取签约类型
      let _ecompanybusi = await this.ecompanybusiSve.findOneByAppidMchtId({
        app_id: this.trim(obj.appId),
        mchtId: this.trim(obj.mchtId)
      });
      console.log("查看签约类型 _ecompanybusi=" + JSON.stringify(_ecompanybusi));
      if(!_ecompanybusi || !_ecompanybusi.hasOwnProperty("app_type")){
        return this.getResult(500,null);
      }
      let _ccashinfoProperty = {};

      _ccashinfoProperty.app_type = _ecompanybusi.app_type;
      _ccashinfoProperty.outTradeNo = obj.outTradeNo;
      _ccashinfoProperty.mchtId = obj.mchtId;
      _ccashinfoProperty.ecid = _ecompanybusobj;
      _ccashinfoProperty.app_id = obj.appId;
      _ccashinfoProperty.amt = Number(obj.amt || 0);
      _ccashinfoProperty.idName = this.trim(obj.idName) || "";
      _ccashinfoProperty.idNo = this.trim(obj.idNo) || "" ;

      //4.保存签约数据
      _cCashInfo = await this.ccashinfoSve.save(_ccashinfoProperty);
      if(!_cCashInfo){
        return this.getResult(500,null);
      }
      //5. 拼接h5 http连接 http//xxx?mchtId=xxx&ecid=xxx&no=id
      let _no = await this.setNo(_cCashInfo.id);
      let custormUrl = `http://bpohhr.gongsibao.com?no=${_no}&outTradeNo=${_cCashInfo.outTradeNo}&mchtId=${_cCashInfo.mchtId}`;
      //6.生成二维码
      let url =await this.qrClient.generateQR(custormUrl);
      return this.getResult(0,{"qrcode": url || ""});
    } catch (e) {
      let result = {
        code: 500,
        msg: "接口异常"
      };
      console.log(e.stack);
      return result;
    }
  }

  async setNo(no){
    return no;
  }

  async getNo(no) {
    return no;
  }

  /**
   * fn:验证商户是否可用
   * @returns {Promise<void>}
   */
  async verificationMtchOutTradeNo(obj, req){
    if(!obj || !obj.outTradeNo || !obj.mchtId || !obj.no){
      return this.getResult(1002001,null);
    }
    let no = await this.getNo(obj.no);
    try {
      let _cCashInfo = await  this.ccashinfoSve.getBean({
        id: no,
        outTradeNo: this.trim(obj.outTradeNo),
        mchtId: this.trim(obj.mchtId),
      });
      return this.getResult(0,{
        id_name:_cCashInfo.id_name,
        id_no:_cCashInfo.id_no,
        app_id: _cCashInfo.app_id,
        id:_cCashInfo.id
      })
    }catch (e) {
      console.log(e);
      let result = {
        code: 500,
        msg: "接口异常"
      };
      console.log(e.stack);
      return result;
    }
  }

  /**
   * fn:个人要素认证
   * @returns {Promise<void>}
   */
  async authentication(obj, req){
    if(!obj || !obj.id_name || !obj.id_no || !obj.mchtId || !obj.app_id|| !obj.id){
      return this.getResult(1002001,null);
    }
    try{
      if (!await this.idcardClient.checkIDCard(obj.id_no)) {
        return this.returnjson(-1, "身份证格式不正确");
      }

      let num = await this.esettleSve.isValidAge([obj.mchtId]);
      if(num) {
        let card = await this.idcardClient.cardInfo(obj.id_no);
        let age = card.age || 0;
        if(!age) {
          return this.returnjson(-1, "身份证号格式错误, 只支持18位身份证号码");
        }
        if(card.sex == 'male') {
          if (age < 18 || age > 60) {
            return this.returnjson(-1, "签约失败，男限制18-60岁之间")
          }
        } else {
          if (age < 18 || age > 55) {
            return this.returnjson(-1, "签约失败，女限制18-55岁之间")
          }
        }
      }

      let doAuthRes = await this.tdevApi.doAuth({idName:this.trim(obj.id_name),idNo:this.trim(obj.id_no)},{ app_id:obj.app_id});
      //异步推送信息
      pushAsync(obj);


    }catch (e) {
      console.log(e);
      let result = {
        code: 500,
        msg: "接口异常"
      };
      console.log(e.stack);
      return result;
    }
    
  }

  /**
   * fn:异步同送信息
   * @param params
   */
  pushAsync(params){



    /**
     * fn:签约
     */
    let res = this.tdevApi.doSign3(params);

    /**
     * fn:更新验证信息 人名 身份证号
     */
    this.ccashinfoSve.update(params);

  }

  /**
   * fn:打开红包
   * @param obj
   */
  openRedEnvelopes(obj){

  }




  getResult(code,data={},other={}){
    let res = {
      "code": code,
      "msg": this.resultMap[code] || "",
      "data": data
    }
    for (let ele in other) {
      res[ele] = other[ele];
    }
    return res;
  }

}
module.exports = BpoSDPJApi;
