const system = require("../../system");
const md5 = require("MD5");
const uuidv1 = require('uuid/v1');

class YZContractApi {
    constructor() {
        this.entcontractSve = system.getObject("service.entcontractSve");
        this.idcardClient = system.getObject("util.idcardClient");
        this.utilesignbaoSve = system.getObject("service.utilesignbaoSve");
        this.ecompanybusiSve = system.getObject("service.ecompanybusiSve");
        this.enttemplateSve = system.getObject("service.enttemplateSve");
        this.econtractSve = system.getObject("service.econtractSve");

        this.esettleSve = system.getObject("service.esettleSve");
        this.etemplatebusiSve = system.getObject("service.etemplatebusiSve");
        this.redisLock = system.getObject("util.redisLock");
        // this.appId = "1201869719607517185";
        // this.key = "bee7870e008ab144bf518b70ef91f8ac";
    }

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

    // async merchantSign(pobj) {
    //     // 处理参数
    //     var param = {
    //         ecid: this.trim(pobj.ecid),
    //         appId: this.trim(pobj.appId),
    //         merchantId: this.trim(pobj.merchantId),
    //
    //         merchantName: this.trim(pobj.merchantName), //甲方 必填
    //         merchantAddr: this.trim(pobj.merchantAddr), //甲方地址
    //         merchantLegal: this.trim(pobj.merchantLegal),//甲方法定代表人
    //
    //         idName: this.trim(pobj.idName),// 代理人姓名
    //         mobile: this.trim(pobj.mobile),// 代理人手机号
    //         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.idName) {
    //         return this.returnjson(-1, "请提供代理人姓名")
    //     }
    //     if (!param.idNo) {
    //         return this.returnjson(-1, "请提供代理人身份证号")
    //     }
    //     if (!await this.idcardClient.checkIDCard(param.idNo)) {
    //         return this.returnjson(-1, "代理人身份证格式不正确");
    //     }
    //     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, "请提供随机码")
    //     }
    //
    //     var enttemplate = await this.enttemplateSve.findById(param.ecid);
    //
    //     if (!enttemplate || !enttemplate.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=" + enttemplate.key;
    //     var sign = md5(signStr).toUpperCase();
    //     console.log(sign)
    //     if (param.sign != sign) {
    //         return this.returnjson(1001001, "签名错误");
    //     }
    //     try {
    //         var result = await this.entcontractSve.yzMerchantAutoSign(param);
    //         return result;
    //     } catch (error) {
    //         console.log(error);
    //     }
    // }


    async merchantSign(pobj) {
        // 处理参数
        var param = {
            ecid: this.trim(pobj.ecid),
            appId: this.trim(pobj.appId),
            merchantId: this.trim(pobj.merchantId),
            merchantName: this.trim(pobj.merchantName), //甲方 必填
            merchantAddr: this.trim(pobj.merchantAddr), //甲方地址
            merchantLegal: this.trim(pobj.merchantLegal),//甲方法定代表人
            idName: this.trim(pobj.idName),// 代理人姓名
            mobile: this.trim(pobj.mobile),// 代理人手机号
            idNo: this.trim(pobj.idNo),// 代理人身份证
            nonceStr: this.trim(pobj.nonceStr),//随机码
            idType : this.trim(pobj.idType),
            sign: this.trim(pobj.sign)
        };
        console.log("有赞商户签约接口===========", param);
        if (!param.ecid) {
            return this.returnjson(-1, "请传入薪必果提供的ecid");
        }
        if (!param.appId) {
            return this.returnjson(-1, "请传入薪必果提供的appId");
        }
        if (!param.idName) {
            return this.returnjson(-1, "请提供代理人姓名");
        }
        if (!param.idNo) {
            return this.returnjson(-1, "请提供代理人身份证号");
        }
        var cludes = ["13","17","18","19"];
        if(!cludes.includes(param.idType)){
            return this.returnjson(-1, "个人证件类型错误");
        }

        if(param.idType == 19){
            if (!await this.idcardClient.checkIDCard(param.idNo)) {
                return this.returnjson(-1, "代理人身份证格式不正确");
            }
            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.idType == 13){
            if (!await this.idcardClient.isPassPortCard(param.idNo)) {
                return this.returnjson(-1, "护照号码不合规");
            }
        }
        if(param.idType == 17){
            if (!await this.idcardClient.isHKCard(param.idNo)) {
                return this.returnjson(-1, "港澳居民来往内地通行证号码不合规");
            }
        }

        if(param.idType == 18){
            if (!await this.idcardClient.isTWCard(param.idNo)) {
                return this.returnjson(-1, "台湾居民来往大陆通行证号码不合规");
            }
        }

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

        var enttemplate = await this.enttemplateSve.findById(param.ecid);

        if (!enttemplate || !enttemplate.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=" + enttemplate.key;
        var sign = md5(signStr).toUpperCase();
        console.log(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.entcontractSve.yzMerchantAutoSigns(param,enttemplate);
            await this.redisLock.unLock(key, id);
            return result;
        } catch (error) {
            console.log(error);
        }
    }

    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),
            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, "请提供该用户身份证号")
        }

        let card = await this.idcardClient.cardInfo(param.idNo);
        let age = card.age || 0;
        if (!age) {
            return this.returnjson(-1, "身份证号格式错误, 只支持18位身份证号码");
        }

        // 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.autoSignNoBank(param);
            await this.redisLock.unLock(key, id);
            return result;
        } catch (error) {
            console.log(error);
        }
    }


    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 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,
        };

        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 sinedMerchant3rd(obj, req) {
        // 验证合法性
        var nonceStr = obj.nonceStr;
        var idNo = obj.idNo || "";
        var startId = obj.startId || 0;
        var merchantId = obj.merchantId || "";
        var pageSize = 20;

        if (!obj.appId) {
            return this.returnjson(-1, "请传入appId")
        }
        var enttemplate = await this.enttemplateSve.findOne({appid: obj.appId});

        if (!enttemplate || !enttemplate.key) {
            return this.returnjson(1001003, "配置信息错误，请联系薪必果人员进行配置");
        }

        var signArr = [];
        signArr.push("appId=" + enttemplate.appid);
        signArr.push("idNo=" + idNo);
        signArr.push("merchantId=" + merchantId);
        signArr.push("nonceStr=" + nonceStr);
        signArr.push("startId=" + startId);
        signArr.push("key=" + enttemplate.key);
        var sign = md5(signArr.join("&")).toUpperCase();
        console.log(signArr.join("&"), sign);
        if (sign != obj.sign) {
            return {
                code: 1001001,
                msg: "签名失败"
            };
        }
        var params = {
            startId: startId,
            idNo: idNo.toUpperCase(),
            pageSize: pageSize,
            userId3rd: merchantId,
        };

        try {
            var userList = await this.econtractSve.findSignedMerchant4Push(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;
        }
    }

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

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


}

module.exports = YZContractApi;
