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 BtnStatus from "./btnstatus"
import Carouselw from "./carousel"
import {connect} from "react-redux"
import {fetchCoursesListIfNeeded} from "./actions"
import {getParam, http, browser} from "@/utils"
import {Toast} from 'antd-mobile'
import {compose} from "redux";

class Detail extends Component {

    constructor(props) {
        super(props)
        this.state = {
            isbuy: 0,
            isvip: 0,
            auditionBox: false,
            singleBox: false,
            shareRank: false,
            singMess: '',
            barInfo: '',
            share: false,
            countdown: '00:00:00',
        }
    }

    componentDidMount() {
        this.props.fetchCoursesListIfNeeded();
    }

    // 点击子组件试听按钮
    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) => {
        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,
                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)
            }
        }
    }

    invitedFriends = () => {
        const {course_title, image_name, course_id, pdd_group_info, pdd_group_info: {groupon_member, groupon_member: {number}, price}} = this.props.courseInfo.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, // 分享图标
            };
            console.log(shareData);
            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);
        }
    }

    //获取砍价信息
    getBargainInfo = () => {
        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)
            }
        })
    }

    // 自组件传给父组件的boxHide
    boxHide = (val) => {
        this.setState({auditionBox: val, singleBox: val})
    }

    render() {
        let courseInfo = '',
            service = '',
            number = 0,
            endTime = 0;
        if (this.props.courseInfo.course_info) {
            courseInfo = this.props.courseInfo.course_info;
            service = courseInfo.service;
            if (courseInfo.group_status === 3 || courseInfo.group_status === 4) {
                number = courseInfo.pdd_group_info.groupon_member.number;
            }
        }
        const {share, countdown} = this.state;
        return (
            <div className='detail-box'>
                <HeaderBar title='课程详情' arrow={true} cart={true}></HeaderBar>
                <CallApp className='toapp'></CallApp>
                {/*弹幕*/}
                <Carouselw></Carouselw>
                {/*课程*/}
                <div className='course-content'>
                    <div className='cover'>
                        <img src={courseInfo.image_name}
                             alt=""/>
                        {
                            (courseInfo.is_aist &&
                                <span className='return_cash'></span>
                            )
                        }
                    </div>
                    <div className="info">
                        <p className='title'>{courseInfo.course_title}</p>
                        <p className='contact text-overflow-2'>{courseInfo.simpledescription}</p>
                        <div className='des'>
                            {courseInfo.is_baoming === 0 && <p className="course-price">
                                <span className="new">¥{courseInfo.price1}</span>
                                <span className="old">¥{courseInfo.price0}</span>
                            </p>
                            }
                            {courseInfo.is_baoming === 1 &&
                            <a href="/#" className="isbuy">已购买</a>
                            }
                        </div>
                    </div>
                </div>
                {/*正常课程已购买时显示*/}
                {
                    courseInfo.is_baoming === 1 &&
                    <div className='group'>
                        上课QQ群：{courseInfo.course_qq}，加群请备注您的学号：{courseInfo.uid}
                    </div>
                }
                {/*vip课程显示*/}
                {
                    courseInfo.vip_range &&
                    <div className="vip">
                        <p>已开通年会员：{courseInfo.vip_range}</p>
                        <p>年会员QQ群：{courseInfo.course_qq}，加群请备注您的学号：{courseInfo.uid}</p>
                    </div>
                }

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

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

                {/*单集购买*/}
                <Single singleBox={this.state.singleBox} boxHide={this.boxHide} data={this.state.singMess}
                        title={courseInfo.course_title}/>

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

                {/*拼团*/}
                {
                    (!courseInfo.is_aist && (courseInfo.group_status === 3 || courseInfo.group_status === 4)) &&
                    <Group history={this.props.history} countdown={countdown}/>
                }


                {/*砍价*/}
                {
                    (!courseInfo.is_aist) && this.props.courseInfo && this.props.courseInfo.is_bargain &&
                    <Bargain/>
                }

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

                {/*课程按钮*/}
                <BtnStatus countdown={countdown}
                           data={this.props.courseInfo}
                           user={this.props.user}
                           barInfo={this.state.barInfo}
                           getBargainInfo={this.getBargainInfo}
                           invitedFriends={this.invitedFriends}
                           history={this.props.history}></BtnStatus>

                {
                    share ? (
                        <div className='groupSuccessMbc' onClick={() => {
                            this.setState({share: false})
                        }}>
                            <div className='tipContent'>

                                {`还差${number}人，分享到3个群，成团率高达98%`}
                            </div>
                            <div className='tipArrow'>
                                <i className='iconfont iconyindao'></i>
                            </div>
                        </div>
                    ) : null
                }
            </div>
        )
    }

}

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

const mapDispatchToProps = {
    fetchCoursesListIfNeeded
}
export default connect(mapStateToProps, mapDispatchToProps)(Detail)