const system = require("../../system");
const md5 = require("MD5");
class EntcontractApi {
    constructor() {
        this.entcontractSve = system.getObject("service.entcontractSve");
        this.ecompanybusiSve = system.getObject("service.ecompanybusiSve");
    }

    async autoSign(pobj) {
        // 处理参数
        var param = {
            name: this.trim(pobj.name), //甲方 必填
            addr: this.trim(pobj.addr), //甲方地址
            legal: this.trim(pobj.legal),//甲方法定代表人
            contactName: this.trim(pobj.contactName),//甲方联系人
            contactMobile: this.trim(pobj.contactMobile),//甲方 联系电话
            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),//随机码
            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 (!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(sign)
        if (param.sign != sign) {
            return this.returnjson(1001001, "签名错误");
        }

        try {
            var result = await this.entcontractSve.autoSign(param);
            return result;
        } catch (error) {
            console.log(error);
        }
    }


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


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


}

module.exports = EntcontractApi;