var system=require("../../system")
var settings=require("../../../config/settings");
const CtlBase = require("../ctl.base");
const uuidv4 = require('uuid/v4');
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.Mail=system.getObject("util.mailClient");

     this.eSignBaoRedirectBossUrl=settings.apiconfig.eSignBaoRedirectBossUrl();
   }
   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 || {};
     let userid ;
     if(req && req.session && req.session.user.id){
        userid = req.session.user.id;
     }
     if(!userid) {
       return system.getErrResult2("登录失效，请重新登录");
     }

     let eaccount_id = obj.eaccount_id;
     let etemplateid = obj.etemplateid;

     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 sinedCompanyIds = await this.service.findUserSinedCompanyIds(eaccount_id);

     if(sinedCompanyIds.indexOf(Number(etemplate.ecompany_id)) != -1) {
       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: etemplate.name,
       etemplate_id : etemplateid,
       user_id : userid,
       usereaccount_id : eaccount_id,
       ecompany_id : etemplate.ecompany_id,
       edocid: "",
       eflowid : "",
       esignUrl : "",
       eflowstatus: "1"
     }

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

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

     var params={
       templateId: etemplate.templateid,  //模板id，由创建模板接口调用返回的templateId 必填
       name:etemplate.name,  //合同模板名称 必填
       simpleFormFields:{
         nameA: company.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.ecompany_id + "&cb=1#/ecompany/signed";

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

   async findInfo(q, obj, req) {
     obj = obj || {};
     var rs=await this.service.findInfo(obj);
     return system.getResult2(rs);
   }
   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:"发送失败"}
     }
   }
}
module.exports=EcontractCtl;
