var System = require("../../system");
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 UitlLBWService {
    constructor() {
        this.lbwConfig = settings.apiconfig.lbwConfig();
        this.restClient = System.getObject("util.restClient");
        this.merchantId = "131032002020009";//商户ID
        this.idauthlogDao  = System.getObject("db.idauthlogDao")
    }

    async bankTwo(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 = "010101";

        var encrypt = {
            "pan": params.cardno,//卡号,
            "chName": params.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;
        this.idauthlogDao.create({
            userName: params.name,
            userBankNo: params.cardno,
            result: result.code
        });
        return result;
    }

    async bankTwoToidCard(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 = "010301";
        var encrypt = {
            "chName": params.name,//姓名
            "idType":"01",
            "idNum": params.idNum,//身份证号,
            "mchInfo":"汉唐信通（北京）科技有限公司",
            "riskInfo": params.cardno,
        };
        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_idcard,
            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;
        this.idauthlogDao.create({
            userName: params.name,
            userBankNo: params.cardno,
            result: result.code
        });
        return result;
    }


    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.cardno,//卡号,
            "idNum": params.idno,//证件号,
            "chName": params.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;
        this.idauthlogDao.create({
            userName: params.idName,
            userIdNo: params.idNo,
            userBankNo: params.bankno,
            result: result.code
        });
        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.cardno,//卡号,
            "idNum": params.idno,//证件号,
            "chName": params.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;
        this.idauthlogDao.create({
            userName: params.idName,
            userIdNo: params.idNo,
            userBankNo: params.bankno,
            userMobile: params.mobile,
            result: result.code
        });
        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 = UitlLBWService;
