import React, { Component } from 'react'
import './index.scss'
import { getParam, http, browser } from "@/utils";
import { Toast } from 'antd-mobile';
import { Link, withRouter } from "react-router-dom";
import { compose } from "redux";
import { connect } from "react-redux";
import { differenceInHours, differenceInMinutes, differenceInSeconds } from "date-fns";


class Single extends Component {
    constructor(props) {
        super(props)
        this.state = {
            // status: 1,
            orderId: '',
            nowPrice: '',
            laterPrice: '',
            hour: '',
            min: '',
            sec: '',
            endTime: '',
            groupOrderId: '',
            payType: '0',  // 1支付宝 0微信
            // singleBox: false,
            showSingleBox: false,
        }
    }

    componentDidMount() {
        // if (getParam('is_class') === 1 || getParam('weixinpay')) {
        //     console.log(0);
        //     this.payCallback()
        // }
        // if (browser.isWeixin) {
        //     this.isweixinPay()
        // }
    }

    componentWillReceiveProps(nextProps, nextContext) {
        // console.log(nextProps);
        // this.setState({
        //     singleBox: nextProps.singleBox
        // })
    }

    // 选择支付方式
    check = (type) => {
        this.setState({
            payType: type
        })
    }

    // 确定购买
    toBuy = () => {
        const { courseId } = this.props;
        const videoID = this.props.data.video_id || this.props.data.id;
        http.get(`${API.home}/sys/createClassOrder/${videoID}`).then((res) => {
            if (res.data.code === 200) {
                this.setState({
                    orderId: res.data.data.order_id
                })
                this.state.payType === '1' ? this.alipayPay(res.data.data.order_id, courseId) : this.weixinPay(res.data.data.order_id)
            } else {
                Toast.info(res.data.msg, 2)
            }
        })
    }
    // 微信支付
    weixinPay = (orderId) => {
        // 微信内部-支付
        if (browser.isWeixin) {
            window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx23dac6775ac82877&redirect_uri=" + encodeURIComponent(window.location.href + "&aa=bb&oid=" + orderId).toLowerCase() + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        } else {
            // 微信外部-支付
            http.get(`${API['base-api']}/pay/wxpay/wap_charge/oid/${orderId}`).then((res) => {
                if (res.data.errno === 0) {
                    window.location.href = res.data.data.url + "&redirect_url=" + encodeURIComponent(window.location.href + "&weixinpay=1&oid=" + orderId).toLowerCase();
                } else {
                    Toast.info(res.data.msg, 2)
                }
            })
        }
    }
    // 支付宝支付
    alipayPay = (orderId, courseId) => {
        http.get(`${API['base-api']}/pay/alipay/wap_charge_new/oid/${orderId}`).then((res) => {
            if (res.data.errno === 0) {
                window.location = res.data.data.url;
                courseId && window.localStorage.setItem('payCourse', courseId);
            } else {
                Toast.info(res.data.msg, 2)
            }
        })
    }

    // 微信内部支付
    isweixinPay = () => {
        let _this = this;
        let weixin_code = getParam('code')
        if (weixin_code) {
            if (!getParam('oid')) {
                return
            } else {
                http.get(`${API['base-api']}/pay/wxpay/pub_charge/oid/${getParam('oid')}/code/${weixin_code}`).then((res) => {
                    if (res.data.errno === 0) {
                        const data = res.data.data;

                        function onBridgeReady() {
                            WeixinJSBridge.invoke(
                                'getBrandWCPayRequest', {
                                    "appId": data.appId,                //公众号名称，由商户传入
                                    "timeStamp": data.timeStamp,        //时间戳，自1970年以来的秒数
                                    "nonceStr": data.nonceStr,          //随机串
                                    "package": data.package,
                                    "signType": data.signType,          //微信签名方式：
                                    "paySign": data.paySign             //微信签名
                                },
                                function (res) {
                                    if (res.err_msg == "get_brand_wcpay_request:ok") {
                                        Toast.info('支付成功', 2);
                                        _this.intervalPayStatus = setInterval(function () {
                                            http.get(`${API['base-api']}/m/orderState/oid/${getParam('oid')}`).then(res => {
                                                if (res.data.errno === 401) {
                                                    clearInterval(_this.intervalPayStatus);
                                                    _this.intervalPayStatus = null;
                                                    // 获取课程类型
                                                    http.get(`${API['base-api']}/class_order_status/${getParam('oid')}`).then((res) => {
                                                        if (Number(res.data.data.errno) === 200) {
                                                            // 正常购买单集成功
                                                            this.setState({
                                                                status: 6,
                                                                showSingleBox: true,
                                                            })
                                                        } else if (Number(res.data.data.errno) === 201) {
                                                            // 0元参团
                                                            this.setState({
                                                                status: 4,
                                                                showSingleBox: true,
                                                            })
                                                        } else if (Number(res.data.data.errno) === 202) {
                                                            // 0元购
                                                            this.setState({
                                                                status: 3,
                                                                showSingleBox: true,
                                                            })
                                                        } else if (Number(res.data.data.errno) === 203) {
                                                            // 三天内特价
                                                            this.setState({
                                                                nowPrice: res.data.data.data.now_price,
                                                                laterPrice: res.data.data.data.three_day_later_price,
                                                                status: 2,
                                                                showSingleBox: true,
                                                            })
                                                        } else {
                                                            Toast.info(res.data.data.msg, 2)
                                                        }
                                                    })
                                                }
                                            })
                                        }, 1000)
                                    } else {
                                        alert('支付失败')
                                    }
                                }
                            )
                        }

                        if (typeof WeixinJSBridge == "undefined") {
                            if (document.addEventListener) {
                                document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false)
                            } else if (document.attachEvent) {
                                document.attachEvent('WeixinJSBridgeReady', onBridgeReady)
                                document.attachEvent('onWeixinJSBridgeReady', onBridgeReady)
                            }
                        } else {
                            onBridgeReady()
                        }
                    } else {
                        Toast.info(res.data.msg, 2)
                    }
                })
            }
        }
    }

    // 支付完成之后获取状态
    payCallback = () => {
        const _this = this;
        if (!getParam('oid')) {
            return;
        } else {
            _this.intervalPayStatus = setInterval(function () {
                http.get(`${API['base-api']}/m/orderState/oid/${getParam('oid')}`).then(res => {
                    if (res.data.errno === 401) {
                        clearInterval(_this.intervalPayStatus);
                        _this.intervalPayStatus = null;
                        // 获取课程类型
                        http.get(`${API['base-api']}/class_order_status/${getParam('oid')}`).then((res) => {
                            if (Number(res.data.data.errno) === 200) {
                                // 正常购买单集成功
                                this.setState({
                                    status: 6,
                                    showSingleBox: true,
                                })
                            } else if (Number(res.data.data.errno) === 201) {
                                // 0元参团
                                this.setState({
                                    status: 4,
                                    showSingleBox: true,
                                })
                            } else if (Number(res.data.data.errno) === 202) {
                                // 0元购
                                this.setState({
                                    status: 3,
                                    showSingleBox: true,
                                })
                            } else if (Number(res.data.data.errno) === 203) {
                                // 三天内特价
                                this.setState({
                                    nowPrice: res.data.data.data.now_price,
                                    laterPrice: res.data.data.data.three_day_later_price,
                                    status: 2,
                                    showSingleBox: true,
                                })
                            } else {
                                Toast.info(res.data.data.msg, 2)
                            }
                        })
                    }
                })
            }, 1000)
        }

    }


    // 特价购买全集
    toBuyAll = () => {

    }
    // 0元购买全集
    zerobuyReceive = () => {
        Toast.success('购买全集成功', 3)
        this.colse()
    }
    // 0元参团
    zerogroupBuy = () => {
        this.getOrderId()
    }

    // 获取订单号-0元参团
    getOrderId = () => {
        let data = {
            course_id: getParam('id')
        }
        http.post(`${API['base-api']}/pdd/sys`, data).then((res) => {
            if (res.data.errno === 0) {
                this.setState({
                    groupOrderId: res.data.data.order_id
                })
                this.getOrderStatus(res.data.data.order_id)
            } else {
                Toast.info(res.data.msg, 2)
            }
        })
    }

    // 获取订单状态-0元参团
    getOrderStatus = (id) => {
        http.get(`${API.home}/m/pdd/order_status/${id}`).then((res) => {
            if (res.data.code === 200) {
                this.getTime(res.data.data.pdd_order_id)
            } else {
                Toast.info(res.data.msg, 2)
            }
        })
    }
    // 获取倒计时-0元参团
    getTime = (id) => {
        http.get(`${API.home}/m/pdd_order_end_time/${id}`).then((res) => {
            if (res.data.code === 200) {
                this.setState({
                    endTime: res.data.data.end_time,
                    status: 7
                })
            } else {
                Toast.info(res.data.msg, 2)
            }
        })
    }

    // 邀请好友参团
    toGroup = () => {
        this.props.history.push(`/togroup?id=${this.state.groupOrderId}`)
    }

    // 关闭弹窗
    colse = () => {
        this.props.boxHide(false);
        this.setState({
            status: 1
        })
    }

    render() {
        const {showSingleBox} = this.state;
        if (this.state.endTime) {
            let date = this.state.endTime * 1000
            let now = Date.now()
            setInterval(() => {
                date -= 1000
                let s = differenceInSeconds(new Date(date), now) % 60,
                    m = differenceInMinutes(new Date(date), now) % 60,
                    h = differenceInHours(new Date(date), now) % 24
                this.setState({
                    hour: h,
                    min: m,
                    sec: s,
                })
            }, 1000)
        }
        const {singleType} = this.props;
        return (
            singleType === 1 &&
            <div>
                <div className='popup-box'>
                    <div className='content singleset-payment'>
                        <div className='price-box'>
                            <span>实付款：</span>
                            <p>{this.props.data.class_price}元</p>
                        </div>
                        <div className='course-info'>
                            <p className='text-overflow-1'><span>课程：</span>
                                {this.props.title}
                            </p>
                            <p className='text-overflow-1'><span>课时：</span>
                                {this.props.data.name}
                            </p>
                        </div>
                        <div className='payment-type'>
                            <label>支付方式：</label>
                            {
                                !browser.isWeixin &&
                                <p onClick={this.check.bind(this, '1')}>
                                    <i className='iconfont iconalipay'></i>
                                    <span>支付宝</span>
                                    <i className={`iconfont icondanseshixintubiao-5 redio ${this.state.payType === '1' ? 'redioed' : ''}`}></i>
                                </p>
                            }

                            <p onClick={this.check.bind(this, '0')}>
                                <i className='iconfont iconweixinzhifu buy'></i>
                                <span>微信支付</span>
                                <i className={`iconfont icondanseshixintubiao-5 redio ${this.state.payType === '0' ? 'redioed' : ''}`}></i>
                            </p>
                        </div>
                        <div className='btn btn-18B4ED' onClick={this.toBuy}>确认购买</div>
                    </div>
                    <i onClick={this.colse} className={'iconfont iconiconfront-2 close'}></i>
                </div>

            </div>

        );
    }

}

export default compose(
    connect(
        state => ({user: state.user}),
        null
    ),
    withRouter
)(Single)
