import React, {Component} from 'react'
import './index.scss'
import Bargain from './bargain'
import Group from './group'
import OutLine from './outline'
import {HeaderBar, CallApp} from '../../common'
import ShareRank from "./shareRank"
import Audition from "./audition"
import Single from "./single"
import SingleSuccess from './single/singleSuccess';
import BtnStatus from "./btnstatus"
import Carouselw from "./carousel"
import {connect} from "react-redux"
import {getCourses, addCourseToCart} from "./actions"
import {getParam, http, browser} from "@/utils"
import {Toast} from 'antd-mobile'
import {compose, bindActionCreators} from "redux";

class Detail extends Component {

    courseId

    constructor(props) {
        super(props)
        this.state = {
            isbuy: 0,
            isvip: 0,
            auditionBox: false,

            singleBox: false,
            singleType: 1,

            shareRank: false,
            singMess: '',
            barInfo: '',
            share: false,
            countdown: '00:00:00',
            outList: [],
            list: [],
            course: {}
        }
    }

    componentDidMount() {
        this.fetchCourseInfo();
        const { location: { state = {} } } = this.props;
        if(state.oid) {
            this.check(state.oid);
        }
    }

    // 判断支付是否成功
    check = (oid) => {
        http.get(`${API['base-api']}/class_order_status/${oid}`).then((res) => {
            if (Number(res.data.data.errno) === 200) {
                // 正常购买单集成功
                this.setState({
                    singleType: 6,
                    
                })
            } else if (Number(res.data.data.errno) === 201) {
                // 0元参团
                this.setState({
                    singleType: 4,
                    
                })
            } else if (Number(res.data.data.errno) === 202) {
                // 0元购
                this.setState({
                    singleType: 3,
                    
                })
            } 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,
                    singleType: 2,
                    
                })
            } else {
                Toast.info(res.data.data.msg, 2)
            }
        })
    }
    // payCallback = () => {
    //
    // };
    // weixinPay = (weixin_code) => {
    //
    // }
    payCallBack = (singleType, nowPrice, laterPrice) => {
        const _this = this;
        if(singleType === 2) {
            _this.setState({
                singleType,
                nowPrice,
                laterPrice
            })
        }else{
            _this.setState({
                singleType,
            })
        }
    };
    fetchCourseInfo = () => {
        const id = getParam('id');
        http.get(`${API.home}/m/course/detail/${id}`).then((res) => {
            const {data, code} = res.data;
            if (code === 200) {
                this.setState({
                    course: data
                });
                if (data.course_info) {
                    let course_info = data.course_info;
                    if (course_info.group_status === 3 || course_info.group_status === 4) {
                        let endTime = course_info.pdd_group_info.groupon_member.end_time;
                        let date = endTime * 1000,
                            hours = 0,
                            minutes = 0,
                            seconds = 0;
                        setInterval(() => {
                            date -= 1000
                            hours = `${parseInt(date / (60 * 60 * 1000))}`.padStart(2, 0);
                            minutes = `${parseInt((date - hours * 3600000) / 60000)}`.padStart(2, 0);
                            seconds = `${parseInt((date - hours * 3600000 - minutes * 60000) / 1000)}`.padStart(2, 0);
                            this.setState({
                                countdown: `${hours}:${minutes}:${seconds}`
                            });
                        }, 1000)
                    }
                }

                
            }
        });
    }

    // 点击子组件试听按钮
    toAudition = () => {
        const {user} = this.props
        const uid = user && user.data && user.data.uid
        if (!uid) {
            this.props.history.push('/passport/login')
        } else {
            this.setState({
                auditionBox: true,
            })
        }
    }
    // 点击子组件单集购买按钮
    toSingleset = (item) => {
        console.log(this.props);
        const {user} = this.props
        const uid = user && user.data && user.data.uid
        if (!uid) {
            this.props.history.push('/passport/login')
        } else {
            this.setState({
                singleBox: true,
                singleType: 1,
                singMess: item
            });
        }
    }

    // componentWillReceiveProps(nextProps) {
    //     let _this = this;
    //     if (nextProps.courseInfo.course_info) {
    //         let courseInfo = nextProps.courseInfo.course_info;
    //         if (courseInfo.group_status === 3 || courseInfo.group_status === 4) {
    //             let endTime = courseInfo.pdd_group_info.groupon_member.end_time;
    //             let date = endTime * 1000,
    //                 hours = 0,
    //                 minutes = 0,
    //                 seconds = 0;
    //             setInterval(() => {
    //                 date -= 1000
    //                 hours = `${parseInt(date / (60 * 60 * 1000))}`.padStart(2, 0);
    //                 minutes = `${parseInt((date - hours * 3600000) / 60000)}`.padStart(2, 0);
    //                 seconds = `${parseInt((date - hours * 3600000 - minutes * 60000) / 1000)}`.padStart(2, 0);
    //                 _this.setState({
    //                     countdown: `${hours}:${minutes}:${seconds}`
    //                 });
    //             }, 1000)
    //         }
    //     }
    // }

    // 加入购物车 type：1 加入购物车，2加入购物车并跳转到购物车页面去支付
    toCart = (type) => {
        const { history, addCourseToCart } = this.props;
        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()
                    addCourseToCart();
                    this.fetchCourseInfo();
                } else {
                    history.replace('/shopcart');ß
                }
            } else if (res.data.code === 15001) {
                history.replace('/shopcart');
            } else if (res.data.code === 4030) {
                history.replace('/passport');
            } else {
                Toast.info(res.data.msg, 2);
            }
        })
    };

    invitedFriends = () => {
        const {course_title, image_name, course_id, pdd_group_info, pdd_group_info: {groupon_member, groupon_member: {number}, price}} = this.state.course.course_info;
        if (browser.isWeixin) {
            let share = this.state.share;
            this.setState({
                share: !share,
            });
            let shareData = {
                title: `【仅剩${number}个名额】我${price}元拼了《${course_title}》`,
                desc: course_title,                               //  分享描述
                link: location.origin + `/detail??id=${course_id}`, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                imgUrl: image_name, // 分享图标
            };

            http.post(`${API['base-api']}/m/sale/signature`).then(res => {
                const {nonce_str, signature, timestamp} = res.data;
                wx.config({
                    "debug": false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                    "appId": 'wx23dac6775ac82877', // 必填，公众号的唯一标识
                    "timestamp": timestamp, // 必填，生成签名的时间戳
                    "nonceStr": nonce_str, // 必填，生成签名的随机串
                    "signature": signature, // 必填，签名
                    jsApiList: [
                        'hideMenuItems',
                        'showMenuItems',
                        'updateAppMessageShareData',
                        'updateTimelineShareData',
                        'onMenuShareWeibo',
                        'onMenuShareAppMessage',
                    ], // 必填，需要使用的JS接口列表
                });
            });
            wx.ready(function () {   //需在用户可能点击分享按钮前就先调用
                wx.hideAllNonBaseMenuItem();
                wx.showMenuItems({
                    menuList: ['menuItem:share:appMessage', 'menuItem:share:timeline'] // 要显示的菜单项，所有menu项见附录3
                });
                wx.updateAppMessageShareData({
                    ...shareData,
                    success: function () {
                        // 设置成功
                    }
                })
                wx.updateTimelineShareData({
                    ...shareData,
                    success: function () {
                        // 设置成功
                    }
                })
            });
        } else {
            Toast.info('请在微信中使用分享功能！', 2);
        }
    }

    // 自组件传给父组件的boxHide
    boxHide = (val) => {
        this.setState({
            auditionBox: val, 
            singleBox: val,
            singleType: 1
        })
        this.props.history.push(`/detail?id=${getParam('id')}`);

    }

    render() {
        const { course: { course_info={} }, barInfo, singleBox, singleType } = this.state;
        console.log(course_info);
        let courseInfo = '',
            service = '',
            number = 0,
            endTime = 0;
        // if (this.props.courseInfo.course_info) {
        //     courseInfo = this.props.courseInfo.course_info;
        //     service = courseInfo.service;
            if (course_info.group_status === 3 || course_info.group_status === 4) {
                number = course_info.pdd_group_info.groupon_member.number;
            }
        // }
        const {share, countdown, list, outList} = this.state;
        let href = this.props.location && this.props.location.state? this.props.location.state.href : undefined;
        const { location: { state = {}} } = this.props;
        if(state.oid) {
            href='/classify'
        }
         
        return (
            <div>
            <div className='detail-box'>
                <HeaderBar 
                    title='课程详情' 
                    arrow={true} 
                    cart={true} 
                    toHref={href}
                />
                <CallApp className='toapp' />

                {/*弹幕*/}
                <Carouselw />

                {/*课程*/}
                <div className='course-content'>
                    <div className='cover'>
                        <img src={course_info.image_name} alt="" />
                        {
                            course_info.is_aist &&
                            <span className='return_cash' />
                        }
                    </div>
                    <div className="info">
                        <p className='title'>{course_info.course_title}</p>
                        <p className='contact text-overflow-2'>{course_info.simpledescription}</p>
                        <div className='des'>
                            {
                                course_info.is_baoming === 0 && 
                                <p className="course-price">
                                    <span className="new">¥{course_info.price1}</span>
                                    <span className="old">¥{course_info.price0}</span>
                                </p>
                            }
                            {
                                course_info.is_baoming === 1 &&
                                <span className="isbuy">已购买</span>
                            }
                        </div>
                    </div>
                </div>

                {/*正常课程已购买时显示*/}
                {
                    course_info.is_baoming === 1 &&
                    <div className='group'>
                        上课QQ群：{course_info.course_qq}，加群请备注您的学号：{course_info.uid}
                    </div>
                }

                {/*vip课程显示*/}
                {
                    course_info.vip_range &&
                    <div className="vip">
                        <p>已开通年会员：{course_info.vip_range}</p>
                        <p>年会员QQ群：{course_info.course_qq}，加群请备注您的学号：{course_info.uid}</p>
                    </div>
                }

                {/*服务承诺*/}
                <div className='promise'>
                    <label>服务承诺</label>
                    <p>
                        {
                            course_info.service && course_info.service.length > 0 && course_info.service.map((item, index) => {
                                return (
                                    <span key={index}> {item} </span>
                                )
                            })
                        }
                    </p>
                </div>

                {/*试听弹窗*/}
                <Audition auditionBox={this.state.auditionBox} boxHide={this.boxHide}/>

                {/*单集购买弹窗*/}
                {
                singleBox && 
                <Single
                    singleType={this.state.singleType}
                    singleBox={this.state.singleBox}
                    boxHide={this.boxHide} 
                    data={this.state.singMess}
                    vcourseId={course_info.v_course_id}
                    videoId={this.state.singMess.video_id}
                    title={course_info.course_title}
                    check={this.check}
                />}
                {/* 单集购买成功弹窗 */}
                {
                    singleType != 1 &&
                    <SingleSuccess 
                    boxHide={this.boxHide} 
                    data={this.state.singMess}
                        singleType={singleType} 
                        videoId={this.state.singMess.video_id}
                        payCallBack={this.payCallBack}
                    />
                }
                {/*payCallback={this.payCallback}*/}
                {/*weixinPay = {this.weixinPay}*/}

                {/*分享赚钱*/}
                {
                    course_info.is_dist &&
                    <ShareRank courseInfo={course_info} />
                }

                {/**
                  * 拼团
                  * is_aist: 是否AI特训营
                  * group_status: 团状态，3：课程有小团 用户没参加小团；4：用户参加了小团
                */}
                {
                    !course_info.is_aist && (course_info.group_status === 3 || course_info.group_status === 4) &&
                    <Group
                        courseInfo={course_info}
                        history={this.props.history} 
                        countdown={countdown}
                        invitedFriends={this.invitedFriends}
                    />
                }

                {/*砍价*/}
                {
                    course_info.is_baoming === 0 && (!course_info.is_aist) && course_info.is_bargain &&
                    <Bargain />
                }

                {/*课程介绍、大纲*/}
                <OutLine 
                    data={course_info} 
                    toAudition={this.toAudition} 
                    toSingleset={this.toSingleset}
                />

                {/*课程按钮*/}
                {
                course_info &&
                <BtnStatus 
                    countdown={countdown}
                    data={course_info}
                    user={this.props.user}
                    invitedFriends={this.invitedFriends}
                    // addCourseToCart={this.props.addCourseToCart}
                    toCart={this.toCart}
                    history={this.props.history}
                />}

                {
                    share ? (
                        <div 
                            className='groupSuccessMbc'
                            onClick={() => {
                                this.setState({share: false})
                            }}
                        >
                            <div className='tipContent'>
                                {`还差${number}人，分享到3个群，成团率高达98%`}
                            </div>
                            <div className='tipArrow'>
                                <i className='iconfont iconyindao' />
                            </div>
                        </div>
                    ) : null
                }
            </div>
            </div>
        )
    }

}

const mapStateToProps = (state) => {
    return {
        // courseInfo: state.courseInfo,
        user: {
            ...state.user
        }
    }
}

// const mapDispatchToProps = {
//     fetchCoursesListIfNeeded
// }
const mapDispatchToProps = (dispatch) => {
    return bindActionCreators(
        {
            getCourses,
            addCourseToCart
        },
        dispatch
    )
}
  

export default connect(mapStateToProps, mapDispatchToProps)(Detail)