var system = require("../../system")
var settings = require("../../../config/settings");
const CtlBase = require("../ctl.base");
const uuidv4 = require('uuid/v4');
const moment = require("moment");

const logCtl = system.getObject("web.oplogCtl");

class DKSignCtl {
  constructor() {
    this.redisClient = system.getObject("util.redisClient");
    this.utilesignbaoSve = system.getObject("service.utilesignbaoSve");

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

    this.dkcompanySve = system.getObject("service.dkcompanySve");
    this.dktemplateSve = system.getObject("service.dktemplateSve");
    this.dkcontractSve = system.getObject("service.dkcontractSve");

    this.mailClient = system.getObject("util.mailClient");

    this.eSignBaoRedirectBossUrl = settings.apiconfig.eSignBaoRedirectBossUrl();
  }
  
  async logints(req) {
    try {
      // 日志记录
      logCtl.info({
        optitle: "userCtl--logints 参数信息",
        op: "base/controller/impl/userCtl/logints",
        content: JSON.stringify(req.query),
        clientIp: ""
      });
      // appId,
      var tid = req.query.tid || 0;
      var appkey = 'tsign';

      var dktemplate = await this.dktemplateSve.getInfo(tid);
      var domain = "http://bpohhr.gongsibao.com";
      if(!dktemplate || !dktemplate.dkaggreement) {
        return domain + "/errpage?errmsg=" + encodeURIComponent(encodeURIComponent("参数错误"));
      }
      var signinforouter = dktemplate.dkaggreement.signinforouter || "ecompany/tsigninfo";

      var userId = req.query.userId || "";
      var userIdNo = (req.query.userIdNo || "").trim().toUpperCase();
      var userMobile = (req.query.userMobile || "").trim();
      var userBankNo = (req.query.userBankNo || "").trim();
      var userName = (decodeURI(req.query.userName || "") || "").trim();
      var accountInfo = {
        userName: userName,
        mobile: userMobile,
        personsSign: userIdNo.toUpperCase(),
        bankno: req.query.userBankNo || "",
      }

      var url = "https://bpohhr.gongsibao.com/tsign?from=ts";
      var ak = uuidv4();
      var key = "ts_" + ak;
      await this.redisClient.setWithEx(key, JSON.stringify(accountInfo), 10 * 60);
      url = url + "&ak=" + ak + "&signinforouter=" + signinforouter + "&ecid=" + tid;
      return url;
    } catch (e) {
      //日志记录
      logCtl.info({
        optitle: "userCtl--logints 异常 error",
        op: "base/controller/impl/userCtl/logints",
        content: e.stack,
        clientIp: ""
      });
    }
  }

  async twaitsign(qobj, pobj, req) {
    var id = Number(pobj.id);
    var eaccount_id = Number(pobj.eaccount_id);
    try {
      let sinedIds = await this.dkcontractSve.findSindIds(eaccount_id, id);
      if(sinedIds.length > 0) {
        return getResult2();
      }

      var info = await this.dktemplateSve.getInfo(id);
      if (info) {
        if (info.created_at) {
          info.created_at = moment(info.created_at).format("YYYY-MM-DD HH:mm:ss");
        }
        if(info.dkcompany) {
          info.dkcompanyName = info.dkcompany.name || "";
        }
      }
      return system.getResult2(info);
    } catch (e) {
      console.log(e);
      return system.getErrResult2("您的网络不稳, 请稍后重试");
    }
  }

  async tsigneds(q, pobj, req) {
    var id = Number(pobj.id);
    var eaccount_id = Number(pobj.eaccount_id);
    try {
      var list = await this.dkcontractSve.findSignedList(eaccount_id, id);
      return system.getResult2(list);
    } catch (e) {
      console.log(e);
      return system.getErrResult2("您的网络不稳, 请稍后重试");
    }
  }

  async templateInfo(queryobj, qobj, req) {
    var id = Number(qobj.id);
    try {
      var info = await this.dktemplateSve.getInfo(id);
      if (info) {
        if (info.created_at) {
          info.created_at = moment(info.created_at).format("YYYY-MM-DD HH:mm:ss");
        }
        if(info.dkcompany) {
          info.dkcompanyName = info.dkcompany.name || "";
        }
      }
      return system.getResult2(info);
    } catch (e) {
      console.log(e);
      return system.getErrResult2("您的网络不稳, 请稍后重试");
    }
  }

  async getTsAccount(qobj, pobj, req) {
    var accountInfo = await this.redisClient.get("ts_" + pobj.ak);
    if (accountInfo && accountInfo != 'undefined') {
      return system.getResult2(JSON.parse(accountInfo));
    }
    return system.getResult2({});
  }

  async contractInfo(qobj, pobj, req) {
    try {
      var contract = await this.dkcontractSve.getInfo(pobj.id);
      if(contract.completed_at) {
        contract.completed_at = moment(contract.completed_at).format("YYYY-MM-DD HH:mm");
      }
      var account = await this.usereaccountSve.findById(contract.usereaccount_id);
      return system.getResult2({contract: contract, usereaccount: account});
    } catch (e) {
      console.log(e);
      return system.getErrResult2("您的网络不稳, 请稍后重试");
    }
  }

  async updateDKSigner(qobj, pobj, req) {
    //var loginUser = await this.service.findById(req.session.user.id);

    try {
      // 获取该身份证帐号信息
      var eaccount = await this.usereaccountSve.findOne({
        personsSign: pobj.personsSign
      });
      // var eaccount = await this.usereaccountSve.findOne({
      //   user_id: req.session.user.id,
      //   personsSign: pobj.personsSign
      // });
      console.log(eaccount, "---------------------------------------------------------eaccount------- ");
      var bool = false;
      if (!eaccount) {
        eaccount = {
          mobile: pobj.mobile,
          userName: pobj.userName,
          personsSign: pobj.personsSign,
          bankno: pobj.bankno,
          eaccountid: "",
          email: "",
          user_id: 0,
          isPush: false,
        };
        eaccount = await this.usereaccountSve.create(eaccount);
      } else {
        bool = true;
      }

      if (!bool || !eaccount.eaccountid || (eaccount.userName != pobj.userName || eaccount.personsSign != pobj.personsSign || eaccount.bankno != pobj.bankno)) {
        var bankthreeParams = {
          name: pobj.userName, //姓名 必填
          idno: pobj.personsSign, //身份证 必填
          cardno: pobj.bankno //银行卡 必填
        };
        var tt = await this.utilesignbaoSve.bankthree(bankthreeParams, "bankinfoAuth");
        // {"code":-110,"message":"手机号格式错误","data":{}}
        //1成功,-110提示验证信息有误，-120亲，提供的信息不正确，请验证后再试！
        console.log("tt-----------------------------", tt);
        if (!tt || tt.code == -120) {
          return system.getErrResult2("银行三要素验证失败，请检查姓名、身份证、银行卡号是否正确");
        }
        if (tt.code == -110) {
          return system.getErrResult2(tt.message);
        }
      }
  
      var params = {
        thirdId: eaccount.eaccountid,
        name: pobj.userName,
        idNo: pobj.personsSign,
        idType: 19,
        mobile: pobj.mobile
      };
      console.log(eaccount.userName, pobj.userName, eaccount.mobile, pobj.mobile, eaccount.personsSign, pobj.personsSign, "--------------------------------------eaccount, pobj-------------------------- ");
      var isNeedCreate = !params.thirdId || eaccount.userName != pobj.userName || eaccount.mobile != pobj.mobile || eaccount.personsSign != pobj.personsSign;
      if (isNeedCreate) {
        params.thirdId = "gsbts_" + uuidv4(); //咱们的唯一码-onlycode
        eaccount.isPush = false;
      }
  
      if (bool) {
        eaccount.mobile = pobj.mobile;
        eaccount.userName = pobj.userName;
        eaccount.personsSign = pobj.personsSign;
        eaccount.bankno = pobj.bankno;
  
        await eaccount.save();
      }
  
      if (isNeedCreate) {
        // 通过手机号，姓名，身份证，获取e签宝 accountid
        var tt = await this.utilesignbaoSve.createAccountId(params, "userCtl");
        console.log(tt, "----------------------------------------------------tt------------ ");
        if (tt && tt.code == 1 && tt.data) {
          console.log(tt.code, "----------------------------------------tt.code------------------------ ");
          eaccount.eaccountid = tt.data.accountId;
          await eaccount.save();
        }
      }
  
      logCtl.info({
        optitle: "电子签更新用户",
        op: "base/controller/impl/dksignCtl.js",
        content: "params=" + JSON.stringify(params) + "，eaccount=" + JSON.stringify(eaccount) + ", isNeedCreate=" + isNeedCreate,
        clientIp: ""
      });
      return system.getResult2(eaccount);
    } catch (error) {
      console.log(error);
    }    
  };

  async getAccount(qobj, pobj, req) {
    try {
      var account = await this.usereaccountSve.findById(pobj.id);
      return system.getResult2(account);
    } catch (error) {
      return system.getErrResult2(error.message);
    }
  }

  async genContract(q, obj, req) {
    try {
      obj = obj || {};
      // eaccount表id
      let eaccount_id = obj.eaccount_id;
      let dktemplate_id = obj.dktemplate_id;

      let dktemplate = await this.dktemplateSve.getInfo(dktemplate_id);
      let dkaggreement = dktemplate.dkaggreement;
      let dkcompany = dktemplate.dkcompany;
      let eaccount = await this.usereaccountSve.findById(eaccount_id);

      if (!eaccount.eaccountid) {
        return system.getErrResult2("签署失败,请重新进入");
      }

      if (!dkaggreement || !dkaggreement.templateid) {
        return system.getErrResult2("协议不存在，请刷新重新选择");
      }

      let sinedIds = await this.dkcontractSve.findSindIds(eaccount_id, dktemplate_id);

      if (sinedIds && sinedIds.length > 0) {
        return system.getErrResult2("你已经签署该公司协议，不可以重复签署");
      }

      var contract = await this.dkcontractSve.findOne({
        "dktemplate_id": dktemplate_id,
        "usereaccount_id": eaccount_id,
        "eflowstatus": "1"
      });
      if (!contract) {
        contract = {
          name: dkcompany.name,
          dktemplate_id: dktemplate_id,
          user_id: 0,
          usereaccount_id: eaccount_id,
          dkcompany_id: dktemplate.dkcompany_id,
          edocid: "",
          eflowid: "",
          esignUrl: "",
          eflowstatus: "1",
        }
        contract = await this.dkcontractSve.create(contract);
      } else {
      }
      var signdate = moment().format("YYYY/MM/DD");
      var params = {
        templateId: dkaggreement.templateid, //模板id，由创建模板接口调用返回的templateId 必填
        name: dkcompany.name, //合同模板名称 必填

        simpleFormFields: {
          nameA: dkcompany.name, //甲方 必填
          addressA: dkcompany.addr,  // 甲方地址
          phoneA: dkcompany.phone,  // 甲方电话

          nameB: eaccount.userName, //乙方姓名 必填
          phoneB: eaccount.mobile, //乙方电话 必填

          nameC: eaccount.userName, // 已方姓名
          phoneC: eaccount.mobile,  // 乙方电话
          idcardC: eaccount.personsSign,  // 乙方身份证

          signdate: signdate,    // 签约日期
        }
      };
      var ebaoAccountId = eaccount.eaccountid; //签署人账户id-- 必填
      var thirdOrderNo = "dk_" + contract.id; //第三方流水号，通知回调使用---选填
      var eBaoRedirectBossUrl = this.eSignBaoRedirectBossUrl + "?ecid=" + dktemplate.id + "&cb=1#/ecompany/tsigned";

      console.log({
        params: params,
        ebaoAccountId: ebaoAccountId,
        thirdOrderNo: thirdOrderNo
      }, "-============= params ===========================");

      var sealId = dkcompany.sealId;
      // TODO 签约合同
      let tt = await this.utilesignbaoSve.userSignContractNoTemplate2(params, ebaoAccountId, thirdOrderNo, eBaoRedirectBossUrl, "econtractCtl", sealId);
      console.log(tt, "-============= result ===========================");
      if (tt && tt.code == 1) {
        contract.eflowid = tt.data.flowId;
        contract.edocid = tt.data.docId;
        contract.esignUrl = tt.data.signUrl;
        contract.save();
      }

      var genResult = {
        tt: tt,
        esignUrl: contract.esignUrl,
        params: params,
        ebaoAccountId: ebaoAccountId,
        thirdOrderNo: thirdOrderNo
      }
      return system.getResult2(genResult, null);
    } catch (error) {
      console.log(error);
      return system.getErrResult2("服务出错，请稍候重试");
    }
  }

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

  async sendContractEmail (q, obj, req) {
    obj = obj || {};
    let id = obj.id;
    let email = obj.email;
    let contract = await this.dkcontractSve.findById(id);

    if (!contract) {
      return {
        code: 0,
        msg: "发送失败，合同不存在"
      }
    }

    if (contract.eflowstatus != "2") {
      return {
        code: 0,
        msg: "合同还未签署完成"
      }
    }

    if (!contract.fileurl) {
      //  请求文件地址
      let fileRs = await this.utilesignbaoSve.downloadUserContractFile(contract.eflowid, "econtractCtl");
      console.log(fileRs, "===============================================================");
      if (fileRs.code == 1 && fileRs.data.selfossUrl) {
        contract.fileurl = fileRs.data.selfossUrl;
        contract.save();
      } else {
        return {
          code: 0,
          msg: "您的网络繁忙，请稍后重试"
        }
      }
    }

    var to = email;
    var title = '合同信息';
    var text = null;
    var html = '请点击下载链接获取合同:';
    var cc = null;
    var bcc = null;
    var atts = [];
    var html = '<a href="' + contract.fileurl + '">' + contract.name + '</a>'

    try {
      console.log(to, title, text, html, cc, bcc, atts);
      var result = await this.mailClient.sendMsg(to, title, text, html, cc, bcc, atts) //发送成功后result的值:250 Data Ok: queued as freedom
      console.log(result);
      if (result.indexOf("Ok") >= 0) {
        return {
          code: 1,
          msg: "发送成功"
        }
      } else {
        return {
          code: 0,
          msg: "发送失败"
        }
      }
    } catch (e) {
      console.log(e);
      return {
        code: 0,
        msg: "发送失败"
      }
    }
  }
}
module.exports = DKSignCtl;