import {Component, Vue} from 'vue-property-decorator';
import Http from '../../extend/Http';
import Utils from '../../extend/Utils';
import wx from 'weixin-jsapi';
import router from '@/router';
import {MessageBox} from 'element-ui';
// import 'vue-router/types/vue';

@Component({
    components: {}
})

export default class UserIndex extends Vue {

    public data: any = {
        hour: 0,
        minute: 0,
        second: 0,
        orderSn: '0',
        totalCharge: '0',
        payment: 'weixin',
        model: false,
        html:'',
        zhifupay:true,
        isShowA:true,
        isShowB: false,
        isShowC: true,
        recharfe: true
    };
    private closeTime: string = '0';
    private timer: number = 0;

    async created() {
        let url = Utils.getInstance().getParams(location.href);
        console.log(url)
        if(url.tip == 'yes'){
            this.data.model = true;
        }else{
            this.data.model = false;
        }
        let isWeiXin = () => { return navigator.userAgent.toLowerCase().indexOf('micromessenger') !== -1 }
        if (isWeiXin()) {
              this.data.zhifupay = false
        }
    }

    mounted() {
        if( this.$route.params.type == '1'){
            let info = JSON.parse(localStorage.getItem('order_paying') as string);
            // this.closeTime = info.close_timestamp;
            this.data.totalCharge = info.total_charge;
            this.data.orderSn = info.order_sn;
        }else{
            let info = JSON.parse(localStorage.getItem('order_payings') as string);
            // this.closeTime = info.close_timestamp;
            this.data.totalCharge = info.total_charge;
            this.data.orderSn = info.order_sn;
        }
        if (this.$route.params.recharfe) {
            this.data.recharfe = false
        }
    }
    hideModel() {
        this.data.model = false;
        router.replace({
            name: 'olist'
        });
    }
    open() {
        // @ts-ignore
        MessageBox.alert('<a href="tel:' + Http.PHONE + '">' + Http.PHONE + '</a>', '请联系客服', {
            dangerouslyUseHTMLString: true,
            confirmButtonText: "拨打" ,
            beforeClose: (action, instance, done) => {
                window.location.href = 'tel://' +Http.PHONE;
                done()
            }
        }).then(action =>{

        });
    }
    weixin(){
            this.data.isShowA = !this.data.isShowA;
            this.data.isShowB = false
    }
    zhifubao(){
            this.data.isShowB = !this.data.isShowB;
             this.data.isShowA = false
    }
    gzhweixin(){
        this.data.isShowC = true
    }
    zongpay(){
        let isWeiXin = () => { return navigator.userAgent.toLowerCase().indexOf('micromessenger') !== -1 }
        if (isWeiXin()) {
            this.weixinpayment()
        }else {
            if( this.data.isShowA == true ){
                this.payment();

            }
            if(this.data.isShowB == true){
                this.alipayment();
            }
        }

    }
    async payment() {
        // let res = await Http.getInstance().payOrder({
        //     order_sn: this.data.orderSn, platform: platform, remark: '订单支付'
        // });
        // let res = await Http.getInstance().getWeixin({
        //     order_sn: this.data.orderSn,
        //     platform: 'weixin',
        //     pay:'wappay'
        // });
        let res = await Http.getInstance().getWeixin({
            order_sn: this.data.orderSn,
            platform: 'weixin',
            pay:'wappay'
        });
        console.log(res)

        window.location.replace(
            res.data.mweb_url+'&redirect_url='+encodeURIComponent(window.location.href+'?tip=yes'))

        // console.log(this.data.orderSn)
        //  this.data.model = true;
        // this.data.payment = platform;
        // switch (platform) {
        //     case 'weixin':
        //         // this.wxpay(res.data);
        //         this.data.payment = 'weixin';
        //         break;
        //     case 'alipay':
        //         // this.alipay(res.data);
        //         break;
        //     case 'union':
        //         // this.unionpay(res.data);
        //         break;
        // }
    }
    async alipayment() {

        let res = await Http.getInstance().getAlipay({
            order_sn: this.data.orderSn,
            platform: 'alipay',
            pay:'wappay'
        });
        console.log(res.data)
        this.data.model = true;
        this.data.html = res.data
        let form= res.data;
        const div = document.createElement('div')
        div.innerHTML = form//此处form就是后台返回接收到的数据
        document.body.appendChild(div)
        document.forms[0].submit()
    }

    async weixinpayment() {
        let openid = localStorage.getItem('openid');
        let res
        if (this.data.recharfe) {
            res = await Http.getInstance().getWeixin({
                order_sn: this.data.orderSn, platform: 'weixin', pay: 'wxpay', openid: openid
            });
        } else {
            res = await Http.getInstance().RechargeOrderPay({
                order_sn: this.data.orderSn, openid: openid
            });
        }
        res.data.jsApiList = ['chooseWXPay'];
        console.log(res.data)
        //wx.config(res.data);
        wx.config({
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            appId: res.data.appId, // 必填，公众号的唯一标识
            timestamp: res.data.timeStamp, // 必填，生成签名的时间戳
            nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
            signature: res.data.paySign,// 必填，签名，见附录1   https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115
            jsApiList: ['chooseWXPay']//['chooseWXPay'] // getBrandWCPayquest 必填，需要使用的JS接口列表，这里只写支付的
        });
        wx.ready(() => {
            wx.chooseWXPay({
                timestamp: res.data.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                nonceStr: res.data.nonceStr, // 支付签名随机串，不长于 32 位
                package: res.data.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
                signType: res.data.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                paySign: res.data.paySign, // 支付签名
                success: (r) => {
                    alert('支付成功');
                    if (r.errMsg == "chooseWXPay:ok") {
                        alert('支付成功');
                        if (this.data.recharfe) {
                            router.replace('/order/list');
                        } else {
                            router.replace('/recharge/list');  
                        }
                    } else {
                        alert('支付失败')
                        if (this.data.recharfe) {
                            router.replace('/order/list');
                        } else {
                            router.replace('/recharge/list');  
                        }
                    }
                },
                cancel: (r) => {
                    //支付取消
                    alert('支付取消')
                    if (this.data.recharfe) {
                        router.replace('/order/list');
                    } else {
                        router.replace('/recharge/list');  
                    }
                },
                fail: (res) => {
                    alert('支付失败');
                    if (this.data.recharfe) {
                        router.replace('/order/list');
                    } else {
                        router.replace('/recharge/list');  
                    }
                }
            });
        });
    }


    private countTime(datetime: any): any {
        this.timer = setInterval(() => {
            // 获取当前时间
            let now = new Date().getTime();
            // 设置截止时间
            let end = new Date(datetime).getTime();
            // 时间差
            let left = end - now;
            if (left > 0) {
                this.data.hour = Utils.getInstance().prefixInteger(Math.floor(left / 3600000));
                this.data.minute = Utils.getInstance().prefixInteger(Math.floor((left / 60000) % 60));
                this.data.second = Utils.getInstance().prefixInteger(Math.floor((left / 1000) % 60));
            } else {
                clearInterval(this.timer);
                router.replace({
                    name: 'olist',
                });
            }
        }, 1000);
    }

   async wxpay(data: any) {
        // let info = JSON.parse(localStorage.getItem('order_paying') || '');
        // console.log('info');
        // let resss = await Http.getInstance().getConfig({
        //     platform: 'weixin',
        //     order_sn: info.order_sn,
        //     url: location.href.slice(0, -7)
        // });
        // console.log(resss)
        let openid = localStorage.getItem('openid');
        let res = await Http.getInstance().getWeixin({
                    order_sn: this.data.orderSn,
                    platform: 'weixin',
                    pay:'wxpay',
                    openid:openid
                });
        res.data.jsApiList = ['chooseWXPay'];
        wx.config(res.data);
        wx.ready(() => {
            wx.chooseWXPay({
                timestamp: res.data.timestamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                nonceStr: res.data.nonceStr, // 支付签名随机串，不长于 32 位
                package: res.data.prepay_id, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
                signType: res.data.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                paySign: res.data.paySign, // 支付签名
                success: (res: any) => {
                    alert(res);
                    if (res) {
                        // localStorage.removeItem('order_paying');
                        // router.replace('orderList');
                    } else {
                    }
                }
            });
        });
        wx.error((err: any) => {
            alert(JSON.stringify(err));
        });
    }

    private alipay(data: any) {

    }

    private unionpay(data: any) {

    }
}
