var system = require("../../system")
var settings = require("../../../config/settings");
const CtlBase = require("../ctl.base");
const uuidv4 = require('uuid/v4');
const moment = require("moment");
class EcontractCtl extends CtlBase {
  constructor() {
    super(CtlBase.getServiceName(EcontractCtl));

    this.etemplateSve = system.getObject("service.etemplateSve");
    this.userSve = system.getObject("service.userSve");
    this.usereaccountSve = system.getObject("service.usereaccountSve");
    this.ecompanySve = system.getObject("service.ecompanySve");
    this.utilesignbaoSve = system.getObject("service.utilesignbaoSve");
    this.ejobapplySve = system.getObject("service.ejobapplySve");
    this.esealSve = system.getObject("service.esealSve");

    this.Mail = system.getObject("util.mailClient");
    this.excelClient = system.getObject("util.excelClient");
    this.econtractDao = system.getObject("db.econtractDao")
    this.eSignBaoRedirectBossUrl = settings.apiconfig.eSignBaoRedirectBossUrl();
  }

  async saveOffline(queryobj,obj,req) {
    var loginUser = req.session.user;
    try {
      var rs = await this.service.saveOffline(obj);
      return system.getResult2(rs);
    } catch (e) {
      console.log(e);
      return system.getErrResult2("您的网络不稳, 请稍后重试");
    }
  }

  async autoSaveOffline(queryobj,obj,req) {
    var loginUser = req.session.user;
    try {
      var rs = await this.service.autoSaveOffline(obj);
      if (rs.code != 1) {
        return system.getErrResult2(rs.msg);
      }else{
        return system.getResult2(rs);
      }
    } catch (e) {
      console.log(e);
      return system.getErrResult2("您的网络不稳, 请稍后重试");
    }
  }

  async allList(queryobj,obj,req) {
    var params = obj.search || {};
    var ecompanyId = params.ecompany_id;
    if(ecompanyId) {
      params.ecompanyIds = [ecompanyId];
      delete params.ecompany_id;
    }
    params.eflowstatusList = ['2'];
    this.doTimeCondition(params, ["signBegin", "signEnd"]);
    try {
      var page = await this.service.pageByCondition(params);
      return system.getResult2(page);
    } catch (e) {
      console.log(e);
      return system.getErrResult2("您的网络不稳, 请稍后重试");
    }
  }

  async allExport(queryobj, req, res) {
    var params = JSON.parse(queryobj.search);
    params.currentPage = 1;
    params.pageSize = 60000;
    var ecompanyId = params.ecompany_id;
    if(ecompanyId) {
      params.ecompanyIds = [ecompanyId];
      delete params.ecompany_id;
    }
    params.eflowstatusList = ['2'];
    this.doTimeCondition(params, ["signBegin", "signEnd"]);

    try {
      var page = await this.service.pageByCondition(params);

      var csvobj = {
        fileName: "签约协议" + moment().format("YYYYMMDD") + ".csv",
        rows: page.rows,
        opts: {
          fields: ['id', 'ecompany.name', 'eaccount.userName', 'eaccount.mobile', 'eaccount.personsSign', 'eaccount.bankno', 'fileurl'],
          unwind: ['ecompany', 'eaccount'],
          unwindBlank: true,
          excelStrings: true,
        },
        headers: {'id': '编号', 'ecompany.name': "公司名", 'eaccount.userName': "姓名", 'eaccount.mobile': "手机号", 'eaccount.personsSign': "身份证", "eaccount.bankno": "银行卡号", 'fileurl': "签约合同"},
      };
      await this.excelClient.exportCsv(req, res, csvobj);
    } catch (e) {
      console.log(e);
      return system.getErrResult2("您的网络不稳, 请稍后重试");
    }
  }

  async myList(queryobj,obj,req) {
    var params = obj.search || {};

    var ownerIds = null;
    if(!req.session.myIds || req.session.myIds.length == 0) {
      ownerIds = [req.session.user.id];
    } else {
      ownerIds = req.session.myIds;
    }

    var ecompanyIds = await this.ecompanySve.findIdsByOwnerIds(ownerIds);
    if(!ecompanyIds || ecompanyIds.length == 0) {
      return system.getResult2({count: 0, rows: []});
    }

    var ecompanyId = params.ecompany_id;
    if(ecompanyId) {
      delete params.ecompany_id;
    }
    if(ecompanyId) {
      if(ecompanyIds.indexOf(ecompanyId) == -1) {
        return system.getResult2({count: 0, rows: []});
      } else {
        params.ecompanyIds = [ecompanyId];
      }
    } else {
      params.ecompanyIds = ecompanyIds;
    }

    params.eflowstatusList = ['2'];
    this.doTimeCondition(params, ["signBegin", "signEnd"]);
    try {
      var page = await this.service.pageByCondition(params);
      return system.getResult2(page);
    } catch (e) {
      console.log(e);
      return system.getErrResult2("您的网络不稳, 请稍后重试");
    }
  }

  async myExport(queryobj, req, res) {
    var params = JSON.parse(queryobj.search);
    params.currentPage = 1;
    params.pageSize = 60000;
    var ownerIds = null;
    if(!req.session.myIds || req.session.myIds.length == 0) {
      ownerIds = [req.session.user.id];
    } else {
      ownerIds = req.session.myIds;
    }

    var ecompanyIds = await this.ecompanySve.findIdsByOwnerIds(ownerIds);
    if(!ecompanyIds || ecompanyIds.length == 0) {
      return system.getErrResult2("无数据");
    }

    var ecompanyId = params.ecompany_id;
    if(ecompanyId) {
      delete params.ecompany_id;
    }
    if(ecompanyId) {
      if(ecompanyIds.indexOf(ecompanyId) == -1) {
        return system.getErrResult2("无数据");
      } else {
        params.ecompanyIds = [ecompanyId];
      }
    } else {
      params.ecompanyIds = ecompanyIds;
    }

    params.eflowstatusList = ['2'];
    this.doTimeCondition(params, ["signBegin", "signEnd"]);
    try {
      var page = await this.service.pageByCondition(params);

      var csvobj = {
        fileName: "签约协议" + moment().format("YYYYMMDD") + ".csv",
        rows: page.rows,
        opts: {
          fields: ['id', 'ecompany.name', 'eaccount.userName', 'eaccount.mobile', 'eaccount.personsSign', 'eaccount.bankno', 'fileurl'],
          unwind: ['ecompany', 'eaccount'],
          unwindBlank: true,
          excelStrings: true,
        },
        headers: {'id': '编号', 'ecompany.name': "公司名", 'eaccount.userName': "姓名", 'eaccount.mobile': "手机号", 'eaccount.personsSign': "身份证", "eaccount.bankno": "银行卡号", 'fileurl': "签约合同"},

      };
      await this.excelClient.exportCsv(req, res, csvobj);
    } catch (e) {
      console.log(e);
      return system.getErrResult2("您的网络不稳, 请稍后重试");
    }
  }

  async findAndCountAll(queryobj,obj,req){
    var search = obj.search || {};
    if(search.accountMobile) {
      obj.accountMobile = search.accountMobile;
      delete search.accountMobile;
    }

    if(search.accountName) {
      obj.accountName = search.accountName;
      delete search.accountName;
    }

    if(search.accountIdno) {
      obj.accountIdno = search.accountIdno;
      delete search.accountIdno;
    }

    var apps=await super.findAndCountAll(queryobj,obj,req);
    if(apps && apps.data && apps.data.rows) {
      for(var row of apps.data.rows) {
        this.service.handleDate(row, ['completed_at'], "YYYY-MM-DD HH:mm:ss", -8);
      }
    }
    return apps;
  }

  async findCompleteContracts(q, obj, req) {
    obj = obj || {};
    obj.eflowstatus = "2";
    if (req && req.session && req.session.user.id) {
      // obj.user_id = req.session.user.id;
    }
    console.log(obj, "=============================================");
    var rs = await this.service.findContracts(obj);
    return system.getResult2(rs);
  }

  async genContract(q, obj, req) {
    obj = obj || {};

    var userid;
    if (req && req.session && req.session.user && req.session.user.id) {
      userid = req.session.user.id;
    } else {
      var referer = req.headers.referer;
      userid = referer.substr(referer.indexOf('&userid=') + 8);
    }

    if (!userid) {
      return system.getErrResult2("登录失效，请重新登录");
    }

    var isInsure = obj.isInsure || 0;
    let eaccount_id = obj.eaccount_id;
    let etemplateid = obj.etemplateid;
    let apply_id = obj.apply_id || 0;

    let user = await this.userSve.findById(userid);
    let etemplate = await this.etemplateSve.findById(etemplateid);
    let company = await this.ecompanySve.findById(etemplate.ecompany_id);
    let eaccount = await this.usereaccountSve.findById(eaccount_id);

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

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

    let todays = moment().format("YYYY-MM-DD") + " 00:00:00";
    let contractId = await this.econtractDao.findSignedContractId({idno: eaccount.personsSign, ecid: etemplateid, today : todays}) || 0;
    if (contractId) {
      return system.getErrResult2("你已经签署该公司协议，不可以重复签署");
    }

    var contract = await this.service.findOne({
      "etemplate_id": etemplateid,
      "usereaccount_id": eaccount_id,
      "eflowstatus": "1"
    });
    if (contract) {
      await this.service.delete({
        id: contract.id
      });
    }

    contract = {
      name: company.name,
      etemplate_id: etemplateid,
      user_id: userid,
      usereaccount_id: eaccount_id,
      ecompany_id: etemplate.ecompany_id,
      edocid: "",
      eflowid: "",
      esignUrl: "",
      eflowstatus: "1",
      isInsure: isInsure
    }

    contract = await this.service.create(contract);

    let today = new Date().Format("yyyy-MM-dd");

    var nameA = etemplate.nameA;
    var eseal = await this.esealSve.findOne({
      nameA: nameA
    });

    var sealId = "";
    if (!eseal) {
      var rs = await this.utilesignbaoSve.creatEntSignet(settings.apiconfig.companyAccountId(), nameA + "alias", nameA, "", "", "econtractCtl");
      if (rs && rs.code == 1) {
        sealId = rs.data.sealId;
        await this.esealSve.create({
          nameA: nameA,
          sealId: sealId,
        });
      } else {
        return system.getErrResult2("签约失败, 生成印章错误");
      }
    } else {
      sealId = eseal.sealId;
    }

    var params = {
      templateId: etemplate.templateid, //模板id，由创建模板接口调用返回的templateId 必填
      name: company.name, //合同模板名称 必填
      simpleFormFields: {
        nameA: nameA, //甲方 必填
        nameB: eaccount.userName, //乙方 必填
        unit: company.name, //合作单位（国美） 必填---------------------------超出长度风险---目前不知多少长度
        signDateA: today, //甲方签约日期 必填
        signDateB: today //乙方签约日期 必填
      }
    };
    var ebaoAccountId = eaccount.eaccountid; //签署人账户id-- 必填
    var thirdOrderNo = contract.id; //第三方流水号，通知回调使用---选填
    var eBaoRedirectBossUrl = this.eSignBaoRedirectBossUrl + "?ecid=" + etemplate.id + "&cb=1#/ecompany/signed";

    if(user.openid3rd) {
      // 跳转到韵达抽奖
      eBaoRedirectBossUrl = "http://op.yundasys.com/opserver/pages/twentyActs/index.html?appid=ydwechat&openid=" + user.openid3rd;
    }

    console.log({
      params: params,
      ebaoAccountId: ebaoAccountId,
      thirdOrderNo: thirdOrderNo
    }, "-============= params ===========================");
    let tt = await this.utilesignbaoSve.userSignContractNoTemplate(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();
    }

    if (apply_id) {
      var ejobapply = await this.ejobapplySve.findById(apply_id);
      if (ejobapply) {
        ejobapply.econtract_id = contract.id;
        ejobapply.save();
      }
    }

    var genResult = {
      tt: tt,
      esignUrl: contract.esignUrl,
      params: params,
      ebaoAccountId: ebaoAccountId,
      thirdOrderNo: thirdOrderNo
    }
    return system.getResult2(genResult, null);
  }

  async findInfo(q, obj, req) {
    obj = obj || {};
    var rs = await this.service.findInfo(obj);
    return system.getResult2(rs);
  }

  async delById(q, obj, req) {
    obj = obj || {};
    var rs = await this.service.findById(obj.id);
    if(rs) {
      rs.eflowstatus = '1';
      rs.save();
    }
    return system.getResult2(1);
  }


  async sendContractEmail (q, obj, req) {
    obj = obj || {};
    let id = obj.id;
    let email = obj.email;
    let contract = await this.service.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.Mail.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: "发送失败"
      }
    }
  }

  async getContractUrl(q, obj, req) {
    var url = await this.service.getContractUrl(obj.id);
    return system.getResult2(url);
  }

  async downloadContractUrl(q, obj, req) {
    let contract = await this.service.findById(obj.id);
    if(!contract) {
      return system.getErrResult2("协议不存在");
    }
    if(contract.fileurl) {
      return system.getResult2(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();
      return system.getResult2(fileRs.data.selfossUrl);
    } else {
      return system.getErrResult2("网络繁忙，获取合同失败，请稍后重试");
    }
  }

  async getPayNotify(queryobj, qobj, req) {
    try {
      var params = qobj.id || {};
      var rs = await this.service.getPayNotify(params);
      return system.getResult2(rs);
    } catch (e) {
      console.log(e);
      return system.getErrResult2("您的网络不稳, 请稍后重试");
    }
  }

}
module.exports = EcontractCtl;
