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

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

    //签约完成参数:
    //专票（三要素）
    //普票（二要素）
    async signParams(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),
            fileurl: this.trim(pobj.fileurl)
        };


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

        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, "身份证格式不正确");
        }
        if (!param.nonceStr) {
            return this.returnjson(-1, "请提供随机码")
        }
        if (!param.fileurl) {
            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.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.signParams(param);
            await this.redisLock.unLock(key, id);
            return result;
        } catch (error) {
            console.log(error);
        }

    }

    async signingQuerytoPer(obj, req) {
        let appId = obj.appId;
        let ecid = obj.ecid;
        let nonceStr = obj.nonceStr;
        let userName = obj.userName;
        let idNo = obj.idNo;

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

        let signArr = [];
        signArr.push("appId=" + appId);
        signArr.push("ecid=" + ecid);
        signArr.push("idNo=" + idNo);
        signArr.push("nonceStr=" + nonceStr);
        if(userName){
            signArr.push("userName=" + userName);
        }
        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: "签名失败"};
        }

        try {
            let user = await this.dkcontractSve.signingQuerytoPer({ecid:ecid,userName:userName,idNo : idNo});
            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 = SignContractApi;


