var system = require("../../system")
const md5 = require("MD5");
const logCtl = system.getObject("web.oplogCtl");
const moment = require("moment");
const uuidv1 = require('uuid/v1');

class DKcontractApi {
    constructor() {
        this.idcardClient = system.getObject("util.idcardClient");
        this.esettleSve = system.getObject("service.esettleSve");
        this.dkcontractSve = system.getObject("service.dkcontractSve");
        this.etemplatebusiSve = system.getObject("service.etemplatebusiSve");
        this.redisLock = system.getObject("util.redisLock");
    }

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


    async autoSign(pobj) {
        // 处理参数
        var param = {
            ecid: this.trim(pobj.ecid),
            appId: this.trim(pobj.appId),
            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),
            userId : this.trim(pobj.userId),
            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, "请提供该用户ID")
        }
        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 busi = await this.etemplatebusiSve.busiByTemplate2(pobj.appId, param.ecid, 2);

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

        let num = await this.esettleSve.isValidAge(busi[0].busi_id);
        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, "请提供随机码")
        }
        // 签名
        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[0].key;
        var sign = md5(signStr).toUpperCase();
        console.log('dkcontractApi---autoSign--签名', param.sign, 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.dkcontractSve.autoSign(param);
            await this.redisLock.unLock(key, id);
            return result;
        } catch (error) {
            console.log(error);
        }
    }

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

        let busi = await this.etemplatebusiSve.busiByTemplate2(appId, ecid, 2);
        if (!busi[0] || !busi[0].app_id || !busi[0].key) {
            return this.returnjson(1001003, "配置信息错误，请联系薪必果人员进行配置");
        }

        let signArr = [];
        signArr.push("appId=" + appId);
        signArr.push("ecid=" + ecid);
        signArr.push("idNo=" + idNo);
        signArr.push("nonceStr=" + nonceStr);
        signArr.push("key=" + busi[0].key);
        let signStr = signArr.join("&")
        let sign = md5(signStr).toUpperCase();
        console.log('dkcontractApi---autoSign--签名', obj.sign, signStr, sign);

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

        try {
            let user = await this.dkcontractSve.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;
        }
    }

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

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


}

module.exports = DKcontractApi;
