var system = require("../../system")
const md5 = require("MD5");
const logCtl = system.getObject("web.oplogCtl");
const moment = require("moment");
const uuidv1 = require('uuid/v1');
class EcontractApi {
    constructor() {
        this.ecompanySve = system.getObject("service.ecompanySve");
        this.econtractSve = system.getObject("service.econtractSve");
        this.etemplateSve = system.getObject("service.etemplateSve");
        this.utilesignbaoSve = system.getObject("service.utilesignbaoSve");

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

        this.ecompanywxuserSve = system.getObject("service.ecompanywxuserSve");
        this.ecompanybpoSve = system.getObject("service.ecompanybpoSve");

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

        this.wxSve = system.getObject("service.wxSve");
        this.esettleSve = system.getObject("service.esettleSve");
        this.etemplatebusiSve = system.getObject("service.etemplatebusiSve");

        this.bankthreelogSve = system.getObject("service.bankthreelogSve");
        this.bankthreelog2Sve = system.getObject("service.bankthreelog2Sve");
        this.idcardClient = system.getObject("util.idcardClient");
        this.restClient = system.getObject("util.restClient");
        this.smsS = system.getObject("util.smsClient");
        this.econtractofflineSve = system.getObject("service.econtractofflineSve");

        this.redisLock = system.getObject("util.redisLock");
    }

    async syncSignedFile() {
        this.econtractSve.downloadCompleteUrl();
        return "start success"
    }

    async importECompany(obj) {
        console.log(obj, "===================>>>>>>>>>>>>>>>>>>>>>");
        var names = obj.companyNames;
        var nameA = obj.nameA || '智信云（天津）科技有限公司';
        var encryptkey = obj.encryptkey;
        var posturl = obj.posturl;
        var etemplate = await this.etemplateSve.findById(Number(obj.etemplateId || 0));
        if (!etemplate) {
            return 0;
        }

        for (var name of names) {
            try {
                console.log("========== import ecompany : " + name);
                let rs = await this.ecompanySve.importCompany(name, nameA, encryptkey, posturl, etemplate);
            } catch (e) {
                console.log(e);
            }
        }
        return 1;
    }

    async importETemplate(obj) {
        console.log(obj, "===================>>>>>>>>>>>>>>>>>>>>>");
        var names = obj.companyNames;
        var etemplateId = obj.etemplateId;
        var etemplate = await this.etemplateSve.findById(Number(etemplateId || 0));
        if (!etemplate) {
            return 0;
        }
        let errors = [];
        let ids = [];
        for (var name of names) {
            try {
                let company = await this.ecompanySve.findOne({name: name});
                if (!company) {
                    errors.push(name);
                    continue;
                }
                // 创建模板
                var newTemplate = {
                    ecompany_id:company.id,
                    name:name,
                    ecompanyMainId : etemplate.ecompanyMainId,
                    mainId:etemplate.mainId,
                    nameA : etemplate.nameA,
                    templateid:etemplate.templateid,
                    filekey:etemplate.filekey,//e签宝返回文件key
                    filepath:etemplate.filepath,//需要在后台补充
                    placeholderkey:etemplate.placeholderkey,//模板占位信息
                    isEnabled:true,
                };
                newTemplate =  await this.etemplateSve.create(newTemplate);
                ids.push(newTemplate.id);
            } catch (e) {
                console.log(e);
            }
        }
        this.addqrcodeurl({ids: ids});
        return errors;
    }


   async addqrcodeurl(obj){
       let ids = obj.ids || [];
       if (!ids || ids.length == 0) {
           return "no ids";
       }
       for (let id of ids) {
           try {
               var newTemplate = await this.etemplateSve.findById(id);
               if (newTemplate) {
                   var qrcodeurl = await this.wxSve.makeQrWithScene("wxf616c0a459d66081", newTemplate.id);
                   newTemplate.qrcodeurl = qrcodeurl;
                   await newTemplate.save();
               }
           } catch (e) {
               console.log(e, id, "addqrcodeurl");
           }
       }
    }

    async testpushContract(obj, req) {
        var ids = obj.ids || [];
        for (var id of ids) {
            // this.econtractSve.syncSign(67854);
            await this.econtractSve.syncSign(id);
        }
    }

    async pushwxuser(obj, req) {
        var ids = obj.ids || [];
        var result = [];
        for (var id of ids) {
            // this.econtractSve.syncSign(67854);
            try {
                var rs = await this.ecompanywxuserSve.pushwxuser(id);
                result.push(rs);
            } catch (error) {
                result.push(error.msg);
            }
        }
        return result;
    }

    async validContract(obj, req) {
        // 验证合法性
        var companyName = obj.companyName;
        var idCardList = obj.idCardList;

        var sign = md5("companyName=" + companyName + "&nonceStr=" + obj.nonceStr + "&key=wxf616c0a459d66081").toUpperCase();
        if (sign != obj.sign) {
            return {
                code: 1,
                msg: "签名失败"
            };
        }

        //日志记录
        if (!idCardList || idCardList.length == 0) {
            return {
                code: 0,
                msg: "success",
                signedList: [],
                unSignList: []
            };
        }

        var ecompany = await this.ecompanySve.findOne({
            name: companyName
        });
        if (!ecompany) {
            return {
                code: 1,
                msg: "公司不存在"
            };
        }


        for(var idcard in idCardList){
            idcard = idcard.toUpperCase();
        }

        try {
            var signedList = await this.econtractSve.fiterSignedCards(ecompany.id, idCardList);
            var unSignList = [];
            for (var ic of idCardList) {
                if (signedList.indexOf(ic) == -1) {
                    unSignList.push(ic);
                }
            }
            var result = {
                code: 0,
                msg: "success",
            };
            result.signedList = signedList;
            result.unSignList = unSignList;
            return result;
        } catch (e) {
            var result = {
                code: 500,
                msg: "接口异常"
            };
            console.log(e.stack);
            //日志记录
            logCtl.error({
                optitle: "校验是否签约error",
                op: "api/econtractApi/validContract",
                content: e.stack,
                clientIp: req.clientIp
            });
            return result;
        }
    }

    async transferNotify(obj, req) {
        this.econtractSve.testtransfer(obj);
    }

    async contractcb(obj, req) {
        this.econtractSve.updateCallbackStatus(obj);
    }

    async synctemplate(obj, req) {
        for (var id = 1; id <= 514; id++) {
            try {
                var template = await this.etemplateSve.findById(id);
                if (!template) {
                    continue;
                }
                template.qrcodeurl = await this.wxSve.makeQrWithScene("wxf616c0a459d66081", template.id);
                await template.save();
            } catch (error) {
                console.log(error);
            }
        }

        for (var id = 10000; id <= 10100; id++) {
            try {
                var template = await this.etemplateSve.findById(id);
                if (!template) {
                    continue;
                }
                template.qrcodeurl = await this.wxSve.makeQrWithScene("wxf616c0a459d66081", template.id);
                await template.save();
            } catch (error) {
                console.log(error);
            }
        }
    }

    async sinedUsers(obj, req) {
        // 验证合法性
        var appId = obj.appId;
        var nonceStr = obj.nonceStr;
        var idNo = obj.idNo;
        var startId = obj.startId || 0;
        var userId = obj.userId || "";
        var userCode = obj.userCode || "";
        var branchCode = obj.branchCode || "";
        var pageSize = 20;

        var busi = await this.ecompanybusiSve.findOne({
            appId: appId
        });
        if (!busi) {
            return {
                code: 1001003,
                msg: "配置信息错误，请联系薪必果人员进行配置"
            };
        }

        var signArr = [];
        signArr.push("appId=" + appId);
        signArr.push("branchCode=" + branchCode);
        signArr.push("idNo=" + idNo);
        signArr.push("nonceStr=" + nonceStr);
        signArr.push("startId=" + startId);
        signArr.push("userCode=" + userCode);
        signArr.push("userId=" + userId);
        signArr.push("key=" + busi.key);

        var sign = md5(signArr.join("&")).toUpperCase();
        console.log(sign)
        if (sign != obj.sign) {
            return {
                code: 1001001,
                msg: "签名失败"
            };
        }
        var params = {
            ecompanyId: busi.ecompany_id,
            startId: startId,
            idNo: idNo.toUpperCase(),
            pageSize: pageSize,
            userId3rd: userId,
            userCode3rd: userCode,
            branchCode3rd: branchCode,
        };

        try {
            var userList = await this.econtractSve.findSignedUses4Push(params);

            var result = {
                code: 0,
                msg: "success",
            };
            result.data = userList;
            return result;
        } catch (e) {
            var result = {
                code: 500,
                msg: "接口异常"
            };
            console.log(e.stack);
            //日志记录
            logCtl.error({
                optitle: "校验是否签约error",
                op: "api/econtractApi/validContract",
                content: e.stack,
                clientIp: req.clientIp
            });
            return result;
        }
    }

    async sinedUsers3rd(obj, req) {
        // 验证合法性
        var appId = obj.appId;
        var nonceStr = obj.nonceStr;
        var idNo = obj.idNo;
        var startId = obj.startId || 0;
        var userId = obj.userId || "";
        var pageSize = 20;

        var busi = await this.ecompanybusiSve.findOne({
            appId: appId
        });
        if (!busi) {
            return {
                code: 1001003,
                msg: "配置信息错误，请联系薪必果人员进行配置"
            };
        }

        var signArr = [];
        signArr.push("appId=" + appId);
        signArr.push("idNo=" + idNo);
        signArr.push("nonceStr=" + nonceStr);
        signArr.push("startId=" + startId);
        signArr.push("userId=" + userId);
        signArr.push("key=" + busi.key);
        var signStr = signArr.join("&")
        var sign = md5(signStr).toUpperCase();
        console.log(signStr, sign);

        if (sign != obj.sign) {
            return {
                code: 1001001,
                msg: "签名失败"
            };
        }
        let idNos = await this.usereaccountSve.idNoByUserId3rd(userId);

        var params = {
            ecompanyId: busi.ecompany_id,
            startId: startId,
            idNo: idNo.toUpperCase(),
            pageSize: pageSize,
        };
        if (idNos && idNos.length > 0) {
            params.idNos = idNos;
        }

        try {
            let userList = await this.econtractSve.findSignedUses4Push(params);
            if (userId && userList && userList.length > 0) {
                for (let u of userList) {
                    u.userId3rd = userId;
                }
            }
            var result = {
                code: 0,
                msg: "success",
            };
            result.data = userList;
            return result;
        } catch (e) {
            var result = {
                code: 500,
                msg: "接口异常"
            };
            console.log(e.stack);
            //日志记录
            logCtl.error({
                optitle: "校验是否签约error",
                op: "api/econtractApi/validContract",
                content: e.stack,
                clientIp: req.clientIp
            });
            return result;
        }
    }

    async sinedUser(obj, req) {
        // 验证合法性
        let appId = obj.appId;
        let nonceStr = obj.nonceStr;
        let ecid = obj.ecid || "";
        let idNo = obj.idNo;

        let busi = await this.ecompanybusiSve.findOne({
            appId: appId
        });
        if (!busi) {
            return {
                code: 1001003,
                msg: "配置信息错误，请联系薪必果人员进行配置"
            };
        }

        let signArr = [];
        signArr.push("appId=" + appId);
        signArr.push("ecid=" + ecid);
        signArr.push("idNo=" + idNo);
        signArr.push("nonceStr=" + nonceStr);
        signArr.push("key=" + busi.key);
        let signStr = signArr.join("&")
        let sign = md5(signStr).toUpperCase();
        console.log(signStr, sign);

        if (sign != obj.sign) {
            return {
                code: 1001001,
                msg: "签名失败"
            };
        }
        let params = {
            etemplate_id: ecid,
            idNo: idNo.toUpperCase(),
        };

        try {
            let user = await this.econtractSve.findSingleSignedUser(params);
            let result = {
                code: 0,
                msg: "success",
                data: user
            };
            return result;
        } catch (e) {
            let result = {
                code: 500,
                msg: "接口异常"
            };
            console.log(e.stack);
            return result;
        }
    }


    async sinedEcontractStatus(obj, req) {
        // 验证合法性
        var appId = obj.appId;
        var ecId = obj.ecId;
        var idNo = obj.idNo;
        var nonceStr = obj.nonceStr;

        if (!appId) {
            return this.returnjson(-1, "请传入薪必果提供的appId")
        }
        if (!ecId) {
            return this.returnjson(-1, "请传入薪必果提供的ecid")
        }
        if (!idNo) {
            return this.returnjson(-1, "请传入身份证号")
        }

        var busi = await this.ecompanybusiSve.findOne({
            appId: appId
        });
        if (!busi) {
            return {
                code: 1001003,
                msg: "配置信息错误，请联系薪必果人员进行配置"
            };
        }

        var signArr = [];
        signArr.push("appId=" + appId);
        signArr.push("ecId" + ecId);
        signArr.push("idNo=" + idNo);
        signArr.push("nonceStr=" + nonceStr);
        signArr.push("key=" + busi.key);

        var sign = md5(signArr.join("&")).toUpperCase();
        console.log(sign)
        if (sign != obj.sign) {
            return {
                code: 1001001,
                msg: "签名失败"
            };
        }
        var params = {
            etemplate_id: ecId,
            idNo: idNo.toUpperCase(),
        };

        try {
            var  contractStatus = await this.econtractSve.sinedEcontractStatus(params);

            var result = {
                code: 0,
            };
            if(contractStatus.length == 0 ){
                result.msg = "未发起签约";
                result.data = {
                    status: 0,
                    statusName: "未发起签约"
                };
            }else if(contractStatus.indexOf('2') != -1 ){
                result.msg = "签约完成";
                result.data = {
                    status: 2,
                    statusName: "签约完成"
                };
            }else if(contractStatus.indexOf('3') != -1){
                result.msg = "签约失败";
                result.data = {
                    status: 3,
                    statusName: "签约失败"
                };
            }else{
                result.msg = "签约中";
                result.data = {
                    status: 1,
                    statusName: "签署中"
                };
            }
            return result;
        } catch (e) {
            var result = {
                code: 500,
                msg: "接口异常"
            };
            console.log(e.stack);
            //日志记录
            logCtl.error({
                optitle: "校验是否签约error",
                op: "api/econtractApi/validContract",
                content: e.stack,
                clientIp: req.clientIp
            });
            return result;
        }
    }

    async sinedList(obj, req) {
        // 验证合法性
        var companyName = obj.companyName;
        var startId = obj.startId || 0;
        var pageSize = obj.pageSize || 20;

        var sign = md5("companyName=" + companyName + "&nonceStr=" + obj.nonceStr + "&startId=" + startId + "&key=wxf616c0a459d66081").toUpperCase();
        if (sign != obj.sign) {
            return {
                code: 1,
                msg: "签名失败"
            };
        }

        var ecompany = await this.ecompanySve.findOne({
            name: companyName
        });
        if (!ecompany) {
            return {
                code: 1,
                msg: "公司不存在"
            };
        }

        try {
            var userList = await this.econtractSve.findSignedUsers(ecompany.id, startId, pageSize);

            var result = {
                code: 0,
                msg: "success",
            };
            result.data = userList;
            return result;
        } catch (e) {
            var result = {
                code: 500,
                msg: "接口异常"
            };
            console.log(e.stack);
            //日志记录
            logCtl.error({
                optitle: "校验是否签约error",
                op: "api/econtractApi/validContract",
                content: e.stack,
                clientIp: req.clientIp
            });
            return result;
        }
    }

    async bankthreeItem(item) {
        var bankthreelog2 = {
            idName: item.idName,
            idNo: item.idNo.toUpperCase(),
            bankno: item.bankno,
            pass: false,
        }
        try {
            var bankthreeParams = {
                name: item.idName, //姓名 必填
                idno: item.idNo.toUpperCase(), //身份证 必填
                cardno: item.bankno //银行卡 必填
            };

            var tt = await this.utilesignbaoSve.bankthree(bankthreeParams, "econtractapi.bankthreeBatch") || {};
            // {"code":-110,"message":"手机号格式错误","data":{}}
            //1成功,-110提示验证信息有误，-120亲，提供的信息不正确，请验证后再试！
            console.log("tt-----------------------------", tt);
            if (tt.code == 1) {
                bankthreelog2.pass = true;
            } else if (tt.code == -110) {
                bankthreelog2.remark = tt.message;
            } else {
                bankthreelog2.remark = "银行三要素验证失败";
            }
        } catch (error) {
            bankthreelog2.remark = "接口异常";
        }
        await this.bankthreelog2Sve.create(bankthreelog2);
    }

    async bankthreeBatch(obj, req) {
        var list = obj || [];
        for (var item of list) {
            await this.bankthreeItem(item);
        }
    }

    async bankthree(obj, req) {
        try {
            var appId = obj.appId;
            var userName = obj.userName || "";
            var userIdNo = obj.userIdNo || "";
            var userBankNo = obj.userBankNo || "";
            var nonceStr = obj.nonceStr || "";

            var sign = obj.sign || "";
            var btl = await this.bankthreelogSve.create({
                appId: appId,
                userName: userName,
                userIdNo: userIdNo.toUpperCase(),
                userBankNo: userBankNo,
                nonceStr: nonceStr,
                sign: sign,
                use_esign: false,
                result: false,
            });

            var busi = await this.ecompanybusiSve.findOne({
                appId: appId
            });
            if (!busi) {
                return {
                    code: 1001003,
                    msg: "配置信息错误，请联系薪必果人员进行配置"
                };
            }

            var signArr = [];
            signArr.push("appId=" + appId);
            signArr.push("nonceStr=" + nonceStr);
            signArr.push("userBankNo=" + userBankNo);
            signArr.push("userIdNo=" + userIdNo);
            signArr.push("userName=" + userName);
            signArr.push("key=" + busi.key);
            var calcSign = md5(signArr.join("&")).toUpperCase();
            console.log(sign, calcSign);
            if (sign != calcSign) {
                return {
                    code: 1,
                    msg: "签名失败"
                };
            }

            // 验证电子签
            // var list = await this.econtractSve.findSinedByThree(userName, userIdNo, userBankNo);
            let exists = await this.bankthreelogSve.findOne({
                userName: userName,
                userIdNo: userIdNo.toUpperCase(),
                userBankNo: userBankNo,
                result: 1,
            });
            if (exists) {
                btl.result = true;
                btl.save();
                return {
                    code: 0,
                    msg: "success"
                };
            }

            var bankthreeParams = {
                name: userName, //姓名 必填
                idno: userIdNo.toUpperCase(), //身份证 必填
                cardno: userBankNo //银行卡 必填
            };

            var tt = await this.utilesignbaoSve.bankthree(bankthreeParams, "econtractapi.bankthree") || {};
            // {"code":-110,"message":"手机号格式错误","data":{}}
            //1成功,-110提示验证信息有误，-120亲，提供的信息不正确，请验证后再试！
            console.log("tt-----------------------------", tt);
            btl.use_esign = true;
            if (tt.code == 1) {
                btl.result = true;
                btl.save();
                return {
                    code: 0,
                    msg: "success"
                };
            } else if (tt.code == -110) {
                btl.result = false;
                btl.save();
                return {
                    code: 1002002,
                    msg: tt.message
                };
            } else {
                btl.result = false;
                btl.save();
                return {
                    code: 1002002,
                    msg: "银行三要素验证失败"
                };
            }
        } catch (error) {
            console.log(error);
            return {
                code: 500,
                msg: "接口异常"
            };
        }
    }

    async bankfour(obj, req) {
        try {
            var appId = obj.appId;
            var userName = obj.userName || "";
            var userIdNo = obj.userIdNo || "";
            var userBankNo = obj.userBankNo || "";
            var userMobile = obj.userMobile || "";
            var nonceStr = obj.nonceStr || "";

            let exists = await this.bankthreelogSve.findOne({
                userName: userName,
                userIdNo: userIdNo.toUpperCase(),
                userBankNo: userBankNo,
                userMobile: userMobile,
                result: 1,
            });
            var sign = obj.sign || "";
            var btl = await this.bankthreelogSve.create({
                appId: appId,
                userName: userName,
                userIdNo: userIdNo.toUpperCase(),
                userBankNo: userBankNo,
                userMobile: userMobile,
                nonceStr: nonceStr,
                sign: sign,
                use_esign: false,
                result: false,
            });

            var busi = await this.ecompanybusiSve.findOne({
                appId: appId
            });
            if (!busi) {
                return {
                    code: 1001003,
                    msg: "配置信息错误，请联系薪必果人员进行配置"
                };
            }

            var signArr = [];
            signArr.push("appId=" + appId);
            signArr.push("nonceStr=" + nonceStr);
            signArr.push("userBankNo=" + userBankNo);
            signArr.push("userIdNo=" + userIdNo);
            signArr.push("userMobile=" + userMobile);
            signArr.push("userName=" + userName);
            signArr.push("key=" + busi.key);
            var calcSign = md5(signArr.join("&")).toUpperCase();
            if (sign != calcSign) {
                return {
                    code: 1,
                    msg: "签名失败"
                };
            }

            var bankParams = {
                name: userName, //姓名 必填
                idno: userIdNo.toUpperCase(), //身份证 必填
                cardno: userBankNo, //银行卡 必填
                mobile: userMobile,
            };

            if (exists) {
                btl.result = true;
                btl.save();
                return {
                    code: 0,
                    msg: "success"
                };
            }

            var tt = await this.utilesignbaoSve.bankfour(bankParams, "econtractapi.bankthree") || {};
            // {"code":-110,"message":"手机号格式错误","data":{}}
            //1成功,-110提示验证信息有误，-120亲，提供的信息不正确，请验证后再试！
            console.log("tt-----------------------------", tt);
            btl.use_esign = true;
            if (tt.code == 1) {
                btl.result = true;
                btl.save();
                return {
                    code: 0,
                    msg: "success"
                };
            } else if (tt.code == -110) {
                btl.result = false;
                btl.save();
                return {
                    code: 1002002,
                    msg: tt.message
                };
            } else {
                btl.result = false;
                btl.save();
                return {
                    code: 1002002,
                    msg: tt.message || "银行四要素验证失败"
                };
            }
        } catch (error) {
            return {
                code: 500,
                msg: "接口异常"
            };
        }
    }

    async bankfourTest(obj, req) {
        try {
            var appId = obj.appId;
            var userName = obj.userName || "";
            var userIdNo = obj.userIdNo || "";
            var userBankNo = obj.userBankNo || "";
            var userMobile = obj.userMobile || "";
            var nonceStr = obj.nonceStr || "";

            var sign = obj.sign || "";
            var btl = await this.bankthreelogSve.create({
                appId: appId,
                userName: userName,
                userIdNo: userIdNo.toUpperCase(),
                userBankNo: userBankNo,
                userMobile: userMobile,
                nonceStr: nonceStr,
                sign: sign,
                use_esign: false,
                result: false,
            });

            var busi = await this.ecompanybusiSve.findOne({
                appId: appId
            });
            if (!busi) {
                return {
                    code: 1001003,
                    msg: "配置信息错误，请联系薪必果人员进行配置"
                };
            }

            var signArr = [];
            signArr.push("appId=" + appId);
            signArr.push("nonceStr=" + nonceStr);
            signArr.push("userBankNo=" + userBankNo);
            signArr.push("userIdNo=" + userIdNo);
            signArr.push("userMobile=" + userMobile);
            signArr.push("userName=" + userName);
            signArr.push("key=" + busi.key);
            var calcSign = md5(signArr.join("&")).toUpperCase();
            if (sign != calcSign) {
                return {
                    code: 1,
                    msg: "签名失败"
                };
            }

            var bankParams = {
                name: userName, //姓名 必填
                idno: userIdNo.toUpperCase(), //身份证 必填
                cardno: userBankNo, //银行卡 必填
                mobile: userMobile,
            };

            // var tt = await this.utilesignbaoSve.bankfour(bankParams, "econtractapi.bankthree") || {};
            var tt = {code: 1};
            return {
                code: 0,
                msg: "success"
            };
        } catch (error) {
            return {
                code: 500,
                msg: "接口异常"
            };
        }
    }

    async dosync(obj, req) {
        // TODO 需要验证一下合法
        this.econtractSve.syncAllSigners();
        return 1;
    }

    async dosync(obj, req) {
        // TODO 需要验证一下合法
        this.econtractSve.syncAllSigners();
        return 1;
    }

    async testinsure() {
        this.econtractSve.sendInsure(61094);
    }

    async ydsignnumber() {
        return this.econtractSve.ydsignnumber();
    }

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

    //三要素验证
    async autoSign(pobj) {
        // 处理参数
        var param = {
            ecid: this.trim(pobj.ecid),
            appId: this.trim(pobj.appId),
            userId: this.trim(pobj.userId),
            idName: this.trim(pobj.idName),
            mobile: this.trim(pobj.mobile),
            idNo: this.trim(pobj.idNo),
            bankno: this.trim(pobj.bankno),
            nonceStr: this.trim(pobj.nonceStr),
            userCode: this.trim(pobj.userCode),//用户code-韵达
            branchCode: this.trim(pobj.branchCode),//韵达分公司ID
            sign: this.trim(pobj.sign)
        };

        if (!param.ecid) {
            return this.returnjson(-1, "请传入薪必果提供的ecid")
        }
        if (!param.appId) {
            return this.returnjson(-1, "请传入薪必果提供的appId")
        }
        if (!param.userId) {
            return this.returnjson(-1, "请提供该用户的userId")
        }
        if (!param.idName) {
            return this.returnjson(-1, "请提供该用户姓名")
        }
        if (!param.idNo) {
            return this.returnjson(-1, "请提供该用户身份证号")
        }
        if (!await this.idcardClient.checkIDCard(param.idNo)) {
            return this.returnjson(-1, "身份证格式不正确");
        }

        let busiIds = await this.etemplatebusiSve.busiIdsByTemplateId(param.ecid);
        let num = await this.esettleSve.isValidAge(busiIds);
        if(num) {
            let card = await this.idcardClient.cardInfo(param.idNo);
            let age = card.age || 0;
            if(!age) {
                return this.returnjson(-1, "身份证号格式错误, 只支持18位身份证号码");
            }
            if(card.sex == 'male') {
                if (age < 18 || age > 60) {
                    return this.returnjson(-1, "签约失败，男限制18-60岁之间")
                }
            } else {
                if (age < 18 || age > 55) {
                    return this.returnjson(-1, "签约失败，女限制18-55岁之间")
                }
            }
        }

        if (!param.bankno) {
            return this.returnjson(-1, "请提供该用户银行卡号")
        }
        if (!param.nonceStr) {
            return this.returnjson(-1, "请提供随机码")
        }

        // 查appId关联key
        var busi = await this.ecompanybusiSve.findOne({
            appId: param.appId
        });
        if (!busi || !busi.key) {
            return this.returnjson(1001003, "配置信息错误，请联系薪必果人员进行配置");
        }

        // 签名
        var signArr = [];
        var keys = Object.keys(param).sort();
        for (var i = 0; i < keys.length; i++) {
            var k = keys[i];
            var v = param[k];
            if (!k || !v || k == 'sign') {
                continue;
            }
            signArr.push(k + "=" + v);
        }
        var signStr = signArr.join("&") + "&key=" + busi.key;
        var sign = md5(signStr).toUpperCase();
        console.log("---autoSign---签名---", signStr, sign);
        if (param.sign != sign) {
            return this.returnjson(1001001, "签名错误");
        }

        try {
            param.idNo = param.idNo.toUpperCase();
            param.bankno = param.bankno.replace(/\s*/g,"");
            var key = param.idNo +"_"+ param.ecid
            const id = uuidv1();
            await this.redisLock.lock(key, id, 20);
            var result = await this.econtractSve.autoSign(param);
            await this.redisLock.unLock(key, id);
            return result;
        } catch (error) {
            console.log(error);
        }
    }


    //四要素验证
    async autoSign4(pobj) {
        // 处理参数
        var param = {
            ecid: this.trim(pobj.ecid),
            appId: this.trim(pobj.appId),
            userId: this.trim(pobj.userId),
            idName: this.trim(pobj.idName),
            mobile: this.trim(pobj.mobile),
            idNo: this.trim(pobj.idNo),
            bankno: this.trim(pobj.bankno),
            nonceStr: this.trim(pobj.nonceStr),
            userCode: this.trim(pobj.userCode),//用户code-韵达
            branchCode: this.trim(pobj.branchCode),//韵达分公司ID
            sign: this.trim(pobj.sign)
        };

        if (!param.ecid) {
            return this.returnjson(-1, "请传入薪必果提供的ecid")
        }
        if (!param.appId) {
            return this.returnjson(-1, "请传入薪必果提供的appId")
        }
        if (!param.userId) {
            return this.returnjson(-1, "请提供该用户的userId")
        }
        if (!param.idName) {
            return this.returnjson(-1, "请提供该用户姓名")
        }
        if (!param.idNo) {
            return this.returnjson(-1, "请提供该用户身份证号")
        }
        if (!param.mobile) {
            return this.returnjson(-1, "请提供该用户手机号")
        }
        if (!await this.idcardClient.checkIDCard(param.idNo)) {
            return this.returnjson(-1, "身份证格式不正确");
        }

        let busiIds = await this.etemplatebusiSve.busiIdsByTemplateId(param.ecid);
        let num = await this.esettleSve.isValidAge(busiIds);
        if(num) {
            let card = await this.idcardClient.cardInfo(param.idNo);
            let age = card.age || 0;
            if(!age) {
                return this.returnjson(-1, "身份证号格式错误, 只支持18位身份证号码");
            }
            if(card.sex == 'male') {
                if (age < 18 || age > 60) {
                    return this.returnjson(-1, "签约失败，男限制18-60岁之间")
                }
            } else {
                if (age < 18 || age > 55) {
                    return this.returnjson(-1, "签约失败，女限制18-55岁之间")
                }
            }
        }

        if (!param.bankno) {
            return this.returnjson(-1, "请提供该用户银行卡号")
        }
        if (!param.nonceStr) {
            return this.returnjson(-1, "请提供随机码")
        }

        // 查appId关联key
        var busi = await this.ecompanybusiSve.findOne({
            appId: param.appId
        });
        if (!busi || !busi.key) {
            return this.returnjson(1001003, "配置信息错误，请联系薪必果人员进行配置");
        }

        // 签名
        var signArr = [];
        var keys = Object.keys(param).sort();
        for (var i = 0; i < keys.length; i++) {
            var k = keys[i];
            var v = param[k];
            if (!k || !v || k == 'sign') {
                continue;
            }
            signArr.push(k + "=" + v);
        }
        var signStr = signArr.join("&") + "&key=" + busi.key;
        var sign = md5(signStr).toUpperCase();
        console.log(signStr, sign);
        if (param.sign != sign) {
            return this.returnjson(1001001, "签名错误");
        }

        try {
            param.idNo = param.idNo.toUpperCase();
            param.bankno = param.bankno.replace(/\s*/g,"");
            var key = param.idNo +"_"+ param.ecid
            const id = uuidv1();
            await this.redisLock.lock(key, id, 20);
            var result = await this.econtractSve.autoSign4(param);
            this.redisLock.unLock(key, id);
            return result;
        } catch (error) {
            console.log(error);
        }
    }

    //不带三要素验证
    async autoSignNo3rd(pobj) {
        // 处理参数
        var param = {
            ecid: this.trim(pobj.ecid),
            appId: this.trim(pobj.appId),
            userId: this.trim(pobj.userId),
            idName: this.trim(pobj.idName),
            mobile: this.trim(pobj.mobile),
            idNo: this.trim(pobj.idNo),
            bankno: this.trim(pobj.bankno),
            nonceStr: this.trim(pobj.nonceStr),
            userCode: this.trim(pobj.userCode),//用户code-韵达
            branchCode: this.trim(pobj.branchCode),//韵达分公司ID
            sign: this.trim(pobj.sign)
        };

        if (!param.ecid) {
            return this.returnjson(-1, "请传入薪必果提供的ecid")
        }
        if (!param.appId) {
            return this.returnjson(-1, "请传入薪必果提供的appId")
        }
        if (!param.userId) {
            return this.returnjson(-1, "请提供该用户的userId")
        }
        if (!param.idName) {
            return this.returnjson(-1, "请提供该用户姓名")
        }
        if (!param.idNo) {
            return this.returnjson(-1, "请提供该用户身份证号")
        }
        if (!await this.idcardClient.checkIDCard(param.idNo)) {
            return this.returnjson(-1, "身份证格式不正确");
        }

        let busiIds = await this.etemplatebusiSve.busiIdsByTemplateId(param.ecid);
        let num = await this.esettleSve.isValidAge(busiIds);
        if(num) {
            let card = await this.idcardClient.cardInfo(param.idNo);
            let age = card.age || 0;
            if(!age) {
                return this.returnjson(-1, "身份证号格式错误, 只支持18位身份证号码");
            }
            if(card.sex == 'male') {
                if (age < 18 || age > 60) {
                    return this.returnjson(-1, "签约失败，男限制18-60岁之间")
                }
            } else {
                if (age < 18 || age > 55) {
                    return this.returnjson(-1, "签约失败，女限制18-55岁之间")
                }
            }
        }

        if (!param.bankno) {
            return this.returnjson(-1, "请提供该用户银行卡号")
        }
        if (!param.nonceStr) {
            return this.returnjson(-1, "请提供随机码")
        }

        // 查appId关联key
        var busi = await this.ecompanybusiSve.findOne({
            appId: param.appId
        });
        if (!busi || !busi.key) {
            return this.returnjson(1001003, "配置信息错误，请联系薪必果人员进行配置");
        }

        // 签名
        var signArr = [];
        var keys = Object.keys(param).sort();
        for (var i = 0; i < keys.length; i++) {
            var k = keys[i];
            var v = param[k];
            if (!k || !v || k == 'sign') {
                continue;
            }
            signArr.push(k + "=" + v);
        }
        var signStr = signArr.join("&") + "&key=" + busi.key;
        var sign = md5(signStr).toUpperCase();
        console.log(signStr, sign);
        if (param.sign != sign) {
            return this.returnjson(1001001, "签名错误");
        }

        try {
            param.idNo = param.idNo.toUpperCase();
            var key = param.idNo +"_"+ param.ecid
            const id = uuidv1();
            await this.redisLock.lock(key, id, 20);
            var result = await this.econtractSve.autoSigns(param);
            await this.redisLock.unLock(key, id);
            return result;
        } catch (error) {
            console.log(error);
        }
    }

    async autoSignTest(pobj) {
        // 处理参数
        var param = {
            ecid: this.trim(pobj.ecid),
            appId: this.trim(pobj.appId),
            userId: this.trim(pobj.userId),
            idName: this.trim(pobj.idName),
            mobile: this.trim(pobj.mobile),
            idNo: this.trim(pobj.idNo),
            bankno: this.trim(pobj.bankno),
            nonceStr: this.trim(pobj.nonceStr),
            sign: this.trim(pobj.sign)
        }

        if (!param.ecid) {
            return this.returnjson(-1, "请传入薪必果提供的ecid")
        }
        if (!param.appId) {
            return this.returnjson(-1, "请传入薪必果提供的appId")
        }
        if (!param.userId) {
            return this.returnjson(-1, "请提供该用户的userId")
        }
        if (!param.idName) {
            return this.returnjson(-1, "请提供该用户姓名")
        }
        if (!param.idNo) {
            return this.returnjson(-1, "请提供该用户身份证号")
        }
        if (!param.bankno) {
            return this.returnjson(-1, "请提供该用户银行卡号")
        }
        if (!param.nonceStr) {
            return this.returnjson(-1, "请提供随机码")
        }

        // 查appId关联key
        var busi = await this.ecompanybusiSve.findOne({
            appId: param.appId
        });
        if (!busi || !busi.key) {
            return this.returnjson(1001003, "配置信息错误，请联系薪必果人员进行配置");
        }

        // 签名
        var signArr = [];
        var keys = Object.keys(param).sort();
        for (var i = 0; i < keys.length; i++) {
            var k = keys[i];
            var v = param[k];
            if (!k || !v || k == 'sign') {
                continue;
            }
            signArr.push(k + "=" + v);
        }
        var signStr = signArr.join("&") + "&key=" + busi.key;
        var sign = md5(signStr).toUpperCase();
        if (param.sign != sign) {
            return this.returnjson(1001001, "签名错误");
        }

        try {
            param.idNo = param.idNo.toUpperCase();
            var result = await this.econtractSve.autoSignTest(param);
            return result;
        } catch (error) {
            console.log(error);
        }
    }

    //二要素验证（身份证、姓名）
    async autoSignPersonalTwo(pobj) {
        // 处理参数
        var param = {
            ecid: this.trim(pobj.ecid),
            appId: this.trim(pobj.appId),
            userId: this.trim(pobj.userId),
            idName: this.trim(pobj.idName),
            idNo: this.trim(pobj.idNo),
            nonceStr: this.trim(pobj.nonceStr),
            sign: this.trim(pobj.sign)
        };

        if (!param.ecid) {
            return this.returnjson(-1, "请传入薪必果提供的ecid")
        }
        if (!param.appId) {
            return this.returnjson(-1, "请传入薪必果提供的appId")
        }
        if (!param.userId) {
            return this.returnjson(-1, "请提供该用户的userId")
        }
        if (!param.idName) {
            return this.returnjson(-1, "请提供该用户姓名")
        }
        if (!param.idNo) {
            return this.returnjson(-1, "请提供该用户身份证号")
        }
        if (!await this.idcardClient.checkIDCard(param.idNo)) {
            return this.returnjson(-1, "身份证格式不正确");
        }

        let busiIds = await this.etemplatebusiSve.busiIdsByTemplateId(param.ecid);
        let num = await this.esettleSve.isValidAge(busiIds);
        if(num) {
            let card = await this.idcardClient.cardInfo(param.idNo);
            let age = card.age || 0;
            if(!age) {
                return this.returnjson(-1, "身份证号格式错误, 只支持18位身份证号码");
            }
            if(card.sex == 'male') {
                if (age < 18 || age > 60) {
                    return this.returnjson(-1, "签约失败，男限制18-60岁之间")
                }
            } else {
                if (age < 18 || age > 55) {
                    return this.returnjson(-1, "签约失败，女限制18-55岁之间")
                }
            }
        }

        if (!param.nonceStr) {
            return this.returnjson(-1, "请提供随机码")
        }

        // 查appId关联key
        var busi = await this.ecompanybusiSve.findOne({
            appId: param.appId
        });
        if (!busi || !busi.key) {
            return this.returnjson(1001003, "配置信息错误，请联系薪必果人员进行配置");
        }

        // 签名
        var signArr = [];
        var keys = Object.keys(param).sort();
        for (var i = 0; i < keys.length; i++) {
            var k = keys[i];
            var v = param[k];
            if (!k || !v || k == 'sign') {
                continue;
            }
            signArr.push(k + "=" + v);
        }
        var signStr = signArr.join("&") + "&key=" + busi.key;
        var sign = md5(signStr).toUpperCase();
        console.log(signStr, sign);
        if (param.sign != sign) {
            return this.returnjson(1001001, "签名错误");
        }

        try {
            param.idNo = param.idNo.toUpperCase();
            var key = param.idNo +"_"+ param.ecid
            const id = uuidv1();
            await this.redisLock.lock(key, id, 20);
            var result = await this.econtractSve.autoSignPersonalTwo(param);
            await this.redisLock.unLock(key, id);
            return result;
        } catch (error) {
            console.log(error);
        }
    }

    //二要素验证（姓名、银行卡）
    async autoSignBankTwo(pobj) {
        // 处理参数
        var param = {
            ecid: this.trim(pobj.ecid),
            appId: this.trim(pobj.appId),
            userId: this.trim(pobj.userId),
            idName: this.trim(pobj.idName),
            idNo: this.trim(pobj.idNo),
            nonceStr: this.trim(pobj.nonceStr),
            sign: this.trim(pobj.sign)
        };

        if (!param.ecid) {
            return this.returnjson(-1, "请传入薪必果提供的ecid")
        }
        if (!param.appId) {
            return this.returnjson(-1, "请传入薪必果提供的appId")
        }
        if (!param.userId) {
            return this.returnjson(-1, "请提供该用户的userId")
        }
        if (!param.idName) {
            return this.returnjson(-1, "请提供该用户姓名")
        }
        if (!param.idNo) {
            return this.returnjson(-1, "请提供该用户身份证号")
        }
        if (!await this.idcardClient.checkIDCard(param.idNo)) {
            return this.returnjson(-1, "身份证格式不正确");
        }

        let busiIds = await this.etemplatebusiSve.busiIdsByTemplateId(param.ecid);
        let num = await this.esettleSve.isValidAge(busiIds);
        if(num) {
            let card = await this.idcardClient.cardInfo(param.idNo);
            let age = card.age || 0;
            if(!age) {
                return this.returnjson(-1, "身份证号格式错误, 只支持18位身份证号码");
            }
            if(card.sex == 'male') {
                if (age < 18 || age > 60) {
                    return this.returnjson(-1, "签约失败，男限制18-60岁之间")
                }
            } else {
                if (age < 18 || age > 55) {
                    return this.returnjson(-1, "签约失败，女限制18-55岁之间")
                }
            }
        }

        if (!param.nonceStr) {
            return this.returnjson(-1, "请提供随机码")
        }

        // 查appId关联key
        var busi = await this.ecompanybusiSve.findOne({
            appId: param.appId
        });
        if (!busi || !busi.key) {
            return this.returnjson(1001003, "配置信息错误，请联系薪必果人员进行配置");
        }

        // 签名
        var signArr = [];
        var keys = Object.keys(param).sort();
        for (var i = 0; i < keys.length; i++) {
            var k = keys[i];
            var v = param[k];
            if (!k || !v || k == 'sign') {
                continue;
            }
            signArr.push(k + "=" + v);
        }
        var signStr = signArr.join("&") + "&key=" + busi.key;
        var sign = md5(signStr).toUpperCase();
        console.log(signStr, sign);
        if (param.sign != sign) {
            return this.returnjson(1001001, "签名错误");
        }

        try {
            param.idNo = param.idNo.toUpperCase();
            var key = param.idNo +"_"+ param.ecid
            const id = uuidv1();
            await this.redisLock.lock(key, id, 20);
            var result = await this.econtractSve.autoSignBankTwo(param);
            await this.redisLock.unLock(key, id);
            return result;
        } catch (error) {
            console.log(error);
        }
    }


    async formateTime(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 formateSimpTime() {
        var date = new Date();
        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();
        minute = minute < 10 ? ('0' + minute) : minute;

        return y + '年' + m + '月' + d + '日' + ' ' + h + ':' + minute;
    };

    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('');
    }

    trim(o) {
        if (!o) {
            return "";
        }
        return o.toString().trim();
    }

    async validateUser(obj, req) {
        // 验证合法性
        var idName = this.trim(obj.idName);
        var idNo = this.trim(obj.idNo.toUpperCase());
        var accNo = this.trim(obj.accNo);
        var nonceStr = obj.nonceStr;
        var sign = obj.sign;
        if (!idName) {
            return {
                code: 1002001,
                msg: "参数错误, 姓名不存在"
            };
        }
        if (!idNo) {
            return {
                code: 1002001,
                msg: "参数错误, 身份证不存在"
            };
        }
        if (!accNo) {
            return {
                code: 1002001,
                msg: "参数错误, 银行卡号不存在"
            };
        }

        var sign = md5("accNo=" + accNo + "&idName=" + idName + "&idNo=" + idNo + "&nonceStr=" + obj.nonceStr + "&key=wxf616c0a459d66081").toUpperCase();
        if (sign != obj.sign) {
            return {
                code: 1001001,
                msg: "签名失败"
            };
        }

        try {
            var list = await this.econtractSve.findSinedByThree(idName, idNo, accNo);
            if (list.length > 0) {
                return {
                    code: 0,
                    msg: "success"
                };
            }
            var nonceStr = obj.nonceStr;

            var bankthreeParams = {
                name: idName, //姓名 必填
                idno: idNo, //身份证 必填
                cardno: accNo //银行卡 必填
            };

            var tt = await this.utilesignbaoSve.bankthree(bankthreeParams, "bankinfoAuth") || {};
            // {"code":-110,"message":"手机号格式错误","data":{}}
            //1成功,-110提示验证信息有误，-120亲，提供的信息不正确，请验证后再试！
            console.log("tt-----------------------------", tt);

            if (tt.code == 1) {
                return {
                    code: 0,
                    msg: "success"
                };
            } else if (tt.code == -110) {
                return {
                    code: 1002002,
                    msg: tt.message
                };
            } else {
                return {
                    code: 1002002,
                    msg: "银行三要素验证失败"
                };
            }
        } catch (e) {
            var result = {
                code: 500,
                msg: "接口异常"
            };
            console.log(e.stack);
            //日志记录
            logCtl.error({
                optitle: "校验是否签约error",
                op: "api/econtractApi/validContract",
                content: e.stack,
                clientIp: req.clientIp
            });
            return result;
        }
    }

    //发薪完，通知消息
    async notifyMssage(obj, req) {
        var resultNotify = {
            code: 1,
            message: "success"
        };

        try {
            this.econtractSve.testtransfer(JSON.stringify(obj));
        } catch (error) {
        }

        var regexNumber = /^[0-9]*$/;
        var wechatNoticeList = [] //微信通知列表
        var notifyTime = await this.formateSimpTime();
        var errorItems = [];

        //循环参数
        for (var item in obj.sendList) {
            var rowItem = Number(item) + 1;
            var orderItemId = obj.sendList[item]['orderItemId'] || "";

            var orderItem = await this.esettleSve.findOrderItemById(orderItemId);
            if (!orderItem) {
                errorItems.push("orderItem" + orderItem + "不存在");
                continue;
            }
            if (orderItem.busi_id = '1152195411663171585') {
                continue;
            }
            var idNo = orderItem.id_no || "";
            var amt = orderItem.amt || 0;
            var mobile = orderItem.mobile || "";
            notifyTime = moment(orderItem.pay_complete_time).add(-8, "hours").format("YYYY年MM月DD日 HH:mm");
            var notifyTimeStr = moment(orderItem.pay_complete_time).add(-8, "hours").format("YYYY-MM-DD HH:mm:ss");

            //添加支付记录
            var incomeTax = parseFloat((Number(orderItem.income_tax) / 100).toFixed(2));

            var notifyUrl = "https://bpohhr.gongsibao.com/paynotify?id=" + orderItemId;

            var notifyObj = {
                fromid: mobile,
                username: orderItem.id_name || "",
                flag: 0,
                amount: amt,
                status: 0,
                notifyTime: notifyTimeStr,
                orderItemId: orderItemId,
                income_tax: orderItem.income_tax
            }

            //为空验证
            if (!idNo) {
                errorItems.push("第" + rowItem + "项-参数错误, 身份证为空");
                continue;
            }
            if (!amt) {
                errorItems.push("第" + rowItem + "项-参数错误, 实发金额为空");
                continue;
            }

            amt = parseFloat((Number(amt) / 100).toFixed(2));
            var message = notifyTime + " 您收到报酬费" + amt + "元, 查看详细内容" + notifyUrl;

            try {
                var list = await this.econtractSve.findOpenIdByNo("2", idNo);
                if (list.length > 0) {
                    var sendItem;
                    var sendMobile;
                    for (var item of list) {
                        if (item.openId.indexOf('oEl') === 0) {
                            sendItem = item;
                            break;
                        }
                        if (item.mobile) {
                            sendMobile = item.mobile;

                            // 手机号通知
                            notifyObj.username = item.userName;
                            notifyObj.fromid = mobile || sendMobile;
                        }
                    }
                    if (sendItem) {
                        // 微信消息模板通知
                        var wechatParam = {
                            url: notifyUrl,
                            first: "您有一个报酬发放通知！",
                            keyword1: sendItem.userName,
                            keyword2: "已发放",
                            keyword3: amt + "元",
                            keyword4: notifyTime + ' 您的报酬已到帐，请查收！',
                            openid: sendItem.openId
                        }
                        wechatNoticeList.push(wechatParam);

                        // 通知参数
                        notifyObj.username = item.userName;
                        notifyObj.fromid = sendItem.openId;
                        notifyObj.flag = 1;
                        await this.econtractSve.addPayNotify(notifyObj);
                    } else if (mobile || sendMobile) {
                        // 手机号码通知
                        // await this.smsS.sendMsg(mobile || sendMobile, message);
                        await this.econtractSve.addPayNotify(notifyObj);
                    }
                } else {
                    if (mobile) {
                        // await this.smsS.sendMsg(mobile, message);
                        await this.econtractSve.addPayNotify(notifyObj);
                    } else {
                        errorItems.push("第" + rowItem + "项-根据身份证获取数据为空");
                    }
                    continue;
                }
            } catch (e) {
                resultNotify.code = 500;
                resultNotify.message = "接口异常";

                //日志记录
                logCtl.error({
                    optitle: "发薪通知error",
                    op: "api/econtractApi/notifyMssage",
                    content: e.stack,
                    clientIp: req.clientIp
                });
            }
        }
        if (wechatNoticeList.length > 0) {
            await this.wxPushMssage(wechatNoticeList);
        }
        if (errorItems.length > 0) {
            var errors = "";
            for (var item of errorItems) {
                errors += item + "、";
            }
            return system.getErrResult2(errors.substr(0, errors.length - 1));
        }

        return resultNotify;
    }

    //微信通知消息
    async wxPushMssage(wechatNoticeList) {
        try {
            //微信处理
            var data = null;
            //添加支付记录
            var wxParam = null;

            for (var i = 0; i < wechatNoticeList.length; i++) {
                var wechatItem = wechatNoticeList[i];
                //发送通知
                data = {
                    first: wechatItem.first,
                    keyword1: {
                        value: wechatItem.keyword1
                    },
                    keyword2: {
                        value: wechatItem.keyword2
                    },
                    keyword3: {
                        value: wechatItem.keyword3
                    },
                    keyword4: {
                        value: wechatItem.keyword4
                    }
                };

                this.wxSve.sendTmplMsg(wechatItem.openid, "khPLingFFTVQM2t7SVm1q1o9MvS2WgqUvIjCPkLcqAY", wechatItem.url || "", data, "wxf616c0a459d66081");
            }
        } catch (e) {
            var result = {
                code: 500,
                msg: "接口异常"
            };
            console.log(e.stack);
            //日志记录
            logCtl.error({
                optitle: "微信发薪通知error",
                op: "api/econtractApi/wxPushMssage",
                content: e.stack,
                clientIp: req.clientIp
            });
        }
        return result;
    }


    async checkSign(obj, req) {
        // 验证合法性
        var mtchId = obj.mtchId;
        var userList = obj.userList;
        try {
            if (!mtchId) {
                return {
                    code: 1,
                    msg: "请传入商户id信息"
                };
            }

            if (!userList || userList.length == 0) {
                return {
                    code: 1,
                    msg: "请传入用户身份信息"
                };
            }

            // 1 处理用户姓名和身份证参数
            var idNoList = [];
            var idNameList = [];
            for (var u of userList) {
                u.idNo = u.idNo.toUpperCase();
                idNoList.push(u.idNo);
                idNameList.push(u.idName);
            }

            // 3 查签约模板(c_etemplate_busi)
            var templateIds = await this.etemplateSve.findIdsByCompanyIdAndMainId(mtchId);

            var signList = [];
            var unSignList = [];
            var accountMap = {};
            var accountMap2 = {};
            var accountMap3 = {};
            // 4 查签约用户
            if (templateIds.idsO.length > 0) {
                var idsOCOunt = await this.usereaccountSve.getSignAccounts(templateIds.idsO, idNoList, idNameList);
                for (var idO of idsOCOunt) {
                    accountMap[idO.userName + "_" + idO.personsSign] = 1;
                }
            }
            if (templateIds.idsT.length > 0) {
                var idsTCount = await this.usereaccountSve.getSignAccounts_dk(templateIds.idsT, idNoList, idNameList);
                for (var idT of idsTCount) {
                    accountMap2[idT.userName + "_" + idT.personsSign] = 1;
                }
            }

            //线下
            var coids = await this.econtractofflineSve.findSignAccount(mtchId,idNoList,idNameList)
            for (var coid of coids){
                accountMap3[coid.id_name + "_" +coid.id_no] = 1;
            }

            // 5 比对用户是否签约
            for (var u of userList) {
                if (accountMap[u.idName + "_" + u.idNo] || accountMap2[u.idName + "_" + u.idNo] || accountMap3[u.idName + "_" + u.idNo]) {
                    signList.push(u);
                } else {
                    unSignList.push(u);
                }
            }

            // var hash = {};
            // signList = signList.reduce(function(item, next) {
            //     hash[next.idNo] ? '' : hash[next.idNo] = true && item.push(next);
            //     return item
            // }, []);
            //
            // unSignList = unSignList.reduce(function(item, next) {
            //     hash[next.idNo] ? '' : hash[next.idNo] = true && item.push(next);
            //     return item
            // }, []);
            return {
                code: 0,
                msg: "",
                data: {
                    signList: signList,
                    unSignList: unSignList
                }
            };
        } catch (error) {
            var result = {
                code: 1,
                msg: "接口异常"
            };
            console.log(error);
            //日志记录
            logCtl.error({
                optitle: "校验签约error",
                op: "api/econtractApi/checkSign",
                content: e.stack,
                clientIp: req.clientIp
            });
            return result;
        }
    }



}

module.exports = EcontractApi;
