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.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 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.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.dkcompanySve.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.dkcompanySve.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) {
    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;