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

        this.utilesignbaoSve = system.getObject("service.utilesignbaoSve");
        this.entcontractSve = system.getObject("service.entcontractSve");
        this.entcompanySve = system.getObject("service.entcompanySve");
        this.DKaggreementService = 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.entcontractSve.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 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;

        if (!req.session.user.isAdmin) {
            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.entcompanySve.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;
            }
        }
        try {
            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.entcompanySve.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");
                }
                var entcompany = await this.entcompanySve.getCompany(info.entcompany_id) || {};
                info.entcompany = entcompany || {};
                if (entcompany) {
                    info.entcompanyName = entcompany.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.entcompanySve.findById(qobj.entcompany_id);

            if (template) { //修改
                template.name = qobj.name;
                template.entcompany_id = qobj.entcompany_id;
                template.remark = qobj.remark || "";
                template.aggreement_id = qobj.aggreement_id;
                await template.save();
            } else { //新增
                template = {};
                template.name = qobj.name || ecompany.name;
                template.entcompany_id = qobj.entcompany_id;
                template.aggreement_id = qobj.aggreement_id;
                template.remark = qobj.remark || "";
                template = await this.service.create(template);
            }

            if (qobj.aggreement_id) {
                var agg = await this.DKaggreementService.findOne({id: qobj.aggreement_id});
                template.codeurl = agg.dataValues.filepath;
                template.templateid = agg.dataValues.templateid;
                template.save();
            }

            return system.getResult2(template, null);
        } catch (e) {
            console.log("-----------------------------e");
            console.log(e);
            return {
                code: -1
            }
        }
    }
}

module.exports = EnttemplateCtl;