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

class BpWXSignApi {
  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', 'idName'];
  }
  trim(o) {
    if(!o) {
      return "";
    }
    return o.toString().trim();
  }

  async getSignedUser(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 api = await this.cwxsignapiSve.findOne({app_id: p.appId, ecid: p.ecid});
    if (!api) {
      return {
        code: 1001003,
        msg: "配置信息错误，请联系薪必果人员进行配置"
      };
    }

    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 (api.app_type == 1) {
        let user = await this.dkcontractSve.findSingleSignedUser({
          dktemplate_id: p.ecid,
          idNo: p.idNo.toUpperCase(),
        });
        let result = {
          code: 0,
          msg: "success",
          data: user
        };
        return result;
      } else {
        return {
          code: -1,
          msg: "暂未提供，工程师正在紧急加班开发"
        };
      }
    } catch (e) {
      let result = {
        code: 500,
        msg: "接口异常"
      };
      console.log(e.stack);
      return result;
    }
  }

}
module.exports = BpWXSignApi;
