var system = require("../../system")
var moment = require("moment");
const md5 = require("MD5");
const logCtl = system.getObject("web.oplogCtl");
class EcontractApi {
  constructor() {
    this.esettleSve = system.getObject("service.esettleSve");
    this.busistatSve = system.getObject("service.busistatSve");
    this.salesmanSve = system.getObject("service.salesmanSve");
    this.restClient = system.getObject("util.restClient");
    this.redisClient = system.getObject("util.redisClient");
    this.outTradeNoKey = 'bpo_outtradeno';
  }

  async syncUserDepartment() {
    let busimap = await this.salesmanSve.mapSalesmen();
    for (let busiId in busimap) {
      let salesman = busimap[busiId] || {name: "", department_name: "未设置部门", mobile: ""};
      if (!salesman) {
        continue;
      }
      await this.busistatSve.updateDepartmentName({
        busiIds: [busiId],
        user_name: salesman.name || "",
        user_mobile: salesman.mobile || "",
        user_department_name: salesman.department_name || "",
      });
    }
  }

  async syncDepartmentStat(pobj) {
    pobj = pobj || {};
    let syncDays = Number(pobj.syncDays || 10);
    // 获取30天内数据
    let t1 = new Date().getTime();
    for (let i = 0; i < syncDays; i++) {
      try {
        let day = moment().subtract(syncDays - i, 'days').format('YYYY-MM-DD');
        console.log(`---------------- begin ${day}`);
        let t1 = new Date().getTime();
        await this.syncDay({day: day});
        let t2 = new Date().getTime();
        console.log(`---------------- end ${day}`, t2 - t1);
      } catch (e) {
        console.log(e.stack);
      }
    }
    let t2 = new Date().getTime();
    console.log(t2 - t1, "------------------");
    this.syncUserDepartment();
    return system.getResult2(1);
  }


  async syncDay(pobj) {
    let day = pobj.day;
    let dayNum = Number(day.replace(new RegExp("-", 'g'), ""));
    let list = await this.esettleSve.busiStatByDay(day);
    console.log(JSON.stringify(list));

    await this.busistatSve.syncDayData(dayNum, list);
  }

  async settleCommission(obj, req) {
    this.esettleSve.settleCommission(obj.begin, obj.end);
  }

  async testCardValid(obj, req) {
    var url = "https://payadmin.gongsibao.com/merchant/bank/support";

    var params = {
      appId: obj.appId,
      accNo: obj.accNo,
      mchtId: obj.mchtId,
      nonceStr: await this.getUidStr(16),
      signType: "MD5",
    }
    var signArr = [];
    signArr.push("accNo=" + params.accNo || "");
    signArr.push("appId=" + params.appId || "");
    signArr.push("mchtId=" + params.mchtId || "");
    signArr.push("nonceStr=" + params.nonceStr || "");
    signArr.push("signType=" + params.signType || "");
    signArr.push("key=ea4eafab8be1d0242399f39649bfabe0");

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

    // "appId": "10000000000",  
    // "mchtId": "1",
    try {
      var t1 = new Date().getTime();
      var rs = await this.restClient.execPost(params, url);
      var t2 = new Date().getTime();
      console.log((t2 - t1), rs, "-------------------- use time & rs-----------------");
      return rs;
    } catch (error) {
      return error.stack;
    }
  }

  async getSign(obj, req) {
    return md5(obj.key || "").toUpperCase();
  }

  async pushSettle(obj, req) {
    try {

      var signArr = [];
      signArr.push("accBank=" + obj.accBank || "");
      signArr.push("accNo=" + obj.accNo || "");
      signArr.push("accType=" + obj.accType || "");
      signArr.push("addedValueTax=" + obj.addedValueTax || 0);
      signArr.push("amt=" + obj.amt || 0);
      signArr.push("appid=" + obj.appid || "");
      signArr.push("companyName=" + obj.companyName || "");
      signArr.push("credit_code=" + obj.credit_code || "");
      signArr.push("mchtId=" + obj.mchtId || "");
      signArr.push("nonceStr=" + obj.nonceStr || "");
      signArr.push("outTradeNo=" + obj.outTradeNo || "");
      signArr.push("payNo=" + obj.payNo || "");
      signArr.push("serviceRate=" + obj.serviceRate || 0);
      signArr.push("serviceTax=" + obj.serviceTax || 0);
      signArr.push("tradeTime=" + obj.tradeTime || "");
      signArr.push("key=wxdc08c441c9fdb7a7");

      var sign = md5(signArr.join("&")).toUpperCase();
      if (obj.sign != sign) {
        return {
          code: 1001001,
          msg: "签名失败",
        };
      }
      var settle = {
        appid: obj.appid,
        mchtId: obj.mchtId,
        outTradeNo: obj.outTradeNo || "",
        payNo: obj.payNo || "",
        companyName: obj.companyName || "",
        credit_code: obj.credit_code || "",
        ecompany_id: 0,
        amt: obj.amt || 0,
        serviceRate: obj.serviceRate || 0,
        serviceTax: obj.serviceTax || 0,
        addedValueTax: obj.addedValueTax || 0,
        tradeTime: obj.tradeTime || "",
        accType: obj.accType || 0,
        accBank: obj.accBank || 0,
        accNo: obj.accNo || 0,
      };

      return await this.esettleSve.saveSettle(obj);
    } catch (e) {
      var result = {
        code: 500,
        msg: "接口异常"
      };
      console.log(e.stack);
      return result;
    }
  }

  async doSettleLogic(obj, req) {
    return await this.esettleSve.doSettleLogic(1);
  }

  async busiAccount() {
    var result = {};
    try {
      var param = {
        "appId": "1103817785",
        "sign": "439BAC772B4ECF9B7D9BB2EBB4A1C438",
        "mchtId": "1103817785420820481",
        "signType": "MD5",
        "nonceStr": await this.getUidStr(16)
      }

      var signArr = [];
      signArr.push("appId=" + param.appId);
      signArr.push("mchtId=" + param.mchtId);
      signArr.push("nonceStr=" + param.nonceStr);
      signArr.push("signType=" + param.signType);
      signArr.push("key=ca47edd3ae8bac3f7a68d8126d891f52");

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

      console.log(param);
      try {
        let rs = await this.restClient.execPost(param, "https://pay.gongsibao.com/merchant/busiAccount/query");

        if (rs && rs.stdout) {
          var stdout = JSON.parse(rs.stdout) || {};
          var code = stdout.code;

          if (code == 0) {
            code = 1;
          } else if (code == 1) {
            code = 0;
          } else {}
          result.code = code;
          result.msg = stdout.msg;
          result.data = stdout.data;
        } else {
          result.code = 0;
          result.msg = '结算接口返回空';
        }
      } catch (error) {
        result.code = 500;
        result.msg = '结算接口异常';
      }
    } catch (error) {
      result.code = 500;
      result.msg = '服务异常';
    }
    return result;
  }

  async transfer(obj, req) {
    var result = {};
    var bizs = obj.bizs;
    var bizContent = [];
    if(!bizs || bizs.length == 0) {
      result.code = 0;
      result.msg = "请填写发薪人员";
      return result;
    }
    for (var biz of bizs) {
      bizContent.push({
        "note": "测试",
        "idType": "00",
        "idName": biz.idName,
        "seqNo": "1001",
        "accNo": biz.accNo,
        "mobile": biz.mobile,
        "amt": Number(biz.amt || 100),
        "accType": "00",
        "idNo": biz.idNo
      });
    }

    var outTradeNo = await this.redisClient.get(this.outTradeNoKey);
    if (!outTradeNo) {
      outTradeNo = 123456579921;
    } else {
      outTradeNo = Number(outTradeNo) + 1;
    }
    this.redisClient.set(this.outTradeNoKey, outTradeNo.toString());
    var now = moment().add(30, 'seconds').format('YYYYMMDDHHmmss');

    var param = {
      "appId": "1103817785",
      "currency": "CNY",
      "mchtId": "1103817785420820481",
      "nonceStr": "nonceStrnonceStr",
      "notityUrl": "http://bpohhr.gongsibao.com/api/econtractApi/transferNotify",
      "outTradeNo": outTradeNo,
      "signType": "MD5",
      "tradeTime": now,
      "bizContent": bizContent
    }
    // now
    var 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=ca47edd3ae8bac3f7a68d8126d891f52");
    param.sign = md5(signArr.join("&")).toUpperCase();

    console.log(param);
    try {
      let rs = await this.restClient.execPost(param, "https://pay.gongsibao.com/merchant/order/transfer");

      console.log(rs);
      if (rs && rs.stdout) {
        var stdout = JSON.parse(rs.stdout) || {};
        var code = stdout.code;

        if (code == 0) {
          code = 1;
        } else if (code == 1) {
          code = 0;
        } else {}
        result.code = code;
        result.msg = stdout.msg;
      } else {
        result.code = 0;
        result.msg = '结算接口返回空';
      }
    } catch (error) {
      result.code = 500;
      result.msg = '结算接口异常';
    }
    //  [{
    //   "note": "测试",
    //   "idType": "00",
    //   "idName": "任智军",
    //   "seqNo": "1001",
    //   "accNo": "6225880170506167",
    //   "mobile": "13488845635",
    //   "amt": 100,
    //   "accType": "00",
    //   "idNo": "230828197712268019"
    // }],

    return result;
  }

  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;
