const system = require("../../system");
const ServiceBase = require("../sve.base");
const logCtl = system.getObject("web.oplogCtl");

const moment = require('moment');
const crypto = require('crypto');
const cryptoJS = require("crypto-js");
const md5 = require("MD5");

class DKcontractService extends ServiceBase {
    constructor() {
        super(ServiceBase.getDaoName(DKcontractService));
        this.dkcompanyDao = system.getObject("db.dkcompanyDao");
        this.usereaccountDao = system.getObject("db.usereaccountDao")
        this.utilesignbaoSve = system.getObject("service.utilesignbaoSve");
        this.userDao = system.getObject("db.userDao");
        this.restClient = system.getObject("util.restClient");
        this.redisClient = system.getObject("util.redisClient");
        this.bankthreelogDao = system.getObject("db.bankthreelogDao");
        this.dktemplateSve = system.getObject("service.dktemplateSve")
        this.dkaggreementDao = system.getObject("db.dkaggreementDao")
    }

    async getInfo(id) {
        var attrs = [];
        return await this.dao.model.findOne({
            where: {id: id}, attrs, raw: true
        });
    }


    async findSindIds(accountId, dktemplateId) {
        var sql = [];
        sql.push("SELECT id");
        sql.push("FROM `c_dkcontract` ");
        sql.push("WHERE dktemplate_id = :dktemplate_id AND usereaccount_id = :usereaccount_id AND eflowstatus = '2' ");

        var list = await this.customQuery(sql.join(" "), {
            usereaccount_id: Number(accountId),
            dktemplate_id: Number(dktemplateId)
        });
        if (!list || list.length == 0) {
            return [];
        }

        var ids = [];
        for (var item of list) {
            ids.push(item.id);
        }
        return ids;
    }

    async findSignedList(accountId, dktemplateId) {
        var sql = [];
        sql.push("SELECT *");
        sql.push("FROM `c_dkcontract` ");
        sql.push("WHERE dktemplate_id = :dktemplate_id AND usereaccount_id = :usereaccount_id AND eflowstatus = '2' ");

        var list = await this.customQuery(sql.join(" "), {
            usereaccount_id: Number(accountId),
            dktemplate_id: Number(dktemplateId)
        });
        if (!list || list.length == 0) {
            return [];
        }

        for (var item of list) {
            if (item.completed_at) {
                item.completed_at = moment(item.completed_at).format("YYYY-MM-DD HH:mm");
            }
        }
        return list;
    }

    async pageByCondition(params) {
        var currentPage = Number(params.currentPage || 0);
        var pageSize = Number(params.pageSize || 10);

        var where = {};

        if (params.dkcompanyIds) {
            where.dkcompany_id = {
                [this.db.Op.in]: params.dkcompanyIds
            };
        }

        if (params.dktemplateIds) {
            where.dktemplate_id = {
                [this.db.Op.in]: params.dktemplateIds
            };
        }

        if (params.dkcompany_id) {
            where.dkcompany_id = params.dkcompany_id;
        }

        if (params.eflowstatusList) {
            where.eflowstatus = {
                [this.db.Op.in]: params.eflowstatusList
            };
        }

        if (params.accountName || params.accountMobile || params.accountIdno) {
            var accountIds = await this.usereaccountDao.idsByCondition({
                userName: params.accountName || "",
                mobile: params.accountMobile || "",
                personsSign: params.accountIdno || "",
            });

            if (!accountIds || accountIds.length == 0) {
                return {
                    total: 0,
                    rows: []
                };
            }

            where.usereaccount_id = {
                [this.db.Op.in]: accountIds
            };
        }
        this.addWhereTime(where, 'completed_at', params.signBegin, params.signEnd, true);

        let orderby = [
            ["id", 'desc']
        ];

        var attributes = [`id`, `fileurl`, `eflowstatus`, `eflowstatusname`, `completed_at`, `end_at`, `user_id`, `usereaccount_id`, `dkcompany_id`, `dktemplate_id`];

        var page = await this.getPageList(currentPage, pageSize, where, orderby, attributes);
        if (page && page.rows) {
            for (var row of page.rows) {
                this.handleDate(row, ["completed_at", "end_at"], null);
            }
            await this.setEaccount(page.rows);
            await this.setCompany(page.rows);
        }
        return page;
    }

    async setEaccount(list) {
        if (!list || list.length == 0) {
            return;
        }

        var ids = [];
        for (var item of list) {
            ids.push(item.usereaccount_id);
        }
        var attrs = " `id`, `mobile`, `userName`, `personsSign`, `bankno` ";
        var accountMap = await this.usereaccountDao.findMapByIds(ids, attrs);

        for (var item of list) {
            item.eaccount = accountMap["id_" + item.usereaccount_id];
        }
    }

    async setCompany(list) {
        if (!list || list.length == 0) {
            return;
        }

        var companyIds = [];
        for (var item of list) {
            companyIds.push(item.dkcompany_id || 0);
        }
        var companyMap = await this.dkcompanyDao.findMapByIds(companyIds, " id, name ");
        for (var item of list) {
            item.dkcompany = companyMap["id_" + (item.dkcompany_id || 0)] || {};
        }
    }

    async findInfo(obj) {
        obj = obj || {};
        let v = [{
            model: this.db.models.ecompany,
            attributes: ["id", "name"]
        },
            {
                model: this.db.models.user,
                attributes: ["id", "userName", "mobile"]
            },
            {
                model: this.db.models.usereaccount,
                attributes: ["id", "userName", "mobile", "personsSign"]
            },
            {
                model: this.db.models.etemplate,
                attributes: ["id", "name"]
            }
        ];
        var result = await this.dao.model.findOne({
            where: obj,
            include: v
        });
        return result;
    }

    async findContracts(obj) {
        obj = obj || {};
        let v = [{
            model: this.db.models.ecompany,
            attributes: ["id", "name"]
        },
            {
                model: this.db.models.user,
                attributes: ["id", "userName", "mobile"]
            },
            {
                model: this.db.models.usereaccount,
                attributes: ["id", "userName", "mobile", "personsSign"]
            },
            {
                model: this.db.models.etemplate,
                attributes: ["id", "name"]
            }
        ];
        var result = await this.dao.model.findAll({
            where: obj,
            include: v
        });
        return result;
    }

    async updateCallbackStatus(obj) {
        obj = obj || {};

        logCtl.info({
            optitle: "e签宝回调修改合同信息info",
            op: "app/base/service/impl/dkcontractSve/updateCallbackStatus",
            content: "请求参数：" + JSON.stringify(obj),
            clientIp: ""
        });

        let contract;
        try {
            let signTime = obj.signTime;
            let signResult = obj.signResult || "1";
            let thirdOrderNo = Number(obj.thirdOrderNo.substring(3) || 0);

            contract = await this.findById(Number(thirdOrderNo));
            if (!contract) {
                return;
            }

            contract.eflowstatus = signResult.toString();
            contract.completed_at = signTime;
            contract.begin_at = signTime;
            contract.resultDescription = obj.resultDescription || "";
            var end_at = new Date(signTime);
            end_at.setFullYear(end_at.getFullYear() + 1);
            contract.end_at = end_at;

            // 合同下载任务
            this.redisClient.rpushBCD({id: contract.id, sve: "dk"});
            await contract.save();
        } catch (e) {
            logCtl.error({
                optitle: "e签宝回调修改合同信息error",
                op: "app/base/service/impl/dkcontractSve/updateCallbackStatus",
                content: "错误信息：" + e.stack,
                clientIp: ""
            });
        }
        return contract;
    }

    async downloadCompleteUrl(limit) {
        var sql = "SELECT id FROM `c_dkcontract` WHERE eflowstatus = '2' AND (fileurl IS NULL OR fileurl = '')  ORDER BY id DESC ";
        if (limit) {
            sql = sql + " LIMIT " + limit;
        }
        var list = await this.dao.customQuery(sql);

        if (!list || list.length == 0) {
            return;
        }

        for (var o of list) {
            var id = o.id;
            try {
                var contract = await this.dao.findById(id);
                if (!contract) {
                    continue;
                }

                if (contract.eflowstatus != "2") {
                    continue;
                }

                if (!contract.fileurl) {
                    //  请求文件地址
                    let fileRs = await this.utilesignbaoSve.downloadUserContractFile(contract.eflowid, "econtractSve");
                    console.log(fileRs, "===============================================================");
                    if (fileRs.code == 1 && fileRs.data.selfossUrl) {
                        contract.fileurl = fileRs.data.selfossUrl;
                        contract.save();
                    } else {
                        await this.utilesignbaoSve.archiveProcess({flowId: contract.eflowid}, "econtractSve");
                        let fileRs = await this.utilesignbaoSve.downloadUserContractFile(contract.eflowid, "econtractSve");
                        if (fileRs.code == 1 && fileRs.data.selfossUrl) {
                            contract.fileurl = fileRs.data.selfossUrl;
                            contract.save();
                        }
                    }
                }
            } catch (e) {
                console.error(e);
                //日志记录
                logCtl.error({
                    optitle: "定时下载合同任务异常, id=" + id,
                    op: "app/base/service/impl/econtractSve.js",
                    content: e.stack,
                    clientIp: ""
                });
                return {
                    code: -200,
                    message: "error",
                    data: {}
                };
            }
        }
    }

    async downloadContract(id) {
        try {
            let contract = await this.dao.findById(id);
            if (!contract || contract.eflowstatus != "2" || contract.fileurl) {
                return;
            }

            //await this.syncYzSign(2134);
            //  请求文件地址
            let fileRs = await this.utilesignbaoSve.downloadUserContractFile(contract.eflowid, "econtractSve");
            if (fileRs.code == 1 && fileRs.data.selfossUrl) {
                contract.fileurl = fileRs.data.selfossUrl;
                await contract.save();
                this.syncYzSign(contract.id);
            } else {
                await this.utilesignbaoSve.archiveProcess({flowId: contract.eflowid}, "econtractSve");
                let fileRs = await this.utilesignbaoSve.downloadUserContractFile(contract.eflowid, "econtractSve");
                if (fileRs.code == 1 && fileRs.data.selfossUrl) {
                    contract.fileurl = fileRs.data.selfossUrl;
                    await contract.save();
                    this.syncYzSign(contract.id);
                }
            }
        } catch (e) {
            console.error(e);
            return {
                code: -200,
                message: "error",
                data: {}
            };
        }
    }

    async getContractUrl(id) {
        var contract = await this.findById(id);
        if (contract.fileurl) {
            return contract.fileurl;
        }

        let fileRs = await this.utilesignbaoSve.downloadUserContractFile(contract.eflowid, "econtractSve");
        if (fileRs.code == 1 && fileRs.data.selfossUrl) {
            contract.fileurl = fileRs.data.selfossUrl;
            await contract.save();
            return contract.fileurl;
        }
        return "";
    }

    async testtransfer(result) {
        var date = new Date().Format("yyyy-MM-dd hh:mm:ss");
        var v = JSON.stringify(result) + "---" + date;
        var sql = "INSERT INTO `testtransfer` (`v`) VALUES ('" + v + "')  ";
        await this.dao.customExecAddOrPutSql(sql, {});
    }

    async formateTime(inputTime) {
        var date = new Date(inputTime);
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? ('0' + m) : m;
        var d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        var h = date.getHours();
        h = h < 10 ? ('0' + h) : h;
        var minute = date.getMinutes();
        var second = date.getSeconds();
        minute = minute < 10 ? ('0' + minute) : minute;
        second = second < 10 ? ('0' + second) : second;
        return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
    }

    async formateTime2(inputTime) {
        if (!inputTime) {
            return '';
        }
        var date = new Date(inputTime);
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? ('0' + m) : m;
        var d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        var h = date.getHours();
        h = h < 10 ? ('0' + h) : h;
        var minute = date.getMinutes();
        var second = date.getSeconds();
        minute = minute < 10 ? ('0' + minute) : minute;
        second = second < 10 ? ('0' + second) : second;
        return y + '' + m + '' + d + '' + h + '' + minute + '' + second;
    }

    async getUidStr(len, radix) {
        var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
        var uuid = [],
            i;
        radix = radix || chars.length;
        if (len) {
            for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
        } else {
            var r;
            uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
            uuid[14] = '4';
            for (i = 0; i < 36; i++) {
                if (!uuid[i]) {
                    r = 0 | Math.random() * 16;
                    uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
                }
            }
        }
        return uuid.join('');
    }

    async autoSign(params) {
        var ecid = params.ecid;
        var unionId = params.appId + "_" + params.userId + "_" + params.idNo;
        // ecid dketemplate
        var etemplate = await this.dktemplateSve.findById(ecid);
        // dkecompany
        var dkcompany = await this.dkcompanyDao.findById(etemplate.dkcompany_id);

        // p_user
        var user = await this.userDao.findOne({
            unionId: unionId,
        });
        if (!user) {
            user = await this.userDao.create({
                appkey: params.appId,
                unionId: unionId,
                userId3rd: params.userId,
                userName: params.idName,
                mobile: params.mobile,
                utype: 0,
            });
        }

        // p_user_eaccount
        var eaccount = await this.usereaccountDao.findOne({
            user_id: user.id,
            personsSign: params.idNo,
        }) || {};

        var isNeedCreate = !eaccount.eaccountid || eaccount.userName != params.idName || eaccount.mobile != params.mobile || eaccount.bankno != params.bankno;

        eaccount.user_id = user.id;
        eaccount.userName = params.idName;
        eaccount.mobile = params.mobile;
        eaccount.bankno = params.bankno;
        eaccount.personsSign = params.idNo;
        if (eaccount.id) {
            await eaccount.save();
        } else {
            eaccount = await this.usereaccountDao.create(eaccount);
        }

        let banklog = await this.bankthreelogDao.findOne({
            userName: eaccount.userName,
            userIdNo: eaccount.personsSign,
            userBankNo: eaccount.bankno,
            result: 1,
        });

        if (!banklog) {
            var bankthreeParams = {
                name: eaccount.userName,
                idno: eaccount.personsSign,
                cardno: eaccount.bankno
            };

            var threeResult = await this.utilesignbaoSve.bankthree(bankthreeParams, "bankinfoAuth");
            console.log("threeResult-----------------------------", threeResult);
            if (!threeResult || threeResult.code == -120) {
                return this.returnjson(-1, "银行三要素（姓名、身份证、银行卡号）验证失败");
            }
            if (threeResult.code == -110) {
                return this.returnjson(-1, "银行三要素验证失败");
            }
        }

        // c_dkecontract
        var dkecontract = await this.dao.findOne({
            eflowstatus: '2',
            usereaccount_id: eaccount.id,
            dktemplate_id: ecid,
        });

        if (dkecontract) {
            return this.returnjson(0, "用户已经签约", {
                contractId: dkecontract.id
            });
        }


        if (isNeedCreate) {
            var uidStr = await this.getUidStr(8, 36);
            var thirdId = etemplate.id + "_" + eaccount.id + uidStr;
            //创建e签宝account 5.2.1 , 创建后save()
            var params = {
                thirdId: thirdId,
                name: eaccount.userName,
                idNo: eaccount.personsSign,
                idType: 19,
                mobile: eaccount.mobile
            };
            var getAccount = await this.utilesignbaoSve.createAccountId(params, "econtractSve");
            if (getAccount && getAccount.code == 1 && getAccount.data) {
                eaccount.eaccountid = getAccount.data.accountId;
                await eaccount.save();
            } else {
                return this.returnjson(-1, "账户创建失败");
            }
        }

        // 设置静默签署授权 5.2.5
        if (!eaccount.isGrantAuto) {
            var paramsGrant = {
                grantAccountId: eaccount.eaccountid
            };
            var grantAuto = await this.utilesignbaoSve.grantAuthorization(paramsGrant, "econtractSve");
            if (grantAuto.code != 1) {
                return this.returnjson(-1, "静默签署设置失败");
            }
            eaccount.isGrantAuto = true;
            await eaccount.save();
        }

        dkecontract = {
            name: dkcompany.name,
            dktemplate_id: ecid,
            user_id: user.id,
            usereaccount_id: eaccount.id,
            dkcompany_id: dkcompany.id,
            edocid: "",
            eflowid: "",
            esignUrl: "",
            eflowstatus: "1",
        }
        dkecontract = await this.create(dkecontract);

        var dkaggreement = await this.dkaggreementDao.findById(etemplate.dkaggreement_id);
        var params = {
            templateId: dkaggreement.templateid, //模板id，由创建模板接口调用返回的templateId 必填
            name: dkcompany.name, //合同模板名称 必填

            simpleFormFields: {
                nameA: dkcompany.name, //甲方 必填
                addressA: dkcompany.addr,  // 甲方地址
                phoneA: dkcompany.phone,  // 甲方电话

                nameB: eaccount.userName, //乙方姓名 必填
                phoneB: eaccount.mobile, //乙方电话 必填

                nameC: eaccount.userName, // 已方姓名
                phoneC: eaccount.mobile,  // 乙方电话
                idcardC: eaccount.personsSign,  // 乙方身份证
                banknoC: eaccount.bankno, // 乙方银行卡号

                signdate: moment().format("YYYY/MM/DD"),    // 签约日期
            }
        };
        var ebaoAccountId = eaccount.eaccountid; //签署人账户id-- 必填
        var thirdOrderNo = "dk_" + dkecontract.id; //第三方流水号，通知回调使用---选填
        var eBaoRedirectBossUrl = "";

        var sealId = dkcompany.sealId;
        let tt = await this.utilesignbaoSve.userAutoSignContractNoTemplate(params, ebaoAccountId, thirdOrderNo, eBaoRedirectBossUrl, "econtractSve", sealId);
        console.log("-============= result ===========================", tt);
        if (tt && tt.data && tt.code == 1) {
            dkecontract.eflowid = tt.data.flowId;
            dkecontract.edocid = tt.data.docId;
            dkecontract.eflowstatus = '2',
                dkecontract.esignUrl = tt.data.signUrl;

            var signTime = new Date();
            dkecontract.completed_at = signTime;
            dkecontract.begin_at = signTime;
            var end_at = new Date();
            end_at.setFullYear(end_at.getFullYear() + 1);
            dkecontract.end_at = end_at;

            dkecontract.save();
        }
        this.redisClient.rpushBCD({id: dkecontract.id, sve: "dk"});

        return this.returnjson(0, "success", {
            contractId: dkecontract.id
        });

        return this.returnjson(-1, tt.message || "签约失败", tt.code);
    }

    async autoSignNew(params) {
        let ecid = params.ecid;
        let unionId = params.appId + "_" + params.idNo;

        let todays = moment().format("YYYY-MM-DD") + " 00:00:00";
        let contractId = await this.dao.findSignedContractId({idno: params.idNo, ecid: ecid, today : todays}) || 0;
        if (contractId) {
            return this.returnjson(0, "用户已经签约", {
                contractId: contractId
            });
        }

        // ecid dketemplate
        let etemplate = await this.dktemplateSve.findById(ecid);
        // dkecompany
        let dkcompany = await this.dkcompanyDao.findById(etemplate.dkcompany_id);
        // p_user
        let user = await this.userDao.findOne({
            unionId: unionId,
        });
        if (!user) {
            user = await this.userDao.create({
                appkey: params.appId,
                unionId: unionId,
                userId3rd: params.userId,
                userName: params.idName,
                mobile: params.mobile,
                utype: 0,
            });
        }

        // p_user_eaccount
        let eaccount = await this.usereaccountDao.findOne({
            user_id: user.id,
            personsSign: params.idNo,
        }) || {};

        let isNeedCreate = !eaccount.eaccountid || eaccount.userName != params.idName || eaccount.mobile != params.mobile || eaccount.bankno != params.bankno;

        eaccount.user_id = user.id;
        eaccount.userName = params.idName;
        eaccount.mobile = params.mobile;
        eaccount.bankno = params.bankno;
        eaccount.personsSign = params.idNo;
        if (!eaccount.id) {
            eaccount = await this.usereaccountDao.create(eaccount);
        }

        // c_dkecontract
        if (eaccount.id) {
            await eaccount.save();
        }
        if (isNeedCreate) {
            let uidStr = await this.getUidStr(8, 36);
            let thirdId = ecid + "_" + eaccount.id + uidStr;
            //创建e签宝account 5.2.1 , 创建后save()
            let cparams = {
                thirdId: thirdId,
                name: eaccount.userName,
                idNo: eaccount.personsSign,
                idType: 19,
                mobile: eaccount.mobile
            };
            var getAccount = await this.utilesignbaoSve.createAccountId(cparams, "econtractSve");
            if (getAccount && getAccount.code == 1 && getAccount.data) {
                eaccount.eaccountid = getAccount.data.accountId;
                await eaccount.save();
            } else {
                return this.returnjson(-1, "账户创建失败");
            }
        }

        // 设置静默签署授权 5.2.5
        if (!eaccount.isGrantAuto) {
            var paramsGrant = {
                grantAccountId: eaccount.eaccountid
            };
            var grantAuto = await this.utilesignbaoSve.grantAuthorization(paramsGrant, "econtractSve");
            if (grantAuto.code != 1) {
                return this.returnjson(-1, "静默签署设置失败");
            }
            eaccount.isGrantAuto = true;
            await eaccount.save();
        }

        let dkecontract = {
            name: dkcompany.name,
            dktemplate_id: ecid,
            user_id: user.id,
            usereaccount_id: eaccount.id,
            dkcompany_id: dkcompany.id,
            edocid: "",
            eflowid: "",
            esignUrl: "",
            eflowstatus: "1",
        }
        dkecontract = await this.create(dkecontract);

        var dkaggreement = await this.dkaggreementDao.findById(etemplate.dkaggreement_id);
        var contractParams = {
            templateId: dkaggreement.templateid, //模板id，由创建模板接口调用返回的templateId 必填
            name: dkcompany.name, //合同模板名称 必填

            simpleFormFields: {
                nameA: dkcompany.name, //甲方 必填
                addressA: dkcompany.addr,  // 甲方地址
                phoneA: dkcompany.phone,  // 甲方电话

                nameB: eaccount.userName, //乙方姓名 必填
                phoneB: eaccount.mobile, //乙方电话 必填

                nameC: eaccount.userName, // 已方姓名
                phoneC: eaccount.mobile,  // 乙方电话
                idcardC: eaccount.personsSign,  // 乙方身份证
                banknoC: eaccount.bankno, // 乙方银行卡号

                signdate: moment().format("YYYY/MM/DD"),    // 签约日期
            }
        };
        var ebaoAccountId = eaccount.eaccountid; //签署人账户id-- 必填
        var thirdOrderNo = "dk_" + dkecontract.id; //第三方流水号，通知回调使用---选填
        var eBaoRedirectBossUrl = "";

        var sealId = dkcompany.sealId;
        let tt = await this.utilesignbaoSve.userAutoSignContractNoTemplate(contractParams, ebaoAccountId, thirdOrderNo, eBaoRedirectBossUrl, "econtractSve", sealId);
        console.log("-============= result ===========================", tt);
        if (tt && tt.data && tt.code == 1) {
            dkecontract.eflowid = tt.data.flowId;
            dkecontract.edocid = tt.data.docId;
            dkecontract.eflowstatus = '2',
              dkecontract.esignUrl = tt.data.signUrl;

            var signTime = new Date();
            dkecontract.completed_at = signTime;
            dkecontract.begin_at = signTime;
            var end_at = new Date();
            end_at.setFullYear(end_at.getFullYear() + 1);
            dkecontract.end_at = end_at;

            dkecontract.save();
        }
        this.redisClient.rpushBCD({id: dkecontract.id, sve: "dk"});

        return this.returnjson(0, "success", {
            contractId: dkecontract.id
        });
    }

    /**
     * 内部app签约
     * @param params
     * @returns {Promise<number>}
     */
    async appAutoSign(params) {
        let ecid = params.ecid;
        let usereaccountId = params.usereaccountId;
        let eaccount = await this.usereaccountDao.findById(usereaccountId);
        if (!eaccount || !eaccount.eaccountid) {
            return system.getErrResult2("账户不存在");
        }
        if (params.forceFace && !eaccount.face_auth_img) {
            return system.getErrResult2("请先进行人脸识别");
        }
        let todays = moment().format("YYYY-MM-DD") + " 00:00:00";
        let contractId = await this.dao.findSignedContractId({idno: eaccount.personsSign, ecid: ecid, today : todays}) || 0;
        if (contractId) {
            return system.getResult2({contractId: contractId}, {}, "用户已签约");
        }

        // ecid dketemplate
        let etemplate = await this.dktemplateSve.findById(ecid);
        // dkecompany
        let dkcompany = await this.dkcompanyDao.findById(etemplate.dkcompany_id);
        // 设置静默签署授权 5.2.5
        if (!eaccount.isGrantAuto) {
            var grantAuto = await this.utilesignbaoSve.grantAuthorization({grantAccountId: eaccount.eaccountid}, "dkcontractSve");
            if (grantAuto.code != 1) {
                return system.getErrResult2("静默签署设置失败");
            }
            eaccount.isGrantAuto = true;
            await eaccount.save();
        }

        let dkecontract = {
            name: dkcompany.name,
            dktemplate_id: ecid,
            user_id: eaccount.user_id,
            usereaccount_id: eaccount.id,
            dkcompany_id: dkcompany.id,
            edocid: "",
            eflowid: "",
            esignUrl: "",
            eflowstatus: "1",
        }
        dkecontract = await this.create(dkecontract);

        var dkaggreement = await this.dkaggreementDao.findById(etemplate.dkaggreement_id);
        var contractParams = {
            templateId: dkaggreement.templateid, //模板id，由创建模板接口调用返回的templateId 必填
            name: dkcompany.name, //合同模板名称 必填

            simpleFormFields: {
                nameA: dkcompany.name, //甲方 必填
                addressA: dkcompany.addr,  // 甲方地址
                phoneA: dkcompany.phone,  // 甲方电话

                nameB: eaccount.userName, //乙方姓名 必填
                phoneB: eaccount.mobile, //乙方电话 必填

                nameC: eaccount.userName, // 已方姓名
                phoneC: eaccount.mobile,  // 乙方电话
                idcardC: eaccount.personsSign,  // 乙方身份证
                banknoC: eaccount.bankno, // 乙方银行卡号

                signdate: moment().format("YYYY/MM/DD"),    // 签约日期
            }
        };
        var ebaoAccountId = eaccount.eaccountid; //签署人账户id-- 必填
        var thirdOrderNo = "dk_" + dkecontract.id; //第三方流水号，通知回调使用---选填
        var eBaoRedirectBossUrl = "";

        var sealId = dkcompany.sealId;
        let tt = await this.utilesignbaoSve.userAutoSignContractNoTemplate(contractParams, ebaoAccountId, thirdOrderNo, eBaoRedirectBossUrl, "econtractSve", sealId);
        console.log("-============= result ===========================", tt);
        if (tt && tt.data && tt.code == 1) {
            dkecontract.eflowid = tt.data.flowId;
            dkecontract.edocid = tt.data.docId;
            dkecontract.eflowstatus = '2',
            dkecontract.esignUrl = tt.data.signUrl;

            let signTime = new Date();
            dkecontract.completed_at = signTime;
            dkecontract.begin_at = signTime;
            let end_at = new Date();
            end_at.setFullYear(end_at.getFullYear() + 1);
            dkecontract.end_at = end_at;
            await dkecontract.save();
        }
        this.redisClient.rpushBCD({id: dkecontract.id, sve: "dk"});
        return system.getResult2({contractId: dkecontract.id}, {}, "success");
    }

    async findSingleSignedUser(params) {
        let sql = [];
        sql.push("SELECT t1.id,t1.begin_at as beginDate,t1.end_at as endDate,");
        sql.push("t2.userName AS idName, t2.mobile ,t2.`personsSign` AS idNo, t1.completed_at AS signTime, t2.bankno AS bankNo,");
        sql.push("t1.fileurl AS fileUrl");
        sql.push("FROM c_dkcontract t1");
        sql.push("INNER JOIN p_user_eaccount t2 ON t1.`usereaccount_id` = t2.`id`");
        sql.push("WHERE t1.`dktemplate_id` = :dktemplate_id AND t1.`eflowstatus` = '2' AND t1.`end_at`>= NOW()");
        sql.push("AND t2.`personsSign` = :idNo");
        sql.push("ORDER BY t1.id ASC LIMIT 1");
        let list = await this.dao.customQuery(sql.join(" "), params);
        if (!list || list.length == 0) {
            return null;
        }
        for (let item of list) {
            item.signTime = await this.formateTime(item.signTime);
            item.beginDate = await this.formateTime(item.beginDate);
            item.endDate = await this.formateTime(item.endDate);
        }
        return list[0];
    }

    returnjson(code, msg, data) {
        return {
            code: code,
            msg: msg,
            data: data || null
        }
    }
}

module.exports = DKcontractService;
