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   //video element
    player  //video player instance
    courseID
    ws  //websocket instance
    timer


    state = {
        title: '',
        courseId: null,
        videoList: [],
        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.getVideoList()
        this.getDatumCatalog()

        this.setupWS()
        // this.setupTimer()

    }

    sendStudyRecord = () => {

    }

    setupWS = () => {
        this.ws = new WebSocket('ws://process-test.julyedu.com:9501');
        this.ws.addEventListener('onmessage', event => {
            console.log(event.data);
        })
        this.ws.addEventListener('open', () => {
            console.log('open');
        })
        this.ws.addEventListener('error', () => {
            console.log('error');
        })
        this.ws.addEventListener('close', () => {
            console.log('close');
        })
    }

    sendMessage = message => {
        if(this.player){

        }
    }

    setupTimer = () => {
        let count = 0
        this.timer = setInterval(() => {
            if(this.player){
                console.log(this.player);
                console.log(this.player.paused());
            }
        },1000)

    }

    initializePlayer = () => {
        window.HELP_IMPROVE_VIDEOJS = false;
        this.player = videojs(this.video, {
            controls: true,
            preload: 'auto',
            bigPlayButton: true,
            textTrackDisplay: false,
            posterImage: false,
            errorDisplay: false,
            playbackRates: ['0.75', '1', '1.5', '2'],
            userActions: {
                doubleClick: () => {
                    // this.player.pause()
                    console.log(this);
                }
            }
        })
        this.player.enableTouchActivity()
        this.player.on('seeking', function () {
            console.log('seeking');
        })
        console.log(this.player);
    }

    componentWillUnmount() {
        if (this.player) {

            this.player.dispose()
        }
        clearInterval(this.timer)
        this.ws = null
    }

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


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

                    this.setState(
                        state => ({
                            videoList: 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 {videoList, activeIndex} = this.state
        return videoList[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 {videoList, activeIndex} = this.state

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

    hasAuth = (index) => {
        const {course, videoList, activeIndex} = this.state
        let lesson = videoList[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 {videoList, 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'>¥{videoList.length && videoList[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.videoList}
                            {...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;