<template>
  <div class="div-container">
    <van-nav-bar title="新闻动态" left-text="返回" left-arrow @click-left="$router.back()" />

    <div class="div-body">
        <!-- 图片 -->
        <div class="detail-head">
            <video height="200" width="100%" controls 
                @playing="onPlaying"
                @pause="onPause"
                @emptied="onEmptied"
                @abort="onAbort"
                @ended="onEnded">
                <source :src="videoData.path">
                您的浏览器不支持 video 标签。
            </video>
        </div>
        <div class="detail-content">
            <div style="margin: 10px 0;">
                <yd-flexbox>
                    <yd-flexbox-item>主讲老师：{{videoData.lector || '无'}}</yd-flexbox-item>
                    <yd-flexbox-item>视频时长：{{videoData.duration|calcDuration}}</yd-flexbox-item>
                </yd-flexbox>
            </div>
            <!-- <h5>简介</h5> -->
            <!-- {{videoData.introduction}} -->
        </div>
    </div>

  </div>
</template>

<script type="text/babel">

import Vue from 'vue';
import { NavBar } from 'vant';

Vue.use(NavBar);

export default {
    filters: {
        calcDuration(num) {
            num = parseInt(num);
            if (isNaN(num)) {
                return 0;
            }
            let min = Math.floor(num / 60),
                sec = num % 60,
                str = '';
            
            min && (str += min + '分');
            str += sec + '秒';
            return str;
        }
    },
    data() {
        return {
            videoId: null,
            videoData: {},
            userid: null,
            openid: null,
            currentTimeIndex: null, // 当前播放进度timer
            playingTimeIndex: null, // 播放时长timer
            // TODO: localStorage保存，与服务器通讯成功后才清零
            // currentTime: 0, // 当前播放时间
            playingTime: 0, // 播放时长：播放（playing）开始计时，停止（pause）、网络错误（emptied）等停止计时；销毁页面清零
            playCount: 0, // 播放次数：播放（playing）时，当值=0时次数+1；销毁页面清零
        };
    },
    created() {
        this.userid = localStorage.getItem("userid");
        this.openid = localStorage.getItem("openid");
        
        // 视频id
        this.videoId = this.$route.query.id;
        if (!this.videoId) {
            this.$notify('缺少参数:id');
            return;
        }
    
        // 获取video信息
        this.getVideoDetail();

        this.$nextTick(()=>{
            // 设置播放进度
            this.setCurrentTime();
            // 设置播放时长
            this.playingTime = this.getStoragePlayingTime();
            // 设置播放次数
            this.playCount = this.getStoragePlayCount();
        })
    },
    destroyed() {
        // 保存播放数据
        this.savePlayingData();
    },
    methods: {
        /**
         * 保存播放数据
         */
        savePlayingData() {
            if (this.playCount == 0 || this.playingTime == 0) {
                return;
            }
            var postData = {
                video_id: this.videoId,
                user_id: this.userid,
                first_play_time: this.firstPlayTime,
                views: this.playCount,
                total_time: this.playingTime,
            }
            this.$http.post('/saveVideoPlayingData&userid=' + this.userid+'&openid='+this.openid, JSON.stringify(postData))
                .then(res => {
                    // 保存成功，播放次数和播放时间清零
                    if (res.data.success) {
                        localStorage.setItem('video_play_count_'+ this.videoId + '_' + this.userid, 0);
                        localStorage.setItem('video_playing_time_'+ this.videoId + '_' + this.userid, 0);
                    } else { // 保存失败，将播放次数、播放时长保存在本地
                        localStorage.getItem('video_play_count_'+ this.videoId + '_' + this.userid, this.playCount);
                        localStorage.getItem('video_playing_time_'+ this.videoId + '_' + this.userid, this.playingTime);
                    }
                }).catch(()=>{
                    localStorage.getItem('video_play_count_'+ this.videoId + '_' + this.userid, this.playCount);
                    localStorage.getItem('video_playing_time_'+ this.videoId + '_' + this.userid, this.playingTime)
                })
        },
        /**
         * 获取课程列表
         */
        getVideoDetail() {
            this.$http.get('/getVideoDetail&userid='+this.userid+'&openid='+this.openid+'&id='+ this.videoId)
                .then(res => {
                    this.videoData = res.data.data || {};

                    document.getElementsByTagName('video')[0].src = this.videoData.path;

                    if (!res.data.success) {
                        this.$notify(res.data.message)
                    }
                })
        },
        /**
         * 开始记录播放进度timer
         */
        startCurrentTimeTimer() {
            this.stopCurrentTimeTimer();

            this.currentTimeIndex = setInterval(() => {
                this.storeCurrentTime();
            }, 1000);
        },
        /**
         * 结束播放进度timer
         */
        stopCurrentTimeTimer() {
            this.currentTimeIndex && clearInterval(this.currentTimeIndex);
        },
        /**
         * 开始播放计时timer
         */
        startPlayingTimer() {
            this.stopPlayingTimer();

            this.playingTimeIndex = setInterval(() => {
                this.playingTime = parseInt(this.playingTime) + 1;
            }, 1000);
        },
        /**
         * 结束播放计时timer
         */
        stopPlayingTimer() {
            this.playingTimeIndex && clearInterval(this.playingTimeIndex);
        },
        /**
         * 播放
         */
        onPlaying() {
            var playCount = this.getStoragePlayCount();
            var currentTime = this.getStorageCurrentTime();
            if (playCount == 0) {
                this.firstPlayTime = new Date().getTime();
            }
            if (currentTime == 0) {
                // 播放次数+1
                this.playCount = parseInt(playCount) + 1;
            }
            // 开始记录当前播放时间
            this.startCurrentTimeTimer();
            // 开始记录播放时长
            this.startPlayingTimer();
        },
        /**
         * 停止
         */
        onPause() {
            // 停止记录当前播放时间
            this.stopCurrentTimeTimer();
            // 停止记录播放时长
            this.stopPlayingTimer();
            // 保存播放次数
            localStorage.setItem('video_play_count_'+ this.videoId + '_' + this.userid, this.playCount);
            // 保存播放时间
            localStorage.setItem('video_playing_time_'+ this.videoId + '_' + this.userid, this.playingTime);
        },
        /**
         * 网络错误、加载错误等 
         */
        onEmptied() {
            this.onPause();
        },
        /**
         * 中止
         */
        onAbort() {
            this.onPause();
        },
        /**
         * 播放结束
         */
        onEnded() {
            // 当前播放进度清零
            localStorage.setItem('video_current_time_' + this.videoId + '_' + this.userid, 0);
        },
        /**
         * 设置播放时长
         */
        storePlayingTime() {
            // 保存播放进度
            this.currentTimeIndex = setInterval(() => {
                this.storeCurrentTime();
            },1000)
        },
        /**
         * 记录当前播放进度
         */
        storeCurrentTime() {
            var el = document.getElementsByTagName('video')[0],
                cur_time = el.currentTime;
            if (!cur_time) {
                return false;
            }
            localStorage.setItem('video_current_time_' + this.videoId + '_' + this.userid, Math.floor(cur_time));
        },
        /**
         * 设置当前播放进度
         */
        setCurrentTime() {
            var cur_time = this.getStorageCurrentTime();
            if (!cur_time) {
                return false;
            }
            var el = document.getElementsByTagName('video')[0];
            el.currentTime = cur_time;
        },
        /**
         * 获取缓存的播放进度
         */
        getStorageCurrentTime() {
            return localStorage.getItem('video_current_time_'+ this.videoId + '_' + this.userid) || 0;
        },
        /**
         * 获取缓存的播放次数
         */
        getStoragePlayCount() {
            return localStorage.getItem('video_play_count_'+ this.videoId + '_' + this.userid) || 0;
        },
        /**
         * 获取缓存的播放次数
         */
        getStoragePlayingTime() {
            return localStorage.getItem('video_playing_time_'+ this.videoId + '_' + this.userid) || 0;
        },
        goback() {
            this.$router.back();
        },

    }
};
</script>
<style scoped="less">
.div-container {
    height: 100vh;
    background-color: #fff;
}
.detail-head {
    width: 100%;
    height: 200px;
    background-color: #000;
}
.yd-tab-panel>.yd-tab-panel-item {
    height: calc(100vh - 295px);
}
.detail-content {
    height: calc(100vh - 250px);
    word-break: break-all;
    overflow-x: hidden;
    overflow-y: auto;
}
#applyBtn {
    position: fixed;
    bottom: 0;
}

.yd-list-other {
    flex-flow: column;
}
.yd-flexbox {
    width: 100%;
    line-height: 2em;
    color: #000;
}
.yd-list-title span{
    overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    word-break: break-all;
    text-overflow: ellipsis;
    line-height: .38rem;
    max-height: 1.34rem;
}
.list-item-content {
    height: 55px;

    display: -webkit-box !important;
    overflow: hidden;
    
    /* text-indent: 2em; */
    text-overflow: ellipsis;
    word-break: break-all;
    
    /* -webkit-box-orient: vertical; */
    -webkit-line-clamp: 3;
}
.detail-content {
    padding: 10px;
}
</style>