var system = require("../../../system");
var settings = require("../../../../config/settings");
const AppServiceBase = require("../../app.base");
const axios = require('axios')
const md5 = require('md5')
var AlipaySdk = require('alipay-sdk').default;
var WXPay = require('wx-pay');
var xml2js = require('xml2js');
//产品操作类
class UtilsUcommuneService extends AppServiceBase {
    constructor() {
        super();
        this.centerOrderUrl = settings.centerOrderUrl();
        this.centerChannelUrl = settings.centerChannelUrl();
        this.redisClient = system.getObject("util.redisClient");
        this.utilsAuthSve = system.getObject("service.utilsSve.utilsAuthSve");
        this.paySecret = settings.paySecret()
    }

    //--------------------------------优客工厂相关接口-start-----------------------------------------------------


    /**
     * 根据优客token获取用户信息，生成userPin返回前端
     * @param {*} pobj 
     * @param {*} actionBody userToken 为优客工厂的userToken
     */
    async getUserInfo(pobj, actionBody) {
        if (!actionBody.userToken) {
            return system.getResult(null, "actionBody.token can not be empty，100410");
        }
        var url = settings.ucommuneUrl() + "third/getUserInfo";    // 调用优客工场接口 获取用户信息
        // 拼接规则curl -k -H 'Content-type: application/json' -H 'authorization:{token}' -X POST {url} pobj作为发生错误时记录日志用
        let result = await this.restPostWithHAuthorizationUrl(pobj, actionBody.userToken, url);
        if (result.retCode == 0) {    // 0成功 1失败
            pobj.actionType = "getLoginByUserName";
            pobj.actionBody.channelUserId = result.data.nationalCode + "-" + result.data.mobile; // 即：86_18512345678
            pobj.actionBody.userName = result.data.mobile;
            pobj.actionBody.nickName = result.data.name;
            pobj.actionBody.mobile = result.data.mobile;
            pobj.actionBody.headUrl = result.data.headImg;
            pobj.actionBody.userpin = pobj.actionBody.userpin || this.getUUID();
            var tmpOpResult = await this.utilsAuthSve.getLoginByUserName(pobj, pobj.actionBody);
            if (tmpOpResult.status != 0 && tmpOpResult.status != 2060) {
                return tmpOpResult;
            }
            return system.getResultSuccess({ userpin: tmpOpResult.data.userpin ? tmpOpResult.data.userpin : pobj.actionBody.userpin })
        } else {
            // 获取用户信息失败
            return system.getResult(null, result);
        }
    }
    /**
     * 优客调取订单列表用
     * @param {*} pobj 
     * @param {*} actionBody 
     */
    async ucommuneGetOrderList(pobj, actionBody) {
        // ucommuneGetOrderList
        var reqUrl = this.centerOrderUrl + "action/ucommuneOrder/springBoard";
        var result = await this.restPostUrl(pobj, reqUrl);
        console.log("-------------ucommuneGetOrderList result start---------------")
        console.log(result)
        console.log("-------------ucommuneGetOrderList result end---------------")
        return result;
    }

    /**
     * addOrder后进入支付页面获取支付金额 addorder返回totalsum 此接口可以不调用
     * @param {*} pobj 
     * @param {*} actionBody orderNo orderIndo订单号
     */
    async orderTotalSum(pobj, actionBody) {
        pobj.actionType = "getOrderDetails" // 获取订单详细信息  totalsum为总金额，返回给前端
        var reqUrl = this.centerOrderUrl + "action/order/springBoard";
        var result = await this.restPostUrl(pobj, reqUrl);
        return result;
    }

    /**
     * 点击确认支付后返回拼接字符串
     * @param {*} pobj 
     * @param {*} actionBody orderNo orderIndo订单号
     */
    async orderConfirm(pobj, actionBody) {
        await this.orderConfirmValidate(pobj, actionBody);
        pobj.actionType = "getPayOrderInfo" // 获取订单详细信息 用来拼接字符串 totalsum为总金额，返回给前端
        var reqUrl = settings.centerOrderUrl() + "action/order/springBoard";
        var orderResult = await this.restPostUrl(pobj, reqUrl);
        if (orderResult.status != 0) {
            // return system.getResult(null, "Failed to get orderResult or order has been paid 100470");
            return system.getResult(null, orderResult);
        } else {
            if (actionBody.payWay == 1) { // 支付宝
                try {
                    let creatPayRequrl = "https://yf-api.gongsibao.com/pay/v1/aliPay/getPrePayIdAliPay";
                    let params = {
                        "app": "ukgc",//固定
                        'body': orderResult.data.orderProduct.channelItemName,
                        "key": "a1519e2eab53dfb909e4c32a86b2ea2b",//固定
                        "notifyUrl": this.centerChannelUrl + "orderNotify/aliPayNotify",
                        "outTradeNo": orderResult.data.receiptVoucher.sourceOrderNo + "-" + pobj.appInfo.uapp_id.toString() + "-" + orderResult.data.orderProduct.id.toString(),
                        "productCode": orderResult.data.orderProduct.channelItemCode,
                        "subject": orderResult.data.orderProduct.channelItemName,
                        "timeoutExpress": '10m',
                        "totalAmount": orderResult.data.receiptVoucher.totalSum,
                    }
                    var sign = JSON.stringify(params);
                    // sign +=  "ab53dfb909e4c32a"
                    sign += this.paySecret
                    sign = md5(sign).toUpperCase()
                    params.sign = sign
                    let res = await axios.post(creatPayRequrl, params)
                    if (res.status == 200 && res.data.code == 200) {
                        await this.cacheManager["TlPayLocker"].init(orderResult.data.receiptVoucher.sourceOrderNo);
                        return system.getResultSuccess(res.data)
                    }
                    return system.getResult(null, res.data);
                } catch (e) {
                    this.logCtl.error({
                        optitle: "alipay生成支付串---error异常",
                        op: "center-app/app/base/service/impl/utilsSve/utilsUcommuneSve.js/orderConfirm",
                        content: "参数=" + JSON.stringify(orderResult) + "，error：" + e.stack,
                        clientIp: pobj.client_ip || ""
                    });
                    return system.getResultFail(-200, e.stack);
                }


                // 之前写的 调用wx/alipay的方法，后续用不到会删掉
                // let sign = await PayUtil.getSign(null,"1")
                // let params = {
                //     "partner" : "2019022163300183" ,
                //     "seller_id" : "353494220@qq.com" ,
                //     // "out_trade_no" : orderResult.data.channelOrderNo ,
                //     "out_trade_no": orderResult.data.receiptVoucher.sourceOrderNo + "-" + pobj.appInfo.uapp_id.toString() + "-" + orderResult.data.orderProduct.id.toString(),
                //     "subject" : orderResult.data.orderProduct.channelItemName ,
                //     "body" : orderResult.data.orderProduct.channelItemName ,
                //     "total_fee" : Number(orderResult.data.receiptVoucher.totalSum) ,
                //     "service" : "alipay.trade.app.pay" ,
                //     "payment_type" : "1" ,
                //     "_input_charset" : "utf-8" ,
                //     "it_b_pay" : "10m" ,
                //     "notify_url" : this.centerChannelUrl + "orderNotify/aliPayNotify" ,
                //     "enable_paymethod" : "balance,moneyFund,coupon,pcredit,pcreditpayInstallment,creditCard,creditCardExpress,creditCardCartoon,credit_group,debitCardExpress,mcard,pcard,promotion" ,
                //     "sign" : sign ,
                //     "sign_type" : "RSA2",
                // }
                // let str = "";
                // for(var k in params) {
                //     console.log(k)
                //     str += k + "=\"" + params[k] + "\"&";
                // }
                // str = str.substr(0,str.length-1)
                // console.log(str)
                // return system.getResultSuccess(str);
                // let alipayAgentInformation = await this.redisClient.get("alipayAgentInformation")
                // if(!alipayAgentInformation) {
                //     console.log("11111")
                //     let res = await axios.post('https://yf-api.gongsibao.com/pay/v1/getPayConfig',{
                //         "app": "ukgc", //应用名称 固定
                //         "key": "a1519e2eab53dfb909e4c32a86b2ea2b", //应用 key 固定
                //         "paymentType": "1", //支付方式 1 支付宝 3 微信
                //         "sign":"D6C4DE28278BC3AAF1C5B22E834F3850"
                //     })
                //     if(res.status == 200) {
                //         alipayAgentInformation = res.data
                //         await this.redisClient.set('alipayAgentInformation',JSON.stringify(res.data))
                //         console.log("缓存alipayAgentInformation")
                //     } else {
                //         return system.getResult(null, "actionBody.token can not be empty，100410");
                //     }
                // }
                // let agentInformation = JSON.parse(alipayAgentInformation)
                // let alipay = new AlipaySdk({

                //     appId: agentInformation.appid,

                //     privateKey: agentInformation.publicKey,

                //     // alipayPublicKey: agentInformation.publicKey,

                // });
                // const params = {
                //     bizContent: {
                //       out_trade_no: '12312312321212', // 商户网站唯一订单号
                //       subject: encodeURIComponent('苹果电脑'),//商品的标题/交易标题/订单标题/订单关键字等
                //       total_amount: 0.2,//实际付款金额
                //       body: encodeURIComponent('Mac Pro1'),//对一笔交易的具体描述信息。如果是多种商品，请将商品描述字符串累加传给body
                //       product_code: 'QUICK_MSECURITY_PAY',
                //       notifyUrl:this.centerChannelUrl + "orderNotify/aliPayNotify"
                //     }
                //   }
                // let alipayResponse = await alipay.exec('alipay.trade.app.pay', params);
                // console.log(alipayResponse)
                // return system.getResultSuccess(alipayResponse)


                // var newobj = JSON.stringify(obj).replace(/\s*/g,"");
                // newobj +=  "ab53dfb909e4c32a"
                // newobj = md5(newobj).toUpperCase()
                // obj.sign = newobj
                // let res = await axios.post(reqUrl, obj)
                // console.log(res);
                // const params = {
                //     bizContent: {
                //       out_trade_no: '12312312321212', // 商户网站唯一订单号
                //       subject: encodeURIComponent('苹果电脑'),//商品的标题/交易标题/订单标题/订单关键字等
                //       total_amount: 0.2,//实际付款金额
                //       body: encodeURIComponent('Mac Pro1'),//对一笔交易的具体描述信息。如果是多种商品，请将商品描述字符串累加传给body
                //       product_code: 'QUICK_MSECURITY_PAY',
                //       notifyUrl:this.centerChannelUrl + "orderNotify/aliPayNotify"
                //     }
                //   }
                // let alipayResponse = await this.alipay.exec('alipay.trade.app.pay', params);
                // console.log(alipayResponse);
            }
            if (actionBody.payWay == 3) { // 微信
                await this.cacheManager["TlPayLocker"].init(orderResult.data.receiptVoucher.sourceOrderNo);
                let creatPayRequrl = "https://yf-api.gongsibao.com/pay/v1/createSign";
                let params = {
                    "app": "ukgc",
                    "key": "a1519e2eab53dfb909e4c32a86b2ea2b",
                    "payParam": [
                        {
                            "name": "appid",
                            // 后期修改
                            // "value":"1"
                            "value": "wx6f3ebe44defe336a"
                        },
                        {
                            "name": "mch_id",
                            // "value":"1"
                            "value": "1232813602"
                        },
                        {
                            "name": "device_info",
                            "value": "1000"
                        },
                        {
                            "name": "body",
                            "value": "商标"
                            // "value":orderResult.data.orderProduct.channelItemName
                        },
                        {
                            "name": "nonce_str",
                            // "value":"ibuaiVcKdpRxkhJA"
                            "value": WxPayUtil.generateNonceString()
                        },
                        {
                            "name": "openid",
                            "value": "o7kgSs_2cuJxyBoIEWMwRUPfobLg"
                        },
                        {
                            "name": "notify_url",
                            "value": "http://"
                            // "value":this.centerChannelUrl + "orderNotify/wxPayNotify",
                        },
                        {
                            "name": "out_trade_no",
                            // "value": "OT37202006221758koyn-37-69"
                            "value": orderResult.data.receiptVoucher.sourceOrderNo + "-" + pobj.appInfo.uapp_id.toString() + "-" + orderResult.data.orderProduct.id.toString()
                        },
                        {
                            "name": "sign_type",
                            "value": "MD5"
                        },
                        {
                            "name": "total_fee",
                            "value": "399"
                            // "value":orderResult.data.receiptVoucher.totalSum,
                        },
                        // {
                        //     "name":"spbill_create_ip",
                        //     // "value":'1'
                        //     "Value": '192.168.2.210',
                        // },
                        {
                            "name": "trade_type",
                            "value": "JSAPI"
                        }
                    ],
                    "paymentType": "3"
                }
                // let params = {
                //     "app": "ukgc",//固定
                //     'body': orderResult.data.orderProduct.channelItemName,
                //     "key": "a1519e2eab53dfb909e4c32a86b2ea2b",//固定
                //     "notifyUrl" : this.centerChannelUrl + "orderNotify/aliPayNotify",
                //     "outTradeNo": orderResult.data.receiptVoucher.sourceOrderNo + "-" + pobj.appInfo.uapp_id.toString() + "-" + orderResult.data.orderProduct.id.toString(),
                //     "totalFee" :  orderResult.data.receiptVoucher.totalSum,
                //     "spbillCreateIp":'192.168.2.210',
                //     "tradeType":"JSAPI"
                // }
                var sign = JSON.stringify(params);
                // sign +=  "ab53dfb909e4c32a"
                sign += this.paySecret
                sign = md5(sign).toUpperCase()
                params.sign = sign
                console.log(params)
                let res = await axios.post(creatPayRequrl, params)
                if (res.status == 200 && res.data.code == 200) {
                    await this.cacheManager["TlPayLocker"].init(orderResult.data.receiptVoucher.sourceOrderNo);
                    return system.getResultSuccess(res.data)
                }
                return system.getResult(null, res.data);

                // 之前写的 调用wx/alipay的方法，后续用不到会删掉
                // let sign = await PayUtil.getSign('wx6f3ebe44defe336a',"3")
                // let wxpayJson = {
                //     "appid": "wx05b764a334ca0472",
                //     "noncestr": "fdbe012e2e11314b96402b32c0df26b7",
                //     "package": "Sign=WXPay",
                //     "partnerid": "1525494731",
                //     "prepayid": "wx221007210600552805dae6511340418300",
                //     "sign": "7BACA717B040DEEA7A8940CEC94A3318",
                //     "timestamp": "1592791641"
                // }
                // let wxAgentInformation = await this.redisClient.get("wxAgentInformation")
                // if(!wxAgentInformation) {
                //     console.log("11111")
                //     let res = await axios.post('https://yf-api.gongsibao.com/pay/v1/getPayConfig',{
                //         "app": "ukgc", //应用名称 固定
                //         "key": "a1519e2eab53dfb909e4c32a86b2ea2b", //应用 key 固定
                //         "paymentType": "3", //支付方式 1 支付宝 3 微信
                //         "sign":"23F763A515AEF5DFC0A2BC04CC21463F"
                //     })
                //     if(res.status == 200) {
                //         wxAgentInformation = res.data
                //         await this.redisClient.set('wxAgentInformation',JSON.stringify(res.data))
                //         console.log("缓存wxAgentInformation")
                //     } else {
                //         return system.getResult(null, "actionBody.token can not be empty，100410");
                //     }
                // }
                // let agentInformation = JSON.parse(wxAgentInformation)
                // var unifiedorderUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";
                // const opts = {
                //     out_trade_no: '12312312321212', // 商户网站唯一订单号
                //     total_fee: 0.2,//实际付款金额
                //     body: encodeURIComponent('Mac Pro1'),//对一笔交易的具体描述信息。如果是多种商品，请将商品描述字符串累加传给body
                //     spbill_create_ip: this.centerChannelUrl,
                //     notify_url:this.centerChannelUrl + "orderNotify/aliPayNotify",
                //     trade_type: 'NATIVE',
                //     attach: ""
                // }

                // opts.nonce_str = opts.nonce_str || WxPayUtil.generateNonceString();

                // opts.appid = agentInformation.appid;

                // opts.mch_id = agentInformation.mchid;

                // opts.device_info = "WEB";

                // opts.sign = WxPayUtil.sign(opts);


                // var postXml = WxPayUtil.buildXML({ xml: opts });

                // axios.post(unifiedorderUrl, postXml).then(function(result) {

                //     // console.log("微信付款单请求result.data",result.data);

                //    WxPayUtil.parseXML(result.data,function(json){
                //         func(json)
                //    });

                // }).catch(function(error){
                //     console.log("微信生成付款单错误",error);
                // })

                // let wepay = new WXPay({

                //     appId: agentInformation.appid,

                //     mch_id: agentInformation.mchid,

                // });
                // let res = await wepay.createUnifiedOrder({
                //     body: '扫码支付测试',
                //     out_trade_no: '20140703'+Math.random().toString().substr(2, 10),
                //     total_fee: 1,
                //     spbill_create_ip: '192.168.2.210',
                //     notify_url: 'http://wxpay_notify_url',
                //     trade_type: 'NATIVE',
                //     product_id: '1234567890'
                // },function(err,res) {
                //     console.log(err);
                //     console.log(res);
                // })
                // console.log(res)
                // let res = await axios.post(reqUrl,obj)
                // console.log(res);
                // console.log(this.WXpay)
                // var wxpay = this.WXpay;
                // var out_trade_no='20160203'+Math.random().toString().substr(2, 10);
                // wxpay.createUnifiedOrder({
                // 	body: '充值兑换宝币',
                // 	out_trade_no: out_trade_no,
                // 	total_fee: 1,
                // 	spbill_create_ip: '192.168.2.210',
                // 	notify_url: 'http://www.gongsibao.com',
                // 	trade_type: 'NATIVE',
                // 	product_id: '1234567890'
                // },function(err, res) {
                //     console.log(res);
                //     return system.getResult(res)
                // })
            }
        }
    }

    /**
     * 点击确认支付后返回拼接字符串 orderConfirm 的验证数据方法
     * @param {*} pobj 
     * @param {*} actionBody orderNo orderIndo订单号
     */
    async orderCheck(pobj, actionBody) {
        pobj.actionType = "getOrderDetails" // 获取订单详细信息  totalsum为总金额，返回给前端
        var reqUrl = this.centerOrderUrl + "action/order/springBoard";
        var result = await this.restPostUrl(pobj, reqUrl);
        return result;
    }

    /**
     * 点击确认支付后返回拼接字符串 orderConfirm 的验证数据方法
     * @param {*} pobj 
     * @param {*} actionBody orderNo orderIndo订单号
     */
    async orderConfirmValidate(pobj, actionBody) {
        if (!actionBody.orderNo) { // 订单号
            return system.getResult(null, "actionBody.orderNo can not be empty，100430");
        }
        if (!actionBody.payWay) { // 支付方式 1 支付宝 3微信
            return system.getResult(null, "actionBody.payWay can not be empty，100440");
        }
        if (actionBody.payWay != 1 || actionBody.payWay != 3) { // payway 非1非3 
            return system.getResult(null, "actionBody.payWay is eoor values，100450");
        }
    }

    /**
     * 订单详情
     * @param {*} pobj 
     * @param {*} actionBody orderNo orderIndo订单号
     */
    async ucommuneGetOrderDetail(pobj, actionBody) {
        return system.getResultSuccess()
    }


    //--------------------------------优客工厂相关接口--end----------------------------------------------------

}


// 之前写的 调用wx/alipay的方法，后续用不到会删掉
PayUtil = {
    getSign: async function (appid, paymentType) {
        let requrl = "https://yf-api.gongsibao.com/pay/v1/createSign"
        let params = {
            "app": "ukgc",
            "key": "a1519e2eab53dfb909e4c32a86b2ea2b",
            "payParam": [
                {
                    "name": "app_id",
                    "value": appid || "2019022163300183"
                },
                {
                    "name": "charset",
                    "value": "UTF-8"
                },
                {
                    "name": "method",
                    "value": "alipay.trade.app.pay"
                },
                {
                    "name": "sign_type",
                    "value": "RSA2"
                },
                {
                    "name": "timestamp",
                    "value": Date.now().toString()
                },
                {
                    "name": "version",
                    "value": "1.0"
                }
            ],
            "paymentType": paymentType,
        }
        var signstr = JSON.stringify(params);
        signstr += "ab53dfb909e4c32a"
        signstr = md5(signstr).toUpperCase()
        params.sign = signstr
        let res = await axios.post(requrl, params)
        if (res.data.code = 200) {
            return res.data.value
        }
        return system.getResult(null, "Failed to get sign， 100460");
    },
}

module.exports = UtilsUcommuneService;

WxPayUtil = {
    generateNonceString: function (length) {
        var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        var maxPos = chars.length;
        var noceStr = "";
        for (var i = 0; i < (length || 32); i++) {
            noceStr += chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return noceStr;
    }

}