var system = require("../../system")
const md5 = require("MD5");
const logCtl = system.getObject("web.oplogCtl");
class EcontractApi {
  constructor() {
    this.ecompanySve = system.getObject("service.ecompanySve");
    this.econtractSve = system.getObject("service.econtractSve");
    this.etemplateSve = system.getObject("service.etemplateSve");
    
    this.restClient = system.getObject("util.restClient");
  }

  async importECompany(obj) {
    console.log(obj, "===================>>>>>>>>>>>>>>>>>>>>>");
    var names = obj.companyNames;
    var nameA = obj.nameA || '智信云（天津）科技有限公司';
    var encryptkey = obj.encryptkey;
    var posturl = obj.posturl;
    var etemplate = await this.etemplateSve.findById(Number(obj.etemplateId || 0));
    if (!etemplate) {
      return 0;
    }

    for (var name of names) {
      try {
        console.log("========== import ecompany : " + name);
        let rs = await this.ecompanySve.importCompany(name, nameA, encryptkey, posturl, etemplate);
      } catch (e) {
        console.log(e);
      }
    }
    return 1;
  }

  async validContract(obj, req) {
    // 验证合法性
    var companyName = obj.companyName;
    var idCardList = obj.idCardList;

    var sign = md5("companyName=" + companyName + "&nonceStr=" + obj.nonceStr + "&key=wxdc08c441c9fdb7a7").toUpperCase();
    if (sign != obj.sign) {
      return {
        code: 1,
        msg: "签名失败"
      };
    }

    //日志记录
    if (!idCardList || idCardList.length == 0) {
      return {
        code: 0,
        msg: "success",
        signedList: [],
        unSignList: []
      };
    }

    var ecompany = await this.ecompanySve.findOne({
      name: companyName
    });
    if (!ecompany) {
      return {
        code: 1,
        msg: "公司不存在"
      };
    }

    try {
      var signedList = await this.econtractSve.fiterSignedCards(ecompany.id, idCardList);
      var unSignList = [];
      for (var ic of idCardList) {
        if (signedList.indexOf(ic) == -1) {
          unSignList.push(ic);
        }
      }
      var result = {
        code: 0,
        msg: "success",
      };
      result.signedList = signedList;
      result.unSignList = unSignList;
      return result;
    } catch (e) {
      var result = {
        code: 500,
        msg: "接口异常"
      };
      console.log(e.stack);
      //日志记录
      logCtl.error({
        optitle: "校验是否签约error",
        op: "api/econtractApi/validContract",
        content: e.stack,
        clientIp: req.clientIp
      });
      return result;
    }
  }


  async sinedList(obj, req) {
    // 验证合法性
    var companyName = obj.companyName;
    var startId = obj.startId || 0;
    var pageSize = obj.pageSize || 20;

    var sign = md5("companyName=" + companyName + "&nonceStr=" + obj.nonceStr + "&startId=" + startId + "&key=wxdc08c441c9fdb7a7").toUpperCase();
    if (sign != obj.sign) {
      return {
        code: 1,
        msg: "签名失败"
      };
    }

    var ecompany = await this.ecompanySve.findOne({
      name: companyName
    });
    if (!ecompany) {
      return {
        code: 1,
        msg: "公司不存在"
      };
    }

    try {
      var userList = await this.econtractSve.findSignedUsers(ecompany.id, startId, pageSize);

      var result = {
        code: 0,
        msg: "success",
      };
      result.data = userList;
      return result;
    } catch (e) {
      var result = {
        code: 500,
        msg: "接口异常"
      };
      console.log(e.stack);
      //日志记录
      logCtl.error({
        optitle: "校验是否签约error",
        op: "api/econtractApi/validContract",
        content: e.stack,
        clientIp: req.clientIp
      });
      return result;
    }
  }

  async dosync(obj, req) {
    // TODO 需要验证一下合法
    this.econtractSve.syncAllSigners();
    return 1;
  }

  async transfer(obj, req) {
    var item = {
      "appId": "10000000000",
      "currency": "CNY",
      "notityUrl": "https://ec.gongsibao.com/api/econtractApi/transferNotify",
      "mchtId": "1",
      "nonceStr": "nonceStrnonceStr",
      "outTradeNo": "2770333475",
      "signType": "MD5",
      "tradeTime": "20190310152415",
      "bizContent": [{
          "note": "",
          "idType": "00",
          "idName": "符伟",
          "province": "string",
          "seqNo": "1000",
          "city": "string",
          "openBank": "string",
          "accNo": "4309221990050628168",
          "mobile": "15618087578",
          "amt": 1,
          "accType": "00",
          "idNo": "430922199005062816"
        },
        {
          "note": "",
          "idType": "00",
          "idName": "符伟2",
          "province": "string",
          "seqNo": "1001",
          "city": "string",
          "openBank": "string",
          "accNo": "4309221990050628168",
          "mobile": "15618087578",
          "amt": 1,
          "accType": "01",
          "idNo": "430922199005062817"
        }
      ],
    };

    var signArr = [];
    signArr.push("appId=" + (item.appId || ""));
    signArr.push("currency=" + (item.currency || ""));
    signArr.push("notityUrl=" + (item.notityUrl || ""));
    signArr.push("mchtId=" + (item.mchtId || ""));
    signArr.push("nonceStr=" + (item.nonceStr || ""));
    signArr.push("outTradeNo=" + (item.outTradeNo || ""));
    signArr.push("signType=" + (item.signType || ""));
    signArr.push("tradeTime=" + (item.tradeTime || ""));
    signArr.push("key=secret");

    item.sign = md5(signArr.join("&")).toUpperCase();

    try {
      // let rs = await this.restClient.execPost(item, "http://39.96.42.199/merchant/order/transfer");
      let rs = await this.restClient.execPost(item, "http://39.106.185.66:8000/merchant/order/transfer");
      console.log(rs, "----------------------------------------- order/transfer -------------------------------------");
    } catch (error) {
      contract.syncCode = '-10500';
      await contract.save();
    }

  }
  async transferNotify(obj) {
    console.log(obj.a);
    await this.econtractSve.testtransfer("转账回调");
  }

  async formateTime(inputTime) {
    if (!inputTime) {
      return '';
    }
    var date = new Date(inputTime);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return y + '' + m + '' + d + '' + h + '' + minute + '' + second;
  };

  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 = EcontractApi;