import React, { Component } from 'react'
import { getParam, http } from "@/utils"
import { Toast } from 'antd-mobile'
import { Link } from 'react-router-dom'
import { getCourses } from "@/components/detail/actions"
import { connect } from "react-redux"
import './index.scss'
import Overlay from '../overlay'
import axios from "axios";


class BtnStatus extends Component {
    constructor(props) {
        super(props)
        this.state = {
            isbuy: 1,
            is_baoming: 0,
            group_status: 3,
            in_cart: false,
            countdown: 0,
            barInfo: ''
        }

    }

    componentDidMount() {
        // this.getBargainInfo()
        this.group = false;
    }


    // componentDidUpdate(prevProps) {
    //     let {courseInfo} = this.props
    //     let {courseInfo: prevCourseInfo} = prevProps
    //     if (courseInfo && courseInfo.is_bargain) {
    //         if (prevCourseInfo && courseInfo.is_bargain !== prevCourseInfo.is_bargain) {
    //             this.getBargainInfo()
    //         }
    //     }
    // }

    componentWillReceiveProps(nextProps) {
        if(nextProps.data && nextProps.data.is_bargain) {
            this.getBargainInfo()
        }
        this.setState({
            ...nextProps.data.course_info,
            countdown: nextProps.countdown,
        });
    }

    // 加入购物车 type:1 加入购物车,2加入购物车并跳转到购物车页面去支付
    toCart = (type) => {
        let data = {
            course_id: getParam('id')
        };
        http.post(`${API.home}/m/cart/add`, data).then((res) => {
            if (res.data.code === 200) {
                if (type === 1) {
                    Toast.info('已加入购物车', 2)
                    // this.props.getCourses()
                    document.location.reload()
                } else {
                    this.props.history.replace('/shopcart');

                }

            } else if (res.data.code === 15001) {
                this.props.history.replace('/shopcart');
            } else {
                Toast.info(res.data.msg, 2);
            }
        })
    };
    // 返现课程的立即购买
    signUpNow = () => {
        if(this.props.user.hasError) {
            // 未登录 去登陆
            this.props.history.push('/passport');
        }else{
            let cidArr = JSON.stringify([Number(getParam('id'))]);
            http.get(`${API['base-api']}/m/cart/addtopreorder/${cidArr}?type=1`).then((res) => {
                if (res.data.errno === 0) {
                    this.props.history.push("/order?id=" + res.data.data[0], {type: 1});
                } else {
                    Toast.info(res.data.msg, 2);
                }
            })
        }
    };
    // 普通课程的立即报名 要模拟结算过程
    simpleCourse = () => {
        if(this.props.user.hasError) {
            // 未登录 去登陆
            this.props.history.push('/passport');
        }else{
            http.get(`${API['base-api']}/m/cart/addtopreorder/[${getParam('id')}]`).then((res) => {
                if (res.data.errno === 0) {
                    this.props.history.push(`/order?id=${getParam('id')}`, {simple: 1})
                } else {
                    Toast.info(res.data.msg, 2);
                }
            })
        }
    };
    // 格式化开课时间
    formatDate = (date) => {
        let ary = date.split('-');
        return `${ary[1]}月${ary[2]}日开课`;
    };
    // 直接购买
    tobuy = () => {
        const {user} = this.props
        const uid = user && user.data && user.data.uid
        if (!uid) {
            this.props.history.push('/passport/login')
        } else {
            if (this.state.barInfo.bargain_status === 2) {
                // this.toCart(2)
                // 新需求 不需要加入购物车 直接走普通课程的立即报名流程 跳到订单页
                this.simpleCourse();
            } else {
                // 取消砍价记录
                this.setState({
                    isShowOverlay: true,
                    bargainStatus: 1,
                })
            }
        }
    };
    // 一键开团
    keyToGroup = () => {
        if(this.props.user.hasError) {
            // 未登录 去登陆
            this.props.history.push('/passport');
            return;
        }
        this.props.history.push(`/order?id=${getParam('id')}`, {group: 1})
    };
    // 砍完价去支付
    bargainToOrder = () => {
        if(this.props.user.hasError) {
            // 未登录 去登陆
            this.props.history.push('/passport');
        }else{
            http.get(`${API['base-api']}/m/cart/addtopreorder/[${getParam('id')}]`).then((res) => {
                if (res.data.errno === 0) {
                    this.props.history.push(`/order?id=[${getParam('id')}]`, {bargain: 1});
                } else {
                    Toast.info(res.data.msg, 2);
                }
            })
        }
    };

    // 取消砍价
    cancel = () => {
        let data = {
            courseId: getParam('id')
        }
        http.post(`${API.home}/m/bargain/cancel`, data).then((res) => {
            if (res.data.code === 200) {
                this.setState({
                    isShowOverlay: false,
                    bargainStatus: '',
                })
                // window.location.href = '/shopcart'
                this.props.history.push(`/order?id=[${getParam('id')}]`, {simple: 1})
            } else {
                Toast.info(res.data.msg, 2)
            }
        })
    }
    close = () => {
        this.setState({
            isShowOverlay: false,
            bargainStatus: '',
        })
    }
    // 砍价接口
    toKanjia = () => {
        const {user} = this.props
        const uid = user && user.data && user.data.uid
        if (!uid) {
            this.props.history.push('/passport/login')
        } else {
            let data = {
                course_id: getParam('id'),
                type: 1,  // 1 用户自己砍价 2 使用砍价神器 3 好友助力砍价 4 好友第二次助力
                parent_uid: 0 // 被助力人id 【自己本人操作传0】
            }
            http.post(`${API.home}/m/bargain/toBargain`, data).then((res) => {
                if (res.data.code === 200) {
                    // this.props.getBargainInfo()
                    document.location.reload()
                } else {
                    Toast.info(res.data.msg, 2)
                }
            })
        }
    }


    //获取砍价信息
    getBargainInfo = () => {
        const {user} = this.props
        const uid = user && user.data && user.data.uid
        let data = {
            courseId: getParam('id')
        }
        http.post(`${API.home}/m/bargain/courseDetail`, data).then((res) => {
            if (res.data.code === 200) {
                this.setState({
                    barInfo: res.data.data
                })
            } else {
                Toast.info(res.data.msg, 2)
            }
        })
    }

    render() {
        let info = ''
        if (this.props.data && this.props.data.course_info) {
            info = this.props.data.course_info
        }
        const {countdown} = this.state;
        const {user} = this.props
        const uid = user && user.data && user.data.uid

        return (

            <div>
                {/*正常购买*/}
                {
                    info.is_baoming === 0 && info.group_status !== 3 &&
                    <div className='btns-box'>
                        <a className='consult consult-s' href="https://q.url.cn/AB8aue?_type=wpa&qidian=true">
                            <i className='iconfont iconerji'></i>
                            <span>课程咨询</span>
                        </a>
                        {
                            info.in_cart &&
                            <Link to='/shopcart' className='btn btn-s bg-FCCD05'>去购物车结算</Link>
                        }
                        {
                            !info.in_cart &&
                            <button className='btn btn-s bg-FCCD05' onClick={e => this.toCart(1)}>加入购物车</button>

                        }
                        <span className='btn btn-s bg-FD7700' onClick={e => this.simpleCourse()}>立即报名</span>
                    </div>
                }

                {/*已购买*/}
                {
                    info.is_baoming === 1 &&
                    <div className='btns-box'>
                        <a className='consult consult-m' href="https://q.url.cn/AB8aue?_type=wpa&qidian=true">
                            <i className='iconfont iconerji' />
                            <span>课程咨询</span>
                        </a>
                        <Link to={`/play?id=${getParam('id')}`} className='btn btn-m bg-09f'>开始学习</Link>
                    </div>
                }
                {/*拼团 未开团*/}
                {
                    info.is_baoming === 0 && info.group_status === 3 &&
                    <div className='btns-box'>
                        <a className='consult consult-s' href="https://q.url.cn/AB8aue?_type=wpa&qidian=true">
                            <i className='iconfont iconerji'></i>
                            <span>课程咨询</span>
                        </a>
                        <button className='btn btn-s bg-F4AAA7' onClick={this.simpleCourse}>
                            <span>{`¥ ${info.price1}`}</span>
                            <span>直接购买</span>
                        </button>
                        <button className='btn btn-s bg-E02E24'>
                            <span onClick={this.keyToGroup}>
                                <span>{`¥ ${info.pdd_group_info.price}`}</span>
                                <span>一键开团</span>
                            </span>
                        </button>
                    </div>

                }
                {/*拼团 已开团*/}
                {
                    info.is_baoming === 0 && info.group_status === 4 &&
                    <div className='btns-box'>
                        <a className='consult consult-s' href="https://q.url.cn/AB8aue?_type=wpa&qidian=true">
                            <i className='iconfont iconerji'></i>
                            <span>课程咨询</span>
                        </a>
                        <div className='btn btn-l bg-E02E24' onClick={this.props.invitedFriends}>
                            邀请好友参团 {countdown} 后结束
                        </div>
                    </div>
                }

                {/*砍价*/}
                {
                    this.props.data && this.props.data.is_bargain &&
                    <div className='btns-box'>
                        <a className='consult consult-s' href="https://q.url.cn/AB8aue?_type=wpa&qidian=true">
                            <i className='iconfont iconerji'></i>
                            <span>课程咨询</span>
                        </a>
                        <button className='btn btn-s bg-F4AAA7'>
                            <span>¥{info.price1}</span>
                            <span onClick={this.tobuy}>直接购买</span>
                        </button>
                        {
                            (this.state.barInfo.bargain_status === 2 || !uid) &&
                            <button className='btn btn-s bg-E02E24' onClick={this.toKanjia}>
                                我要砍价
                            </button>
                        }
                        {
                            (this.state.barInfo.bargain_status === 0 || this.state.barInfo.bargain_status === 1) && (uid) &&
                            <button className='btn btn-s bg-E02E24'>
                                <span>¥{this.state.barInfo.amount}</span>
                                <span onClick={this.bargainToOrder}>去支付</span>
                            </button>
                        }
                    </div>
                }

                {/*特殊课程*/}
                {
                    this.state.isbuy === 20 &&
                    <div className='btns-box'>
                        <a className='consult-l' href="https://q.url.cn/AB8aue?_type=wpa&qidian=true">
                            <i className='iconfont iconerji'></i>
                            <span>课程咨询</span>
                        </a>
                    </div>
                }

                {/*特训营课程 未登录 未报名*/}
                {
                    (info.is_aist && (this.props.user.hasError || info.is_baoming === 0)) &&
                    <div className='btns-box'>
                        <a className='consult consult-m' href="https://q.url.cn/AB8aue?_type=wpa&qidian=true">
                            <i className='iconfont iconerji'></i>
                            <span>课程咨询</span>
                        </a>

                        <button className='btn sign-up-now' onClick={e => this.signUpNow()}>
                            <span>立即报名</span>
                        </button>
                    </div>
                }
                {/*特训营课程 登陆且已报名*/}
                {
                    info.is_aist && !this.props.user.hasError && info.is_baoming === 1 &&
                    <div className='btns-box'>
                        <a className='consult consult-m' href="https://q.url.cn/AB8aue?_type=wpa&qidian=true">
                            <i className='iconfont iconerji'></i>
                            <span>课程咨询</span>
                        </a>

                        {
                            info.aist_start_time === "" ?
                                (
                                    <Link to={`/play?id=${getParam('id')}`} className='btn btn-m learn-now'>
                                        <span>开始学习</span>
                                    </Link>

                                ) : (
                                    <button className='btn btn-m wait-open' >
                                        <span>{this.formatDate(info.aist_start_time)}</span>
                                    </button>
                                )
                        }
                    </div>
                }


                {
                    this.state.isShowOverlay &&
                    <Overlay>
                        {/*引导关注公众号*/}
                        {
                            this.state.bargainStatus === 1 &&
                            <CancelBargain close={this.close} cancel={this.cancel}/>
                        }

                        <i onClick={this.close} className={'iconfont iconiconfront-2 bargain-close'}></i>
                    </Overlay>

                }
            </div>
        )
    }
}


function CancelBargain(props) {
    return (
        <div className='cancel-bargain'>
            <p className='top-img'><i className='iconfont icondanseshixintubiao-8'></i></p>
            <p className='tip-mess'>您已发起砍价,直接购买将清除已砍金额。直接购买可使用优惠券~</p>
            <div className="btns">
                <button onClick={props.close}>取消</button>
                <button onClick={props.cancel}>确定</button>
            </div>
        </div>
    )
}

export default connect(
    state => ({
        user: state.user
    }),
    {getCourses}
)(BtnStatus)