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

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

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


    this.wxSve = system.getObject("service.wxSve");
    this.esettleSve = system.getObject("service.esettleSve");

    this.restClient = system.getObject("util.restClient");
    this.smsS = system.getObject("util.smsClient");
  }

  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 testpushContract(obj, req) {
    var ids = obj.ids || [];
    for (var id of ids) {
      // this.econtractSve.syncSign(67854);
      await this.econtractSve.syncSign(id);
    }
  }

  async pushwxuser(obj, req) {
    var ids = obj.ids || [];
    var result = [];
    for (var id of ids) {
      // this.econtractSve.syncSign(67854);
      try {
        var rs = await this.ecompanywxuserSve.pushwxuser(id);
        result.push(rs);
      } catch (error) {
        result.push(error.msg);
      }
    }
    return result;
  }

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

    var sign = md5("companyName=" + companyName + "&nonceStr=" + obj.nonceStr + "&key=wxf616c0a459d66081").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 transferNotify(obj, req) {
    this.econtractSve.testtransfer(obj);
  }
  async contractcb(obj, req) {
    this.econtractSve.updateCallbackStatus(obj);
  }

  async synctemplate(obj, req) {
    for (var id = 1; id <= 514; id++) {
      try {
        var template = await this.etemplateSve.findById(id);
        if (!template) {
          continue;
        }
        template.qrcodeurl = await this.wxSve.makeQrWithScene("wxf616c0a459d66081", template.id);
        await template.save();
      } catch (error) {
        console.log(error);
      }
    }

    for (var id = 10000; id <= 10100; id++) {
      try {
        var template = await this.etemplateSve.findById(id);
        if (!template) {
          continue;
        }
        template.qrcodeurl = await this.wxSve.makeQrWithScene("wxf616c0a459d66081", template.id);
        await template.save();
      } catch (error) {
        console.log(error);
      }
    }
  }

  async sinedUsers(obj, req) {
    // 验证合法性
    var appId = obj.appId;
    var nonceStr = obj.nonceStr;
    var idNo = obj.idNo;
    var startId = obj.startId || 0;
    var userId = obj.userId || "";
    var userCode = obj.userCode || "";
    var branchCode = obj.branchCode || "";
    var pageSize = 20;

    var busi = await this.ecompanybusiSve.findOne({ appId: appId });
    if (!busi) {
      return {
        code: 1001003,
        msg: "配置信息错误，请联系薪必果人员进行配置"
      };
    }

    var signArr = [];
    signArr.push("appId=" + appId);
    signArr.push("branchCode=" + branchCode);
    signArr.push("idNo=" + idNo);
    signArr.push("nonceStr=" + nonceStr);
    signArr.push("startId=" + startId);
    signArr.push("userCode=" + userCode);
    signArr.push("userId=" + userId);
    signArr.push("key=" + busi.key);

    var sign = md5(signArr.join("&")).toUpperCase();
    if (sign != obj.sign) {
      return {
        code: 1001001,
        msg: "签名失败"
      };
    }
    var params = {
      ecompanyId: busi.ecompany_id,
      startId: startId,
      idNo: idNo,
      pageSize: pageSize,
      userId3rd: userId,
      userCode3rd: userCode,
      branchCode3rd: branchCode,
    };

    try {
      var userList = await this.econtractSve.findSignedUses4Push(params);

      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 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=wxf616c0a459d66081").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 testinsure() {
    this.econtractSve.sendInsure(61094);
  }

  async ydsignnumber() {
    return this.econtractSve.ydsignnumber();
  }


  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 formateSimpTime() {
    var date = new Date();
    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();
    minute = minute < 10 ? ('0' + minute) : minute;

    return y + '年' + m + '月' + d + '日' + ' ' + h + ':' + minute;
  };

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

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

  async validateUser(obj, req) {
    // 验证合法性
    var idName = this.trim(obj.idName);
    var idNo = this.trim(obj.idNo);
    var accNo = this.trim(obj.accNo);
    var nonceStr = obj.nonceStr;
    var sign = obj.sign;
    if (!idName) {
      return { code: 1002001, msg: "参数错误, 姓名不存在" };
    }
    if (!idNo) {
      return { code: 1002001, msg: "参数错误, 身份证不存在" };
    }
    if (!accNo) {
      return { code: 1002001, msg: "参数错误, 银行卡号不存在" };
    }

    var sign = md5("accNo=" + accNo + "&idName=" + idName + "&idNo=" + idNo + "&nonceStr=" + obj.nonceStr + "&key=wxf616c0a459d66081").toUpperCase();
    if (sign != obj.sign) {
      return {
        code: 1001001,
        msg: "签名失败"
      };
    }

    try {
      var list = await this.econtractSve.findSinedByThree(idName, idNo, accNo);
      if (list.length > 0) {
        return { code: 0, msg: "success" };
      }

      var bankthreeParams = {
        name: idName, //姓名 必填
        idno: idNo, //身份证 必填  
        cardno: accNo //银行卡 必填
      };

      var tt = await this.utilesignbaoSve.bankthree(bankthreeParams, "bankinfoAuth") || {};
      // {"code":-110,"message":"手机号格式错误","data":{}}
      //1成功,-110提示验证信息有误，-120亲，提供的信息不正确，请验证后再试！
      console.log("tt-----------------------------", tt);

      if (tt.code == 1) {
        return { code: 0, msg: "success" };
      } else if (tt.code == -110) {
        return { code: 1002002, msg: tt.message };
      } else {
        return { code: 1002002, msg: "银行三要素验证失败" };
      }
    } 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 notifyMssage(obj, req) {
    var resultNotify = {
      code: 1,
      message: "success"
    };

    try {
      this.econtractSve.testtransfer(JSON.stringify(obj));  
    } catch (error) {
    }

    var regexNumber = /^[0-9]*$/;
    var wechatNoticeList = []//微信通知列表
    var notifyTime = await this.formateSimpTime();
    var errorItems = [];

    //循环参数
    for (var item in obj.sendList) {
      var rowItem = Number(item) + 1;
      var orderItemId = obj.sendList[item]['orderItemId'] || "";

      var orderItem = await this.esettleSve.findOrderItemById(orderItemId);
      if(!orderItem) {
        errorItems.push("orderItem" + orderItem + "不存在");
        continue;
      }
      var idNo = orderItem.id_no || "";
      var amt = orderItem.amt || 0;
      var mobile = orderItem.mobile || "";
      notifyTime = moment(orderItem.pay_complete_time).add(-8, "hours").format("YYYY年MM月DD日 HH:mm");
      var notifyTimeStr = moment(orderItem.pay_complete_time).add(-8, "hours").format("YYYY-MM-DD HH:mm:ss");

      //添加支付记录
      var incomeTax = parseFloat((Number(orderItem.income_tax) / 100).toFixed(2));

      var notifyUrl = "https://bpohhr.gongsibao.com/paynotify?id=" + orderItemId;

      var notifyObj = {
        fromid: mobile,
        username: orderItem.id_name || "",
        flag: 0,
        amount: amt,
        status: 0,
        notifyTime: notifyTimeStr,
        orderItemId: orderItemId,
        income_tax: orderItem.income_tax
      }

      //为空验证
      if (!idNo) {
        errorItems.push("第" + rowItem + "项-参数错误, 身份证为空");
        continue;
      }
      if (!amt) {
        errorItems.push("第" + rowItem + "项-参数错误, 实发金额为空");
        continue;
      }

      amt = parseFloat((Number(amt) / 100).toFixed(2));
      var message = notifyTime + " 您收到报酬费" + amt + "元, 查看详细内容" + notifyUrl;

      try {
        var list = await this.econtractSve.findOpenIdByNo("2", idNo);
        if (list.length > 0) {
          var sendItem;
          var sendMobile;
          for (var item of list) {
            if (item.openId.indexOf('oEl') === 0) {
              sendItem = item;
              break;
            }
            if (item.mobile) {
              sendMobile = item.mobile;

              // 手机号通知
              notifyObj.username = item.userName;
              notifyObj.fromid = mobile || sendMobile;
            }
          }
          if (sendItem) {
            // 微信消息模板通知
            var wechatParam = {
              url: notifyUrl,
              first: "您有一个报酬发放通知！",
              keyword1: sendItem.userName,
              keyword2: "已发放",
              keyword3: amt + "元",
              keyword4: notifyTime + ' 您的报酬已到帐，请查收！',
              openid: sendItem.openId
            }
            wechatNoticeList.push(wechatParam);

            // 通知参数
            notifyObj.username = item.userName;
            notifyObj.fromid = sendItem.openId;
            notifyObj.flag = 1;
            await this.econtractSve.addPayNotify(notifyObj);
          } else if (mobile || sendMobile) {
            // 手机号码通知
            await this.smsS.sendMsg(mobile || sendMobile, message);
            await this.econtractSve.addPayNotify(notifyObj);
          }
        } else {
          if (mobile) {
            await this.smsS.sendMsg(mobile, message);
            await this.econtractSve.addPayNotify(notifyObj);
          } else {
            errorItems.push("第" + rowItem + "项-根据身份证获取数据为空");
          }
          continue;
        }
      } catch (e) {
        resultNotify.code = 500;
        resultNotify.message = "接口异常";

        //日志记录
        logCtl.error({
          optitle: "发薪通知error",
          op: "api/econtractApi/notifyMssage",
          content: e.stack,
          clientIp: req.clientIp
        });
      }
    }
    if (wechatNoticeList.length > 0) {
      await this.wxPushMssage(wechatNoticeList);
    }
    if (errorItems.length > 0) {
      var errors = "";
      for (var item of errorItems) {
        errors += item + "、";
      }
      return system.getErrResult2(errors.substr(0, errors.length - 1));
    }

    return resultNotify;
  }

  //微信通知消息
  async wxPushMssage(wechatNoticeList) {
    try {
      //微信处理
      var data = null;
      //添加支付记录
      var wxParam = null;

      for (var i = 0; i < wechatNoticeList.length; i++) {
        var wechatItem = wechatNoticeList[i];
        //发送通知
        data = {
          first: wechatItem.first,
          keyword1: { value: wechatItem.keyword1 },
          keyword2: { value: wechatItem.keyword2 },
          keyword3: { value: wechatItem.keyword3 },
          keyword4: { value: wechatItem.keyword4 }
        };

        this.wxSve.sendTmplMsg(wechatItem.openid, "khPLingFFTVQM2t7SVm1q1o9MvS2WgqUvIjCPkLcqAY", wechatItem.url || "", data, "wxf616c0a459d66081");
      }
    } catch (e) {
      var result = {
        code: 500,
        msg: "接口异常"
      };
      console.log(e.stack);
      //日志记录
      logCtl.error({
        optitle: "微信发薪通知error",
        op: "api/econtractApi/wxPushMssage",
        content: e.stack,
        clientIp: req.clientIp
      });
    }
    return result;
  }
}
module.exports = EcontractApi;