/**
 *Created by ZHJY on 2020/7/14.
 */
var payContainer = new Vue({
    el:"#payContainer",
    data: {
        isSubMitStatus:false,
        payInfo:{
            PAY_BANK_NUM: '', //支付类型
            PAY_ORDERID: '',  //订单ID
            PAY_UNPAIDAMOUNT: '', //待支付金额
            PAY_PAYAMOUNT: 0,//本次支付金额
            PAY_MOBILE_URL: '',//二维码生成链接
            PAY_DATA:{}       //支付数据
        },
        bankData:[
            {imgUrl:'/img/pay/iconbank-01@2x.png',bankName:'中国工商银行',bankNum:'ICBC_B2B'},
            {imgUrl:'/img/pay/iconbank-02@2x.png',bankName:'招商银行',bankNum:'CMBCHINA_B2B'},
            {imgUrl:'/img/pay/iconbank-03@2x.png',bankName:'中国建设银行',bankNum:'CCB_B2B'},
            {imgUrl:'/img/pay/iconbank-04@2x.png',bankName:'交通银行',bankNum:'BOCO_B2B'},
            {imgUrl:'/img/pay/iconbank-05@2x.png',bankName:'兴业银行',bankNum:'CIB_B2B'},
            {imgUrl:'/img/pay/iconbank-06@2x.png',bankName:'中国民生银行',bankNum:'CMBC_B2B'},
            {imgUrl:'/img/pay/iconbank-07@2x.png',bankName:'中国广发银行',bankNum:'CEB_B2B'},
            {imgUrl:'/img/pay/iconbank-08@2x.png',bankName:'中国银行',bankNum:'BOC_B2B'},
            {imgUrl:'/img/pay/iconbank-09@2x.png',bankName:'平安银行',bankNum:'SZPA_B2B'},
            {imgUrl:'/img/pay/iconbank-10@2x.png',bankName:'中信银行',bankNum:'ECITIC_B2B'},
            {imgUrl:'/img/pay/iconbank-11@2x.png',bankName:'浦发银行',bankNum:'SPDB_B2B'},
            {imgUrl:'/img/pay/iconbank-12@2x.png',bankName:'华夏银行',bankNum:'HXB_B2B'},
            {imgUrl:'/img/pay/iconbank-13@2x.png',bankName:'北京银行',bankNum:'BCCB_B2B'},
            {imgUrl:'/img/pay/iconbank-14@2x.png',bankName:'中国农业银行',bankNum:'ABC_B2B'},
            {imgUrl:'/img/pay/iconbank-15@2x.png',bankName:'中国邮政储蓄银行',bankNum:'PSBC_B2B'},
            {imgUrl:'/img/pay/iconbank-16@2x.png',bankName:'徽商银行',bankNum:'HSB_B2B'},
            {imgUrl:'/img/pay/iconbank-17@2x.png',bankName:'青岛银行',bankNum:'QDYH_B2B'},
            {imgUrl:'/img/pay/iconbank-18@2x.png',bankName:'浙商银行',bankNum:'CZ_B2B'},
            {imgUrl:'/img/pay/iconbank-19@2x.png',bankName:'齐鲁银行',bankNum:'QLYH_B2B'}
        ],
        methodTab:['线上支付','转账支付'],
        mobileData:[
            {imgUrl:'/img/pay/iconbank-ali@2x.png',bankName:'支付宝支付',bankNum:'ALIPAY'},
            {imgUrl:'/img/pay/iconbank-wx@2x.png',bankName:'微信支付',bankNum:'WEIXIN'},
            {imgUrl:'/img/pay/iconbank-bank@2x.png',bankName:'网银支付',bankNum:'ICBC_B2B'}
        ],
        pageType:'',//页面跳转类型
        paidAmount:'',//订单待付金额
        payableAmount:'',//应付金额
        receiptAmount:'',//已支付金额
        balanceAmount:'',//应付剩余金额
        payAmount:'',//本次支付金额
        paymentIimit:50000,
        paymentIimitText:'',
        discernReceiptList:[],//支付记录列表
        tabIndex:0,//支付方式 0 移动支付 1网银支付 2线下转账
        mbOrderId:'',//支付订单ID
        mobileTabIndex:null,
        bankTabIndex:0,
        isRequest:false,
        isPayAlert:false,
        isPaySwitch:false,
        paySuccessCounter:'',
        bankPayLink_url:'',
        orderIdentificationId:'',//订单标识
        receiptStatus:'',
        invoiceStatus:false,
        isReceiptStatus:false,
        onlinePayFlag:'',
        payStatusText:'使用微信和企业网银支付全部金额后，供应商会在24小时后发货（周末、节假日顺延）。若着急发货，可以选择使用线下转账进行付款。',
        productID:'',//发布商品的ID
        is_Wechat_bowcr:false
    },
    filters: {
        NumFormat:function(value) {
            if(!value) return '0.00';
            var intPart = Number(value) - Number(value)%1; //获取整数部分（这里是windy93的方法）
            var intPartFormat = intPart.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,'); //将整数部分逢三一断
            var floatPart = ".00"; //预定义小数部分
            var value2Array = value.toString().split(".");
            if(value2Array.length == 2) {  //=2表示数据有小数位
                floatPart = value2Array[1].toString(); //拿到小数部分
                if(floatPart.length == 1) { //补0,实际上用不着
                    return intPartFormat + "." + floatPart + '0';
                } else {
                    return intPartFormat + "." + floatPart;
                }
            } else {
                return intPartFormat + floatPart;
            }
        }
    },
    methods: {
        infoPayOrderCheckoutCounter:function(){//初始化订单数据
            var _self = this;
            PayApi.PayOrderCheckoutCounter({orderId:_self.payInfo.PAY_ORDERID},function(response){
                if(response.code == 0){
                    // console.log(response);
                    var data = response.data; //金额初始化
                    _self.payInfo.PAY_UNPAIDAMOUNT = (data.order.payableAmount - data.order.receiptAmount).toFixed(2);
                    _self.payInfo.PAY_PAYAMOUNT = (data.order.payableAmount-data.order.receiptAmount).toFixed(2);
                    _self.discernReceiptList = data.discernReceipt;
                    _self.paidAmount =  (data.order.payableAmount-data.order.receiptAmount).toFixed(2);
                    _self.receiptAmount =  data.order.receiptAmount;
                    _self.payableAmount=  data.order.payableAmount;
                    _self.balanceAmount =  ( _self.payableAmount - _self.receiptAmount).toFixed(2) - _self.payInfo.PAY_PAYAMOUNT;
                    _self.payAmount =  (_self.payableAmount - _self.receiptAmount).toFixed(2);//本次支付金额
                    _self.paySuccessCounter = data.order.paySuccessCounter;
                    _self.receiptStatus =  data.order.receiptStatus;
                    _self.invoiceStatus = data.order.invoiceStatus;
                    _self.onlinePayFlag = data.order.onlinePayFlag;
                    if(_self.receiptAmount>0){
                        _self.payStatusText = '使用微信和企业网银支付全部金额后，供应商会在24小时后发货（周末、节假日顺延）。';
                        _self.isReceiptStatus = false;
                    }else{
                        _self.payStatusText = '使用微信和企业网银支付全部金额后，供应商会在24小时后发货（周末、节假日顺延）。若着急发货，可以选择使用线下转账进行付款。';
                        _self.isReceiptStatus = true;
                    }
                    _self.isRequest = true;
                    _self.PayOrderOnLineSwitch();
                }else{
                    CAIMEI.Alert(response.msg,'确定',false);
                }
            })
        },
        PayOrderOnLineSwitch:function(){//获取是否可以先上支付
            var _self = this;
            PayApi.PayOrderOnLineSwitch({},function(response){
                if(response.code == 0){
                    if(response.data === 0){
                        _self.isPaySwitch = true;
                        CAIMEI.Alert('线上支付功能正在维护中，请前往订单详情页面查看线下转账方式后进行付款','确定',true,function(){
                            window.location.href='/user/order/detail.html?orderId='+_self.payInfo.PAY_ORDERID;
                        });
                    }
                }else{
                    CAIMEI.Alert(response.msg,'确定',false);
                }
            })
        },
        PayMobileSubmitFn:function(){//点击移动支付方式
            var _self = this;
            if(_self.invoiceStatus){
                _self.layerConfirm();
            }else{
                if(_self.payInfo.PAY_BANK_NUM == ''){
                    CAIMEI.dialog('请选择支付方式');
                    return;
                }
                if(_self.payAmount == ''){
                    CAIMEI.dialog('请输入本次支付金额');
                    return;
                }
                if(_self.payAmount == 0){
                    CAIMEI.dialog('本次支付金额不能为0');
                    return;
                }
                if(_self.payAmount*100 < 2){
                    CAIMEI.dialog('本次支付金额必须大于￥0.02');
                    return;
                }
                if(_self.payAmount > _self.paymentIimit){
                    switch (_self.payInfo.PAY_BANK_NUM) {
                        case 'WEIXIN':
                            _self.paymentIimitText = '本次支付金额已超出微信支付限额，请输入小于5万的金额进行支付';
                            break;
                        case 'ALIPAY':
                            _self.paymentIimitText = '本次支付金额已超出支付宝限额，请输入小于5万的金额进行支付';
                            break;
                    }
                    CAIMEI.Alert(_self.paymentIimitText,'知道了');
                    return;
                }
                if(_self.payInfo.PAY_BANK_NUM == "WEIXIN"){

                    if(_self.pageType === '1'){
                        if(!isPC){
                            var orderInfo = {//二手微信二维码参数
                                    pageType:1,
                                    productId:_self.productID,
                                    payAmount:_self.payAmount
                            };
                            _self.payInfo.PAY_MOBILE_URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxea43a0f9ebce9e66&redirect_uri=https://www.caimei365.com/pay/wechatpay.html&response_type=code&scope=snsapi_base&state="+JSON.stringify(orderInfo)+"#wechat_redirect";
                            location.href = _self.payInfo.PAY_MOBILE_URL;
                        }else{
                            _self.payInfo.PAY_DATA = {//二手
                                type:_self.payInfo.PAY_BANK_NUM,
                                productId:_self.productID,
                                amount:_self.payAmount,
                                url:_self.payInfo.PAY_MOBILE_URL
                            };
                            CAIMEI.Storage.setItem('PAY_DATA',JSON.stringify(_self.payInfo.PAY_DATA));
                            window.open("/pay/caimei-paymobile.html?pageType=1");
                            _self.isPayAlert = true;
                        }
                    }else{
                        if(!isPC){
                            var orderInfo = {//普通订单微信二维码参数
                                    pageType:0,
                                    orderID:_self.payInfo.PAY_ORDERID,
                                    payAmount:_self.payAmount
                            };
                            console.log(orderInfo)
                            _self.payInfo.PAY_MOBILE_URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxea43a0f9ebce9e66&redirect_uri=https://www.caimei365.com/pay/wechatpay.html&response_type=code&scope=snsapi_base&state="+JSON.stringify(orderInfo)+"#wechat_redirect";
                            location.href = _self.payInfo.PAY_MOBILE_URL;
                        }else{
                            _self.payInfo.PAY_DATA = {//正常订单
                                type:_self.payInfo.PAY_BANK_NUM,
                                orderid:_self.payInfo.PAY_ORDERID,
                                amount:_self.payAmount,
                                url:_self.payInfo.PAY_MOBILE_URL
                            };
                            CAIMEI.Storage.setItem('PAY_DATA',JSON.stringify(_self.payInfo.PAY_DATA));
                            window.open("/pay/caimei-paymobile.html?pageType=1");
                            _self.isPayAlert = true;
                        }
                    }
                }else{
                    if(_self.pageType === '1'){
                        var params = {//二手
                            payWay:_self.payInfo.PAY_BANK_NUM,
                            returnUrl:'https://www.caimei365.com/',
                            productId:_self.productID,
                        };
                        _self.PayOrdersecondHandPay(params,_self.payInfo.PAY_BANK_NUM);
                    }else{
                        var params = {//正常订单
                                payWay:_self.payInfo.PAY_BANK_NUM,
                                payAmount:parseInt(_self.payAmount*100),
                                returnUrl:'https://www.caimei365.com/',
                                orderId:_self.payInfo.PAY_ORDERID
                        };
                        _self.PayOrderPcMallPay(params,_self.payInfo.PAY_BANK_NUM);
                    }
                }
            }
        },
        PaySubmitFn:function(){//点击网银支付方式
            var _self = this;
            if(_self.invoiceStatus){
                _self.layerConfirm();
            }else{
                if(_self.payInfo.PAY_BANK_NUM == ''){
                    CAIMEI.dialog('请选择银行！');
                    return;
                }
                if(_self.payAmount <= 10){
                    CAIMEI.dialog('企业网银支付的金额必须大于￥10.00');
                    return;
                }
                if(_self.pageType === '1'){
                    var params = {//二手
                            payWay:'UNIONPAY',
                            payAmount: parseInt(_self.payAmount*100),
                            bankCode:_self.payInfo.PAY_BANK_NUM,
                            returnUrl:'https://www.caimei365.com/',
                            productId:_self.productID,
                    };
                    _self.PayOrdersecondHandPay(params,_self.payInfo.PAY_BANK_NUM);
                }else{
                    var params = {//正常订单
                            payWay:'UNIONPAY',
                            payAmount: parseInt(_self.payAmount*100),
                            bankCode:_self.payInfo.PAY_BANK_NUM,
                            returnUrl:'https://www.caimei365.com/',
                            orderId:_self.payInfo.PAY_ORDERID
                    };
                    _self.PayOrderPcMallPay(params,_self.payInfo.PAY_BANK_NUM);
                }
            }
        },
        PayOrderPcMallPay:function(params,type){//网银&&支付宝生成支付地址
            var _self = this;
            _self.isSubMitStatus=true;
            PayApi.PayOrderPcMallPay(params,function(response){
                if(response.code == 0){
                    _self.isPayAlert = true;
                    _self.isSubMitStatus=false;
                    _self.mbOrderId = response.data.data.mbOrderId;
                    if(type == 'ALIPAY'){
                        _self.payInfo.PAY_MOBILE_URL = response.data.data.payUrl;
                        _self.payInfo.PAY_DATA = {
                            mbOrderId:_self.mbOrderId,
                            type:_self.payInfo.PAY_BANK_NUM,
                            orderid:_self.payInfo.PAY_ORDERID,
                            amount:_self.payAmount,
                            url:_self.payInfo.PAY_MOBILE_URL
                        };
                        CAIMEI.Storage.setItem('PAY_DATA',JSON.stringify(_self.payInfo.PAY_DATA));
                        if(!isPC){
                            location.href = _self.payInfo.PAY_MOBILE_URL;
                        }else{
                            window.open("/pay/caimei-paymobile.html?pageType=1");
                        }
                    }else{
                        window.open(response.data.data.payUrl);
                    }
                }else{
                    _self.isSubMitStatus=false;
                    CAIMEI.Alert(response.msg,'确定',false);
                }
            })
        },
        PayOrdersecondHandPay:function(params,type){//二手支付请求
            var _self = this;
            _self.isSubMitStatus=true;
            PayApi.PayOrdersecondHandPay(params,function(response){
                if(response.code == 0){
                    _self.isPayAlert = true;
                    _self.isSubMitStatus=false;
                    _self.mbOrderId = response.data.data.mbOrderId;
                    if(type == 'ALIPAY'){
                        _self.payInfo.PAY_MOBILE_URL = response.data.data.payUrl;
                        if(_self.pageType === '1'){
                            _self.payInfo.PAY_DATA = {
                                mbOrderId:_self.mbOrderId,
                                type:_self.payInfo.PAY_BANK_NUM,
                                productId:_self.productID,
                                amount:_self.payAmount,
                                url:_self.payInfo.PAY_MOBILE_URL
                            };
                            CAIMEI.Storage.setItem('PAY_DATA',JSON.stringify(_self.payInfo.PAY_DATA));
                            window.open("/pay/caimei-paymobile.html?pageType=1");
                        }else{
                            _self.payInfo.PAY_DATA = {
                                mbOrderId:_self.mbOrderId,
                                type:_self.payInfo.PAY_BANK_NUM,
                                orderid:_self.payInfo.PAY_ORDERID,
                                amount:_self.payAmount,
                                url:_self.payInfo.PAY_MOBILE_URL
                            };
                            CAIMEI.Storage.setItem('PAY_DATA',JSON.stringify(_self.payInfo.PAY_DATA));
                            window.open("/pay/caimei-paymobile.html");
                        }
                    }else{
                        window.open(response.data.data.payUrl);
                    }
                }else{
                    CAIMEI.Alert(response.msg,'确定',false);
                    _self.isSubMitStatus=false;
                }
            })
        },
        changePayAmount:function(event){//输入支付金额控制
            var _self = this;
            var value = event.target.value;
            if(value == "" || value <0 ){//判断是否等于0 或者为空
                _self.payAmount = '';
                _self.payInfo.PAY_PAYAMOUNT = _self.payInfo.PAY_UNPAIDAMOUNT;
                _self.balanceAmount = _self.toFixedFn(_self.payInfo.PAY_UNPAIDAMOUNT);
                return;
            }else if(Number(value) > _self.payInfo.PAY_UNPAIDAMOUNT){//判断大于应付金额
                _self.payAmount = _self.payInfo.PAY_UNPAIDAMOUNT;
                _self.payInfo.PAY_PAYAMOUNT =  _self.payAmount;
                _self.balanceAmount = _self.toFixedFn(_self.payInfo.PAY_UNPAIDAMOUNT-_self.payInfo.PAY_PAYAMOUNT);
            }else{
                _self.payAmount = value;
                _self.payInfo.PAY_PAYAMOUNT = _self.payAmount;
                _self.balanceAmount = _self.toFixedFn(_self.payInfo.PAY_UNPAIDAMOUNT-_self.payInfo.PAY_PAYAMOUNT);
            }
        },
        changePayAmountBlur:function(event){//失去焦点设置金额
            var _self = this;
            _self.payAmount = _self.toFixedFn(event.target.value);
            _self.payInfo.PAY_PAYAMOUNT = _self.payAmount;
        },
        changeTab:function(index,item){//选择支付方式切换
            this.tabIndex = index;
            switch (this.tabIndex) {
                case 0:
                    this.payInfo.PAY_BANK_NUM = 'ALIPAY';
                    break;
                case 1:
                    this.payInfo.PAY_BANK_NUM = '';
                    break;
            }
        },
        checkMobilePay:function(index,bankNum){//选择移动支付方式
            this.mobileTabIndex = index;
            this.payInfo.PAY_BANK_NUM = bankNum;
            if( this.mobileTabIndex==2){

            }
        },
        checkBankPay:function(index,item){//选择网银支付方式-选择银行
            this.bankTabIndex = index;
            this.payInfo.PAY_BANK_NUM = item.bankNum;
        },
        copyLinkPaySubmitFn:function(){//复制网银支付链接
            var _self = this;
            if(_self.invoiceStatus){
                _self.layerConfirm();
            }else{
                if(_self.payAmount == ''){
                    CAIMEI.dialog('请输入本次支付金额');
                    return;
                }
                if(_self.payAmount == 0){
                    CAIMEI.dialog('本次支付金额不能为0');
                    return;
                }
                if(_self.payAmount <= 10){
                    CAIMEI.dialog('企业网银支付的金额必须大于￥10.00');
                    return;
                }
                PayApi.PayOrderPayLink({unpaidAmount:_self.payAmount,orderId:_self.payInfo.PAY_ORDERID},function(response){
                    _self.bankPayLink_url = response.data;
                    var oInput = document.createElement("textarea");
                    oInput.value = _self.bankPayLink_url;
                    document.body.appendChild(oInput);
                    oInput.select(); // 选择对象
                    document.execCommand("Copy"); // 执行浏览器复制命令
                    document.body.removeChild(oInput);
                    CAIMEI.dialog('复制成功');
                })
            }
        },
        copyOrderBtnSubmitFn:function(){//复制订单标识
            var _self = this;
            var oInput = document.createElement("textarea");
            oInput.value = _self.orderIdentificationId;
            document.body.appendChild(oInput);
            oInput.select(); // 选择对象
            document.execCommand("Copy"); // 执行浏览器复制命令
            document.body.removeChild(oInput);
            CAIMEI.dialog('复制成功');
        },
        hidePayAlert:function(){//隐藏已支付弹窗
            var _self = this;
            _self.isPayAlert = false;
        },
        RefreshBody:function(){//刷新页面
            var _self = this;
            if(_self.payInfo.PAY_BANK_NUM == 'WEIXIN'){
                PayApi.PayOrderPayWhetherSuccess({orderId: _self.payInfo.PAY_ORDERID, paySuccessCounter:_self.paySuccessCounter},function(response){
                    _self.isPayAlert = false;
                    if(response.code === 0){
                        _self.windowLocationHref('success');
                    }else{
                        _self.windowLocationHref('error');
                    }
                });
            }else{
                PayApi.PayOrderFindOrderStatus({mbOrderId:_self.mbOrderId},function(response){
                    _self.isPayAlert = false;
                    var data = response.data.data;
                    if(data.status === '1'){
                        _self.windowLocationHref('success');
                    }else{
                        _self.windowLocationHref('error');
                    }
                });
            }
        },
        windowLocationHref:function(state){
            var _self = this;
            if( _self.pageType === '1'){
                window.location.href = '/pay/success.html?pageType=second&type='+state+'&payAmount='+_self.payAmount;
            }else{
                window.location.href = '/pay/success.html?pageType=www&type='+state+'&payAmount='+_self.payAmount;
            }
        },
        payTypeText:function(state){//处理支付记录文字
            var stateText = '',
                stateTextObject={
                    12:'企业网银',
                    13:'微信支付',
                    14:'支付宝',
                    15:'微信支付',
                    16:'余额抵扣',
                };
            Object.keys(stateTextObject).forEach(function(key) {
                if(key == state){
                    stateText = stateTextObject[key]
                }
            });
            return stateText;
        },
        toFixedFn:function(text){//处理小数点后两位数
            return Number(text).toFixed(2);
        },
        layerConfirm:function(){
            var _self = this;
            CAIMEI.Alert('本次交易暂不支持线上支付开票,请使用线下转账的方式付款','知道了',true,function () {
                _self.payStatusText = '使用微信和企业网银支付全部金额后，供应商会在24小时后发货（周末、节假日顺延）。若着急发货，可以选择使用线下转账进行付款。';
                _self.isReceiptStatus = true;
            });
        }
    },
    mounted: function () {
        var _self = this;
        _self.pageType = CAIMEI.getUrlParam('pageType');
        if( _self.pageType === '1'){//二手
            _self.productID = CAIMEI.getUrlParam('productID');
            _self.payAmount = _self.toFixedFn(100);
            _self.isRequest = true;
            _self.payStatusText = '';
        }else{
             var HrefType = CAIMEI.getUrlParam('type');
            if(HrefType == 'payfirm'){
                _self.payInfo.PAY_ORDERID =  CAIMEI.getUrlParam('orderID');
                _self.orderIdentificationId = '#'+_self.payInfo.PAY_ORDERID+'#';
            }else{
                var data =JSON.parse(localStorage.getItem("confirmOrderInfo"));
                _self.payInfo.PAY_ORDERID = data.data.orderID;
                _self.orderIdentificationId = '#'+_self.payInfo.PAY_ORDERID+'#';
            }
            _self.infoPayOrderCheckoutCounter();//正常订单初始化
        }
        var viewer = window.navigator.userAgent.toLowerCase();
        if(viewer.match(/MicroMessenger/i) == 'micromessenger'){
            _self.is_Wechat_bowcr = true;
            _self.payInfo.PAY_BANK_NUM = 'WEIXIN';
            _self.mobileTabIndex = 1;
        }else{
            _self.is_Wechat_bowcr = false;
            _self.payInfo.PAY_BANK_NUM = 'ALIPAY';
            _self.mobileTabIndex = 0;
        }

    }
});
