var settings = require("../../config/settings");
const axios = require('axios');
const moment = require("moment");
const md5 = require("MD5");
const crypto = require('crypto');
const Qs = require('qs');

class UtilESignBaoService {
    constructor() {
        this.lbwConfig = settings.apiconfig.lbwConfig();
        this.merchantId = "131032002020009";//商户ID
    }

    async bankthree(params, opName) { //三要素验证
        console.log(opName, "兰铂旺三要素验证");
        var result = {
            code: 1,
            message: "success",
            data: {}
        };
        var merchantTraceNo = await this.getRandomCode(32);
        var merchantRequestTime = moment().format("YYYY-MM-DD HH:mm:ss");
        var bizType = "010102"; //业务类型，010112（精准）010102（非精准）

        var encrypt = {
            "idType": "01",
            "pan": params.bank_no,//卡号,
            "idNum": params.id_no,//证件号,
            "chName": params.id_name,//姓名
        };
        var encryptStr = JSON.stringify(encrypt);
        var str = crypto.privateEncrypt(this.lbwConfig.pik, Buffer.from(encryptStr)).toString('base64');
        var paramMap = {};
        paramMap.merchantId = this.merchantId;
        paramMap.bizType = bizType;
        paramMap.merchantTraceNo = merchantTraceNo;
        paramMap.merchantRequestTime = merchantRequestTime;
        paramMap.encrypt = str;

        var signStr = await this.sortParam(paramMap);
        var sign = md5(signStr);

        var list = {
            "merchantId": this.merchantId,
            "bizType": bizType,
            "merchantTraceNo": merchantTraceNo,
            "merchantRequestTime": merchantRequestTime,
            "encrypt": str,
            "sign": sign
        }
        console.log("请求参数=", list);
        let rs = await axios({
            url: this.lbwConfig.validate_bank,
            method: 'post',
            data: list,
            transformRequest: [function (data) {
                data = Qs.stringify(data);
                return data;
            }],
            headers: {"Content-Type": "application/x-www-form-urlencoded"},
        });
        console.log("返回状态===", rs.status);
        console.log("返回参数===", rs.data);
        if (rs.status === 200 && rs.data) {
            if (rs.data.respCode != '00000000') { //验证通过
                result.code = -120;
            }
            return result;
        }
        result.code = -110;
        return result;

    }

    async bankfour(params, opName) { //四要素验证

        console.log(opName, "兰铂旺四要素验证");
        var result = {
            code: 1,
            message: "success",
            data: {}
        };
        var merchantTraceNo = await this.getRandomCode(32);
        var merchantRequestTime = moment().format("YYYY-MM-DD HH:mm:ss");
        var bizType = "010103"; //业务类型，010113（精准）010103（非精准）
        var encrypt = {
            "idType": "01",
            "pan": params.bank_no,//卡号,
            "idNum": params.id_no,//证件号,
            "chName": params.id_name,//姓名
            "chTel": params.mobile,//手机号
        };
        var encryptStr = JSON.stringify(encrypt);
        var str = crypto.privateEncrypt(this.lbwConfig.pik, Buffer.from(encryptStr)).toString('base64');
        var paramMap = {};
        paramMap.merchantId = this.merchantId;
        paramMap.bizType = bizType;
        paramMap.merchantTraceNo = merchantTraceNo;
        paramMap.merchantRequestTime = merchantRequestTime;
        paramMap.encrypt = str;

        var signStr = await this.sortParam(paramMap);
        var sign = md5(signStr);

        var list = {
            "merchantId": this.merchantId,
            "bizType": bizType,
            "merchantTraceNo": merchantTraceNo,
            "merchantRequestTime": merchantRequestTime,
            "encrypt": str,
            "sign": sign
        }
        console.log("请求参数=", list);
        let rs = await axios({
            url: this.lbwConfig.validate_bank,
            method: 'post',
            data: list,
            transformRequest: [function (data) {
                data = Qs.stringify(data);
                return data;
            }],
            headers: {"Content-Type": "application/x-www-form-urlencoded"},
        });
        console.log("返回状态===", rs.status);
        console.log("返回参数===", rs.data);

        if (rs.status === 200 && rs.data) {
            if (rs.data.respCode != '00000000') { //验证通过
                result.code = -120;
            }
            return result;
        }
        result.code = -110;
        return result;
    }

    async sortParam(paramMap) {
        var signArr = [];
        var keys = Object.keys(paramMap).sort();
        for (var i = 0; i < keys.length; i++) {
            var k = keys[i];
            var v = paramMap[k];
            if (!k || !v || k == 'sign') {
                continue;
            }
            signArr.push(k + "=" + v);
        }
        var signStr = signArr.join(",");
        return signStr;
    }

    async getRandomCode(iun) {
        var randStr = "";
        for (var i = 0; i < iun; i++) {//此处的12为生成12位数字，可随即更改
            var randItem = Math.floor(Math.random() * 10);
            randStr += randItem;
        }
        return randStr;
    }
}

module.exports = UtilESignBaoService;
