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");
const moment = require("moment");

class EtemplateCtl extends CtlBase {
  constructor() {
    super(CtlBase.getServiceName(EtemplateCtl));

    this.utilesignbaoSve = system.getObject("service.utilesignbaoSve");
    this.econtractSve = system.getObject("service.econtractSve");
    this.ecompanySve = system.getObject("service.ecompanySve");
    this.wxSve = system.getObject("service.wxSve");

    this.excelClient = system.getObject("util.excelClient");
  }
  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 signList(queryobj, qobj, req) {
    var params = qobj.search;
    try {
      var ecompanyId = params.ecompany_id;
      if (ecompanyId) {
        params.ecompanyIds = [ecompanyId];
        delete params.ecompany_id;
      }
      var page = await this.service.signPage(params);
      return system.getResult2(page);
    } catch (e) {
      console.log(e);
      return system.getErrResult2("您的网络不稳, 请稍后重试");
    }
  }

  async getListByName(queryobj, qobj, req){
    var name = this.trim(qobj.name);
    if(!name) {
      return system.getResult2([])
    }    
    
    var list = await this.service.getListByName(name);
    return system.getResult2(list);
  }

  async signExport(pobj, req, res) {
    var params = JSON.parse(pobj.search);
    try {
      params.currentPage = 1;
      params.pageSize = 60000;
      var ecompanyId = params.ecompany_id;
      if (ecompanyId) {
        params.ecompanyIds = [ecompanyId];
        delete params.ecompany_id;
      }
      var page = await this.service.signPage(params);
      
      var csvobj = {
        fileName: "二维码-" + moment().format("YYYYMMDD") + ".csv",
        rows: page.rows,
        opts: {
          fields: ['id', 'ecompany.name', 'nameA', 'qrcodeurl'],
          unwind: ['ecompany'],
          excelStrings: true,
          unwindBlank: true
        },
        headers: {
          "id": "编号",
          'ecompany.name': "公司名",
          'nameA': "签约主体",
          'qrcodeurl': "二维码"
        },
      };
      await this.excelClient.exportCsv(req, res, csvobj);
    } catch (e) {
      console.log(e);
      return system.getErrResult2("您的网络不稳, 请稍后重试");
    }
  }

  async mySignList(queryobj, qobj, req) {
    var params = qobj.search;
    try {
      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;
      }

      var page = await this.service.signPage(params);
      return system.getResult2(page);
    } catch (e) {
      console.log(e);
      return system.getErrResult2("您的网络不稳, 请稍后重试");
    }
  }

  async mySignExport(pobj, req, res) {
    var params = JSON.parse(pobj.search);
    try {
      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;
      }

      var page = await this.service.signPage(params);

      var csvobj = {
        fileName: "二维码-" + moment().format("YYYYMMDD") + ".csv",
        rows: page.rows,
        opts: {
          fields: ['id', 'ecompany.name', 'nameA', 'qrcodeurl'],
          unwind: ['ecompany'],
          excelStrings: true,
          unwindBlank: true
        },
        headers: {'id': '编号', 'ecompany.name': "公司名", 'nameA': "签约主体", 'qrcodeurl': "二维码"},
      };
      await this.excelClient.exportCsv(req, res, csvobj);
    } catch (e) {
      console.log(e);
      return system.getErrResult2("您的网络不稳, 请稍后重试");
    }
  }

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

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

      var ecompany = await this.ecompanySve.findById(qobj.ecompany_id);

      if (template) { //修改
        template.name = qobj.name || ecompany.name;
        template.nameA = qobj.nameA;
        template.ecompany_id = qobj.ecompany_id;
        template.filepath = qobj.filepath;
        template.remark = qobj.remark || "";

        await template.save();
      } else { //新增
        console.log("new++++++++++++++++++++++++++++++++++++");
        template = {};
        template.name = qobj.name || ecompany.name;
        template.nameA = qobj.nameA;
        template.ecompany_id = qobj.ecompany_id;
        template.filepath = qobj.filepath;
        template.placeholderkey = qobj.placeholderkey;
        template.remark = qobj.remark || "";
        template = await this.service.create(template);
      }
      // 调用e签宝接口生成template
      if (template.filepath && ecompany.name) {
        try {
          let templateRs = await this.utilesignbaoSve.createEntTemplate(template.filepath, ecompany.name, "etemplateCtl");

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

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