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 DKtemplateCtl extends CtlBase {
  constructor() {
    super(CtlBase.getServiceName(DKtemplateCtl));

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

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

    this.excelClient = system.getObject("util.excelClient");
  }
  async findReadyContracts(q, obj, req) {
    // obj = obj || {};
    // obj.userId = req.session.user.id;

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

    // let sinedCompanyIds = await this.econtractSve.findUserSinedCompanyIds(Number(obj.eaccount_id));
    // if (sinedCompanyIds.indexOf(Number(obj.dkcompany_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 dkcompanyId = params.dkcompany_id;
      if (dkcompanyId) {
        params.dkcompanyIds = [dkcompanyId];
        delete params.dkcompany_id;
      }
      var page = await this.service.pageByCondition(params);
      return system.getResult2(page);
    } catch (e) {
      console.log(e);
      return system.getErrResult2("您的网络不稳, 请稍后重试");
    }
  }

  async signExport(pobj, req, res) {
    var params = JSON.parse(pobj.search);
    try {
      params.currentPage = 1;
      params.pageSize = 60000;
      var dkcompanyId = params.dkcompany_id;
      if (dkcompanyId) {
        params.dkcompanyIds = [dkcompanyId];
        delete params.dkcompany_id;
      }
      var page = await this.service.pageByCondition(params);
      
      var csvobj = {
        fileName: "二维码-" + moment().format("YYYYMMDD") + ".csv",
        rows: page.rows,
        opts: {
          fields: ['id', 'dkcompany.name', 'name', 'codeurl'],
          unwind: ['dkcompany'],
          excelStrings: true,
          unwindBlank: true
        },
        headers: {
          "id": "编号",
          'dkcompany.name': "公司名",
          'name': "模板名称",
          'codeurl': "签约地址"
        },
      };
      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 isAdmin = req.session.user.isAdmin;
      var ownerIds = null;
      var dkcompanyIds = null;
      if(!isAdmin) {
        if (!req.session.myIds || req.session.myIds.length == 0) {
          ownerIds = [req.session.user.id];
        } else {
          ownerIds = req.session.myIds;
        }
  
        dkcompanyIds = await this.dkcompanySve.findIdsByOwnerIds(ownerIds);
        if (!dkcompanyIds || dkcompanyIds.length == 0) {
          return system.getResult2({
            count: 0,
            rows: []
          });
        }
      }

      var dkcompanyId = params.dkcompany_id;
      if (dkcompanyId) {
        delete params.dkcompany_id;
      }
      if (dkcompanyId) {
        if(isAdmin) {
          params.dkcompanyIds = [dkcompanyId];
        } else {
          if (dkcompanyIds.indexOf(dkcompanyId) == -1) {
            return system.getResult2({
              count: 0,
              rows: []
            });
          } else {
            params.dkcompanyIds = [dkcompanyId];
          }
        }
      } else {
        params.dkcompanyIds = dkcompanyIds;
      }
      

      var page = await this.service.pageByCondition(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 isAdmin = req.session.user.isAdmin;
      var ownerIds = null;
      var dkcompanyIds = null;
      if(!isAdmin) {
        if (!req.session.myIds || req.session.myIds.length == 0) {
          ownerIds = [req.session.user.id];
        } else {
          ownerIds = req.session.myIds;
        }
  
        dkcompanyIds = await this.dkcompanySve.findIdsByOwnerIds(ownerIds);
        if (!dkcompanyIds || dkcompanyIds.length == 0) {
          return system.getResult2({
            count: 0,
            rows: []
          });
        }
      }

      var dkcompanyId = params.dkcompany_id;
      if (dkcompanyId) {
        delete params.dkcompany_id;
      }
      if (dkcompanyId) {
        if(isAdmin) {
          params.dkcompanyIds = [dkcompanyId];
        } else {
          if (dkcompanyIds.indexOf(dkcompanyId) == -1) {
            return system.getResult2({
              count: 0,
              rows: []
            });
          } else {
            params.dkcompanyIds = [dkcompanyId];
          }
        }
      } else {
        params.dkcompanyIds = dkcompanyIds;
      }

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

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

  async info(queryobj, qobj, req) {
    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");
        }
        info.dkcompany = await this.dkcompanySve.getInfo(info.dkcompany_id) || {};
        info.dkcompanyName = info.dkcompany.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 dkcompany = await this.dkcompanySve.findById(qobj.dkcompany_id);
      var aggreement = await this.dkaggreementSve.findById(qobj.dkaggreement_id);
      if (template) {
        //修改
        template.name = qobj.name || dkcompany.name;
        template.dkcompany_id = qobj.dkcompany_id;
        template.dkaggreement_id = qobj.dkaggreement_id;
        template.remark = qobj.remark || "";
        await template.save();
      } else {
        //新增
        console.log("new++++++++++++++++++++++++++++++++++++");

        template = {};
        template.name = qobj.name || dkcompany.name;
        template.dkcompany_id = qobj.dkcompany_id;
        template.dkaggreement_id = qobj.dkaggreement_id;
        template = await this.service.create(template);
      }
      var homeurl = aggreement.homeurl || "https://bpohhr.gongsibao.com/ts";

      template.codeurl = homeurl + "?tid=" + template.id;
      await template.save();
      return system.getResult2(template, null);
    } catch (e) {
      console.log("-----------------------------e");
      console.log(e);
      return {
        code: -1
      }
    }
  }
}
module.exports = DKtemplateCtl;