var APIBase = require("../../api.base");
var system = require("../../../system");
const axios = require("axios");
const validation = system.getObject("util.validation");
const md5 = require("MD5");

class TestAPI extends APIBase {
    constructor() {
        super();
        this.SMS_BANKMOBILE_KEY = "gtb_appl_mobile_";
        this.SMS_LOGINMOBILE_KEY = "gtb_login_mobile_";
        this.BANK_FOUR = "https://bpohhr.gongsibao.com/api/econtractApi/bankfour";
        this.GTB_APPID = "gtb-mcht-applet";
        this.GTB_KEY = "0e2e4e7249b79q50f234071651971242";

        this.uploadCtl = system.getObject("web.common.uploadCtl");
        this.idcardClient = system.getObject("util.idcardClient");
        this.merchantappletuserSve = system.getObject("service.uc.merchantappletuserSve");
        this.orderSve = system.getObject("service.saas.orderSve");
        this.businessmenSve = system.getObject("service.saas.businessmenSve");
        this.tradeSve = system.getObject("service.trade.tradeSve");
        this.saasInvoiceSve = system.getObject("service.saas.invoiceSve");
        this.merchantSve = system.getObject("service.saas.merchantSve");
        this.redisClient = system.getObject("util.redisClient");

        this.smsClient = system.getObject("util.smsClient");
    }

    doMerchantId(obj) {
        if (!obj.merchant_id) {
            return;
        }
        try {
            obj.merchant_id = system.decryption(decodeURIComponent(obj.merchant_id));
        } catch (e) {
            console.log(e);
            return;
        }
    }

    //H5登录获取验证码
    async sendMobileCode(obj, obj1, req) {
        this.doMerchantId(obj);
        let mobile = obj.mobile;
        if (!mobile) {
            return this.returnFail("请先填写手机号");
        }
        if (validation.isMobile(mobile)) {
            return this.returnFail("手机号格式错误");
        }
        try {
            let key = this.SMS_LOGINMOBILE_KEY + mobile;
            let vcode = await this.redisClient.get(key + "t");
            // let vcode;
            if (!vcode) {
                vcode = await this.getVCode();
                await this.redisClient.setWithEx(key, vcode, 5 * 60);
                await this.redisClient.setWithEx(key + "t", vcode, 60);
                let msg = "您的个体户注册手机验证码为" + vcode + ", (切勿将验证码告知别人, 请在5分钟内输入完成验证, 如有问题请联系客服。)";
                let rs = await this.smsClient.sendMsg(mobile, msg);
                //this.addLog(obj, "sms");
                console.log(rs);
            }
            return this.returnSuccess(1);
        } catch (error) {
            return system.getResultFail(500, "接口异常：" + error.message);
        }
    }

    // 登录接口 post
    async login(obj, obj1, req) {
        this.doMerchantId(obj);
        try {
            if (!obj.mobile) {
                return this.returnFail("请填写手机号");
            }
            let noteCode = (obj.noteCode || "").trim();
            if (!noteCode) {
                return this.returnFail("请填写短信验证码");
            }
            // TODO 手机号验证码登录
            let key = this.SMS_LOGINMOBILE_KEY + obj.mobile;
            let vcode = await this.redisClient.get(key + "t");

            if (!vcode) {
                return this.returnFail("短信验证码已过期，请重新发送");
            }
            if (vcode != noteCode) {
                return this.returnFail("短信验证码错误，请重新填写");
            }
            let openID = "gtbh5_" + obj.mobile;

            let merchant_id = obj.merchant_id;
            let params = {
                saas_merchant_id: merchant_id,
                saas_id: null,
                openid: openID,
                nickName: obj.mobile,
                avatarUrl: "",
                ucname: obj.mobile,
                mobile :obj.mobile,
            };

            let res = await this.merchantappletuserSve.login(params);
            if (res.status === 0) {
                return this.returnSuccess(res.data);
            } else {
                return this.returnFail(res.msg, res.data);
            }
        } catch (e) {
            console.log(e.stack);
        }
    }


    //验证登录
    async loginUser(obj) {
        this.doMerchantId(obj);
        // let merchant_id = decodeURIComponent(obj.merchant_id);
        // let merchant_id = system.decryption(decodeURIComponent(obj.merchant_id));
        let user = await this.getLoginUser(obj.merchant_id, obj.openid);
        return this.returnSuccess(user);
    }


    async uploadConfig(obj, obj1, req) {
        this.doMerchantId(obj);
        try {
            let data = await this.uploadCtl.getOssConfig();
            return this.returnSuccess(data);
        } catch (error) {
            console.log(error);
            return {code: 500};
        }
    }

    // 保存订单信息
    async saveOrder(obj, obj1, req) {
        this.doMerchantId(obj);

        try {
            // TODO this.loginUser();
            let loginUser = await this.loginUser(obj);
            if (!loginUser) {
                return this.returnFail("订单保存失败");
            }
            let rs = await this.buildOrder(obj);
            if (rs.code === 0) {
                return rs;
            }
            let bminfo = rs.data;
            // 银行卡四要数验证
            let bf = await this.bankfour({
                userName: bminfo.legal_name,
                userIdNo: bminfo.legal_idno,
                userBankNo: bminfo.bank_no,
                userMobile: bminfo.bank_mobile,
            });
           // this.addLog(obj, "bankfour");
            if (bf.code !== 0) {
                return this.returnFail("银行卡四要素验证失败，请检查法人姓名，身份证，银行卡号，银行卡预留手机号正确");
            }

            let merchant = await this.getMerchant(obj.merchant_id);
            //let loginUser = await this.getLoginUser(pobj.merchant_id, pobj.openid);
            let order = {
                saas_id: merchant.saas_id,
                merchant_id: merchant.id,
                channel_id: merchant.channel_id,
                product_id: "10020000",
                merchant_app_user_id: loginUser.data.id,
                price: system.y2f(merchant.sign.bm_reg_price) || 0,
                bminfo: rs.data
            };

            let res = await this.orderSve.microAdd(order);
            if (res.status === 0) {
                return this.returnSuccess(res.data);
            } else {
                return this.returnFail(res.msg || "保存订单失败");
            }
        } catch (e) {
            console.log(e.stack);
            return {
                code: -200,
                msg: "error",
                data: {},
                stack: e.stack
            };
        }
    }

    async buildOrder(obj) {
        if (!obj.idcard_front) {
            return this.returnFail("请上传身份证人像面");
        }
        if (!obj.idcard_back) {
            return this.returnFail("请上传身份证国徽图");
        }
        if (!obj.legal_name) {
            return this.returnFail("请填写法人姓名");
        }
        if (!obj.legal_mobile) {
            return this.returnFail("请填写联系手机");
        }
        if (!/^1\d{10}$/.test(obj.legal_mobile)) {
            return this.returnFail("联系手机格式错误");
        }
        if (!obj.legal_idno) {
            return this.returnFail("请填写身份证号码");
        }
        if (!await this.idcardClient.checkIDCard(obj.legal_idno)) {
            return this.returnFail("身份证号码错误，请检查后重新输入");
        }
        if (!obj.company_names) {
            return this.returnFail("请填写公司名称");
        }

        if (!obj.bank_front) {
            return this.returnFail("请上传银行卡正面");
        }
        if (!obj.bank_back) {
            return this.returnFail("请上传银行卡反面");
        }
        if (!obj.bank_name) {
            return this.returnFail("请填写银行预留手机号");
        }
        if (!obj.bank_no) {
            return this.returnFail("请填写银行预留手机号");
        }
        if (!obj.bank_mobile) {
            return this.returnFail("请填写银行预留手机号");
        }
        let noteCode = (obj.note_code || "").trim();
        if (!noteCode) {
            return this.returnFail("请填写短信验证码");
        }

        // let vcode = await this.redisClient.get(this.SMS_LOGINMOBILE_KEY + obj.bank_mobile);
        // if (!vcode) {
        //     return this.returnFail("短信验证码已过期，请重新发送");
        // }
        // if (vcode != noteCode) {
        //     return this.returnFail("短信验证码错误，请重新填写");
        // }
        let bminfo = {
            idcard_front: obj.idcard_front,
            idcard_back: obj.idcard_back,
            legal_name: obj.legal_name,
            legal_mobile: obj.legal_mobile,
            legal_idno: obj.legal_idno,
            company_names: obj.company_names,
            bank_front: obj.bank_front,
            bank_back: obj.bank_back,
            bank_name: obj.bank_name,
            bank_no: obj.bank_no,
            bank_mobile: obj.bank_mobile,
        };

        return this.returnSuccess(bminfo);
    }

    async myOrders(obj, obj1, req) {
        this.doMerchantId(obj);
        // TODO this.loginUser();
        let loginUser = await this.loginUser(obj);
        if (!loginUser) {
            return this.returnSuccess({count: 0, rows: []});
        }
        try {
            let params = {
                pageSize: Number(obj.pageSize || 10),
                currentPage: Number(obj.currentPage || 1),
                merchant_app_user_id: loginUser.data.id,
                merchant_id: loginUser.data.saas_merchant_id,
            }

            let listRes = await this.orderSve.page(params);
            if (listRes.status === 0) {
                if (listRes.status != 0) {
                    return system.getResult(null, `系统错误`);
                }
                let source_nos = [];
                for (let item of listRes.data.rows) {
                    source_nos.push(item.id);
                }
                if(source_nos.length==0){
                    return system.getResult(null, `暂无数据`);
                }
                let res =await this.orderSve.queryOrderStatusBySourceNo({source_nos:source_nos});
                if(res.status!=0){
                    return res;
                }
                let StatusMap = res.data;
                // for(let item of listRes.data.rows){
                //     if(StatusMap[item.id]){
                //         item.handle_name = StatusMap[item.id]['name3'] || "处理中";
                //     }else{
                //         item.handle_name ="订单处理中";
                //     }
                // }
                for(let item of listRes.data.rows){
                    if(StatusMap[item.id]){
                        item.handle_name = StatusMap[item.id]['name3'] || "处理中";
                    }else if(item.pay_status=="10"){
                        item.handle_name ="订单待处理";
                    }else if(item.audit_status=="30"){
                        item.handle_name ="订单处理失败";
                    }else{
                        item.handle_name = "订单处理中";
                    }
                }
                return this.returnSuccess(listRes.data);
            } else {
                return this.returnFail(listRes.msg);
            }
        } catch (e) {
            console.log(e.stack);
            //日志记录
            return {
                code: -200,
                msg: "error",
                data: {},
                stack: e.stack
            };
        }

        console.log(decryptData);
    }

    /**
     * 查询订单明细
     * @param {*} gobj
     * @param {*} pobj
     * @param {*} req
     * @param {*} loginUser
     */
    async orderInfo(obj, obj1, req) {
        this.doMerchantId(obj);

        // TODO this.loginUser();

        let loginUser = await this.loginUser(obj);
        if (!loginUser) {
            return this.returnSuccess({});
        }
        try {
            let rs = await this.orderSve.orderInfo(obj);
            if (rs.status === 0) {
                return this.returnSuccess(rs.data);
            } else {
                return this.returnFail(rs.msg);
            }
        } catch (error) {
            console.log(error);
            return system.getResult(null, error);
        }
    }

    async idNoValid(obj, obj1, req) {
        this.doMerchantId(obj);

        try {
            let idno = (obj.idno || "").trim();
            if (!idno) {
                return {code: 0, msg: "请填写身份证号码"};
            }

            let success = await this.idcardClient.checkIDCard(idno);
            if (success) {
                return this.returnSuccess(1);
            }
            return this.returnFail("身份证号码格式错误");
        } catch (error) {
            console.log(error);
            return {code: 500, msg: "服务忙，请稍后重试"};
        }
    }

    /**
     * 个体户列表/个体户列表
     * @param params
     * @param pobj2
     * @param req
     * @returns {Promise<void>}
     */
    async saasorderbusinessmenPage(params, pobj2, req) {
        this.doMerchantId(params);

        // TODO this.loginUser();

        let loginUser = await this.loginUser(params);
        params.merchant_app_user_id = loginUser.data.id;
        let res = await this.businessmenSve.saasorderbusinessmenPage(params);
        if (res.status == 0) {
            return this.returnSuccess(res.data);
        } else {
            this.returnFail("请求超时 请稍后在试");
        }
    }

    /**
     * 获取用户下的所有交易记录
     * @param pobj1
     * @param pobj2
     * @param req
     * @returns {Promise<{msg: string, data: (*|null), bizmsg: string, status: number}>}
     */
    async saasTradeBusinessmenPage(obj, obj1, req) {
        this.doMerchantId(obj);

        // TODO this.loginUser();
        let loginUser = await this.loginUser(obj);
        obj.merchant_app_user_id = loginUser.data.id;
        obj.attrs = ["credit_code"];
        if (!obj.merchant_app_user_id) {
            return system.getResult(null, `登录失效，请重新登录`);
        }
        try {
            let creditCodeArray = await this.businessmenSve.assorderBusinessmenInfo(obj);
            if (creditCodeArray.status != 0) {
                return this.returnSuccess({count: 0, rows: []});
            }
            let creditCodes = [];
            for (let val of creditCodeArray.data) {
                creditCodes.push(val.credit_code);
            }
            if (!creditCodes || creditCodes.length == 0) {
                return this.returnSuccess({count: 0, rows: []});
            }
            obj.credit_code_array = creditCodes;
            let res = await this.tradeSve.tradeItemBycreditCode(obj);
            if (res.status == 0) {
                return this.returnSuccess(res.data);
            } else {
                return this.returnFail("请求超时 请稍后在试");
            }
        } catch (e) {
            console.log(e);
            return this.returnFail("请求超时 请稍后在试");
        }
    }

    /**
     * 发票管理
     * @param pobj1
     * @param pobj2
     * @param req
     * @returns {Promise<void>}
     */
    async invoiceBycreditCode(obj, obj1, req) {
        this.doMerchantId(obj);

        // TODO this.loginUser();
        let loginUser = await this.loginUser(obj);
        obj.merchant_app_user_id = loginUser.data.id;
        obj.attrs = ["credit_code"];
        if (!obj.merchant_app_user_id) {
            return system.getResult(null, `登录失效，请重新登录`);
        }
        try {
            let creditCodeArray = await this.businessmenSve.assorderBusinessmenInfo(obj);
            if (creditCodeArray.status != 0) {
                return this.returnSuccess({count: 0, rows: []});

            }
            let creditCodes = [];
            for (let val of creditCodeArray.data) {
                creditCodes.push(val.credit_code);
            }
            if (!creditCodes || creditCodes.length == 0) {
                return this.returnSuccess({count: 0, rows: []});
            }
            obj.credit_code_array = creditCodes;

            let res = await this.saasInvoiceSve.invoiceBycreditCode(obj);
            if (res.status == 0) {
                return this.returnSuccess(res.data);
            } else {
                return this.returnFail("请求超时 请稍后在试");
            }
        } catch (e) {
            console.log(e);
            return system.getResult(null, `系统错误`);
        }
    }

    /**
     * 银行卡预留手机号短信验证码
     * @param pobj1
     * @param pobj
     * @param req
     * @returns {Promise<void>}
     */
    async sendBankMobileCode(obj, obj1, req) {
        this.doMerchantId(obj);

        // TODO this.loginUser();
        let loginUser = await this.loginUser(obj);
        let mobile = obj.mobile;
        if (!mobile) {
            return this.returnFail("请先填写银行卡预留手机号");
        }
        if (validation.isMobile(mobile)) {
            return this.returnFail("银行卡预留手机号格式错误");
        }
        try {
            let key = this.SMS_LOGINMOBILE_KEY + mobile;
            let vcode = await this.redisClient.get(key + "t");
            // let vcode;
            if (!vcode) {
                vcode = await this.getVCode();
                await this.redisClient.setWithEx(key, vcode, 5 * 60);
                await this.redisClient.setWithEx(key + "t", vcode, 60);
                let msg = "您的个体户注册手机验证码为" + vcode + ", (切勿将验证码告知别人, 请在5分钟内输入完成验证, 如有问题请联系客服。)";
                let rs = await this.smsClient.sendMsg(mobile, msg);
                //this.addLog(pobj, "sms");
                console.log(rs);
            }
            return this.returnSuccess(1);
        } catch (error) {
            return system.getResultFail(500, "接口异常：" + error.message);
        }
    }


    getVCode() {
        var randomNum = "" + Math.round(Math.random() * 1000000);
        while (randomNum.length < 6) {
            randomNum = "0" + randomNum;
        }
        return randomNum;
    }

    async bankfour(params) {
        let nonceStr = await this.getUidStr(16, 36);
        let data = {
            appId: this.GTB_APPID,
            userName: params.userName,
            userIdNo: params.userIdNo,
            userBankNo: params.userBankNo,
            userMobile: params.userMobile,
            nonceStr: nonceStr,
        };

        // 签名
        var signArr = [];
        var keys = Object.keys(data).sort();
        for (var i = 0; i < keys.length; i++) {
            var k = keys[i];
            var v = data[k];
            if (!k || !v || k == 'sign') {
                continue;
            }
            signArr.push(k + "=" + v);
        }

        var signStr = signArr.join("&") + "&key=" + this.GTB_KEY;
        var sign = md5(signStr).toUpperCase();
        console.log(sign);
        data.sign = sign;
        let rs = await axios({
            method: 'post',
            url: this.BANK_FOUR,
            data: data,
        });
        try {
            console.log(rs.data, `个体户注册银行卡四要素验证request[${JSON.stringify(data)}], response[${JSON.stringify(rs.data)}]`);
        } catch (e) {
            console.log(e.stack);
        }
        return rs.data || {};
    }


    //日志
    async addLog(obj, consume_type) {
        let user = await this.getLoginUser(obj.merchant_id, obj.openid);
        let log = {
           // saas_id: user.saas_id,
            saas_merchant_id: user.saas_merchant_id,
            consume_type: consume_type,
            consume_id: user.id
        };
        let rs = await this.merchantSve.addConsumeLog({log: log});
        console.log("log rs : ", rs);
    }


    returnResult(code, msg, data) {
        return {
            code: code || 0,
            msg: msg || "",
            data: data
        }
    }

    returnSuccess(data) {
        return this.returnResult(1, "success", data)
    }

    returnFail(msg, data) {
        return this.returnResult(0, msg, data);
    }

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

    getUidStr(len, radix) {
        var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
        var uuid = [],
            i;
        radix = radix || chars.length;
        if (len) {
            for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
        } else {
            var r;
            uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
            uuid[14] = '4';
            for (i = 0; i < 36; i++) {
                if (!uuid[i]) {
                    r = 0 | Math.random() * 16;
                    uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
                }
            }
        }
        return uuid.join('');
    }

    exam() {
        return "";
    }

    classDesc() {
        return {
            groupName: "",
            groupDesc: "",
            name: "",
            desc: "",
            exam: "",
        };
    }

    methodDescs() {
        return [
            {
                methodDesc: "",
                methodName: "",
                paramdescs: [
                    {
                        paramDesc: "",
                        paramName: "",
                        paramType: "",
                        defaultValue: "",
                    }
                ],
                rtnTypeDesc: "",
                rtnType: ""
            }
        ];
    }
}

module.exports = TestAPI;
