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

class EtemplateCtl extends CtlBase{
   constructor(){
     super(CtlBase.getServiceName(EtemplateCtl));
     this.utilesignbaoSve = system.getObject("service.utilesignbaoSve");
     this.econtractSve = system.getObject("service.econtractSve");
     this.wxSve = system.getObject("service.wxSve");
   }
   async findReadyContracts(q,obj, req){
     obj = obj || {};
     obj.userId = req.session.user.id;

     // 验证companyId
     if(!obj.ecompany_id || !obj.eaccount_id) {
       return system.getResult2([]);
     }

     let sinedCompanyIds = await this.econtractSve.findUserSinedCompanyIds(Number(obj.eaccount_id));
     if(sinedCompanyIds.indexOf(Number(obj.ecompany_id)) != -1) {
       return system.getResult2([]);
     }

     var rs=await this.service.findReadyContracts(obj);
     return system.getResult2(rs);
   }

   async mysave(queryobj,qobj,req){
     try {
       var old=null;
       let id = qobj.id;
       if(id){
         old = await this.service.findById(id);
       }

       var rtn = null;
       if(old){//修改
         console.log("edit++++++++++++++++++++++++++++++++++++");
         await this.service.update(qobj);
         rtn = await this.service.findById(id);
       }else{//新增
         console.log("new++++++++++++++++++++++++++++++++++++");
         rtn = await this.service.create(qobj);
       }
       // 调用e签宝接口生成template
       if(rtn.filepath && rtn.name) {
         try {
           let templateRs = await this.utilesignbaoSve.createEntTemplate(rtn.filepath, rtn.name, "etemplateCtl");

           logCtl.info({
              optitle:"e签宝===>保存模板信息template",
              op:"app/base/controller/impl/etemplateCtl/mysave",
              content:"参数：filepath="+rtn.filepath+";name="+rtn.name + "; result : " + JSON.stringify(templateRs),
              clientIp:""
            });
           if(templateRs && templateRs.code == 1 && templateRs.data) {
             rtn.filekey = templateRs.data.fileKey;
             rtn.templateid = templateRs.data.templateId;
             rtn.save();
           } else {
             console.log("======================12222222222222222222222222222222222222222222222222222222222222222222222222====================");
           }
         } catch (e) {
           console.error(e);
         }
       }

       rtn.qrcodeurl = await this.wxSve.makeQrWithScene("wxdc08c441c9fdb7a7", rtn.ecompany_id);
       rtn.save();
       return system.getResult2(rtn, null);
     } catch (e) {
       console.log("-----------------------------e");
       console.log(e);
       return {code:-1}
     }
   }
}
module.exports=EtemplateCtl;
