import React, { Component } from 'react';
import HeaderBar from '@/common/HeaderBar'
import './video.scss'
import { NavLink, Route, Redirect, Switch } from 'react-router-dom';
import { http, api, getParam } from '@/utils'
import Recommendation from './recommendation'
import VideoCatalog from './video-catalog'
import DatumCatalog from './datum-catalog'
import { Toast } from 'antd-mobile';
import videojs from 'video.js'
import 'video.js/dist/video-js.min.css'
import { Modal } from "antd-mobile";
import { Loading } from '@/common'

let alert = Modal.alert


class Video extends Component {

    video
    player
    courseID


    state = {
        title: '',
        courseId: null,
        video_catalog: [],
        datum: [],
        currentVideoSrc: '',
        activeIndex: 0,
        isAuth: true,
        course: null,
        salePrice: null,
        vCourseId: null,
        isLoading: true
    }


    componentDidMount() {
        this.courseID = getParam('id')
        this.setState({
            courseId: this.courseID
        })
        this.getVideoCatalog()
        this.getDatumCatalog()
    }

    initializePlayer = () => {
        window.HELP_IMPROVE_VIDEOJS = false;
        this.player = videojs(this.video, {
            controls: true,
            preload: 'auto',
            bigPlayButton: true,
            textTrackDisplay: false,
            posterImage: false,
            errorDisplay: false
        })
        this.player.enableTouchActivity()

    }

    componentDidUpdate(prevProps, prevState) {
        console.log(this.video);
    }


    componentWillUnmount() {
        if (this.player) {

            this.player.dispose()
        }
    }

    handleClick = index => {
        if (this.hasAuth()) {
            this.setPlayerSrc(this.state.video_catalog[index]['play_url'])
            this.playVideo()
        }
        this.setState({
            activeIndex: index
        })
    }


    getVideoCatalog = () => {
        http.get(`${api.home}/m/course/play/${this.courseID}`)
            .then(res => {
                const data = res.data
                if (data.code === 200) {

                    this.setState(
                        state => ({
                            video_catalog: data.data['lessons'],
                            currentVideoSrc: data.data['lessons'][state.activeIndex]['play_url'],
                            course: data.data.course,
                            courseId: data.data.course['course_id'],
                            vCourseId: data.data.course['v_course_id'],
                            title: data.data.course['course_title'],
                            isLoading: false
                        }),
                        () => {
                            if (this.lessonAvailable()) {
                                if (this.hasAuth(this.state.activeIndex)) {
                                    Promise.resolve().then(() => {
                                        this.initializePlayer()
                                        this.playWithAuth()
                                    })
                                } else {
                                    this.getCoursePrice();
                                }
                            } else {
                                alert('暂无视频', '', [{
                                    text: 'OK',
                                    onPress: () => {
                                        this.props.history.push('/')
                                    }
                                }])
                            }
                        }
                    )
                } else {
                    Toast.info(data.msg)
                }
            })
    }

    setPlayerSrc = src => {
        this.player.src({
            src,
            type: 'application/x-mpegURL'
        })
    }

    playVideo = () => {
        this.player.play()
    }


    getDatumCatalog() {
        http.get(`${api.home}/m/course/data/${this.courseID}`)
            .then(res => {
                const data = res.data
                if (data.code === 200) {

                    this.setState({
                        datum: data.data
                    })

                } else {
                    Toast.info(data.msg)
                }
            })
    }

    lessonAvailable = () => {
        const {video_catalog, activeIndex} = this.state
        return video_catalog[activeIndex]['video_size'] !== 0
    }

    getCoursePrice = () => {
        http.get(`${api.home}/sys/course/price/${this.state.courseId}`)
            .then(res => {
                const {data} = res
                if (data.code === 200) {
                    this.setState({
                        salePrice: data.data['sale_price']
                    })
                }
            })
    }

    playWithAuth = () => {
        const {video_catalog, activeIndex} = this.state

        if (this.hasAuth()) {
            this.setPlayerSrc(video_catalog[activeIndex]['play_url'])
        }
    }

    hasAuth = (index) => {
        const {course, video_catalog, activeIndex} = this.state
        let lesson = video_catalog[activeIndex]
        if (!lesson['is_free']) {
            if (course['is_audition']) {
                this.setState({
                    isAuth: true
                })
                return true
            } else {
                if (lesson['video_auth']) {
                    this.setState({
                        isAuth: true
                    })
                    return true
                }
                this.setState({
                    isAuth: false
                })
                return false
            }

        }
        this.setState({
            isAuth: true
        })
        return true
    }


    render() {
        let {match, location} = this.props
        const {video_catalog, activeIndex, isAuth, salePrice} = this.state
        return (
            <div className='play'>
                <HeaderBar title={this.state.title} arrow={true}/>
                <Loading isLoading={this.state.isLoading}>
                    <div className="video">
                        <video className={'video-js'} ref={el => this.video = el}>
                            <source src={'/'} type='application/x-mpegURL'/>
                        </video>
                        {
                            !isAuth && (
                                <div className="purchase-box">
                                    <div className='hint'>您尚未购买该课时，请购买后学习。</div>
                                    <div className='btns'>
                                        <button type='button' className='purchase-class'>¥{salePrice} 购买课程</button>
                                        <button type='button'
                                                className='purchase-episode'>¥{video_catalog.length && video_catalog[activeIndex]['class_price']} 购买单集
                                        </button>
                                    </div>
                                </div>
                            )
                        }
                    </div>
                    <div className='tab'>
                        <div>
                            <NavLink to={`${match.url}/video`}
                                     replace
                                     activeClassName='active'
                            >视频</NavLink>
                        </div>
                        <div>
                            <NavLink to={`${match.url}/datum`}
                                     replace
                                     activeClassName='active'
                            >资料</NavLink>
                        </div>
                    </div>
                </Loading>
                <Switch>
                    <Redirect exact from={'/play'} to={{
                        pathname: '/play/video',
                        search: location.search
                    }}/>
                    <Route path={`${match.path}/video`} render={props => {
                        return <VideoCatalog
                            activeIndex={this.state.activeIndex}
                            handleClick={this.handleClick}
                            videoCatalog={this.state.video_catalog}
                            {...props}/>
                    }}/>
                    <Route path={`${match.path}/datum`} render={props => {
                        return <DatumCatalog {...props} datum={this.state.datum}/>
                    }}/>
                </Switch>
                <Route render={props => {
                    return this.state.vCourseId ? <Recommendation {...props} vCourseId={this.state.vCourseId}/>
                        : null
                }}/>
            </div>
        );
    }
}


export default Video;