<template>
    <div class="video-container">
        <div class="video-main">
            <video class="video-js vjs-theme-city" id="my-player" preload="auto" ref="videoPlayer1"></video>
        </div>
        <div class="vjs-playlist" v-if="clonedOptions.hasPlaylist">
        </div>
        <div id="wxyDialog" style="visibility: hidden; position: absolute;">
            <div class="dl-shiti">
                <mta-single-choice
                        :getShowModel="false"
                        :questionData="shiti"
                        @reply="replyCallback"
                        ref="shiti1"
                        v-if="shiti.stTypeId === 1"
                ></mta-single-choice>
                <mta-multiple-choice
                        :getShowModel="false"
                        :questionData="shiti"
                        @reply="replyCallback"
                        ref="shiti2"
                        v-if="shiti.stTypeId === 2"
                ></mta-multiple-choice>
                <mta-true-or-false
                        :getShowModel="false"
                        :questionData="shiti"
                        @reply="replyCallback"
                        ref="shiti3"
                        v-if="shiti.stTypeId === 3"
                ></mta-true-or-false>
                <mta-gap-filling
                        :getShowModel="false"
                        :questionData="shiti"
                        @reply="replyCallback"
                        ref="shiti4"
                        v-if="shiti.stTypeId === 4"
                ></mta-gap-filling>
                <mta-read-the-topic
                        :getShowModel="false"
                        :questionData="shiti"
                        @reply="replyCallback"
                        ref="shiti5"
                        v-if="shiti.stTypeId === 5"
                ></mta-read-the-topic>
            </div>

            <div class="dl-btn">
                <el-button @click="isReplyRight" size="small" type="primary">确定</el-button>
            </div>
            <div class="answer-dialog" v-show="answerDialogVisible">
                <i class="el-message__icon el-icon-error"></i>
                <div>答案不正确</div>
            </div>
            <!--<el-dialog
                    title="提示"
                    class="response-tip-dialog"
                    :visible.sync="answerDialogVisible"
                    :append-to-body="options.type === 1"
                    center>
                <div style="padding-bottom: 20px">答案不正确</div>
            </el-dialog>-->
        </div>

    </div>
</template>

<script>
    import 'video.js/dist/video-js.css';
    import '@/assets/css/video/city.css';
    import 'videojs-playlist-ui/dist/videojs-playlist-ui.vertical.css';

    import videojs    from 'video.js';
    import playlist   from 'videojs-playlist';
    import playlistUi from 'videojs-playlist-ui';
    import {
        isObject, clone, getZhcnOption,
        saveCourseProgress, updateSectionProgress,
        getCourseProgress,
    }                 from '@/utils/common';

    import MtaSingleChoice   from '@/components/client/QuestionsForCuoti/SingleChoice.vue';
    import MtaMultipleChoice from '@/components/client/QuestionsForCuoti/MultipleChoice.vue';
    import MtaTrueOrFalse    from '@/components/client/QuestionsForCuoti/TrueOrFalse.vue';
    import MtaGapFilling     from '@/components/client/QuestionsForCuoti/GapFilling.vue';
    import MtaReadTheTopic   from '@/components/client/QuestionsForCuoti/ReadTheTopic.vue';

    export default {
        name:       'VideoPlayer',
        props:      {
            options: {
                type: Object,
                default() {
                    return {};
                },

            },
        },
        computed:   {},
        components: {
            MtaSingleChoice,
            MtaMultipleChoice,
            MtaTrueOrFalse,
            MtaGapFilling,
            MtaReadTheTopic,
        },
        data() {
            return {
                player:              null,
                clonedOptions:       {},
                modalDialog:         null,
                shiti:               {},
                shitiIndex:          null,
                shitiList:           null,
                shitiTimeArr:        null,
                shitiTimeDoneArr:    [],
                doneTempFlg:         false,
                dialogDisplay:       false,
                lastOpenTime:        0,
                preTimeupdateTime:   0,
                maxPlayTime:         0,
                maxPlayTimeRecord:   0,
                hasInitPlayer:       false,
                duration:            0,
                answerDialogVisible: false,
            };
        },
        mounted() {
            this.initShiti();
            this.setVideoZhCN();
            videojs.hook('beforesetup', function (videoEl, options) {
                options.language = 'zh-CN';
                options.userActions = {};
                options.userActions.hotkeys = {};
                options.userActions.hotkeys.playPauseKey = function (e) {
                    videojs.log(e);
                };
                return options;
            });
            if (this.clonedOptions.hasPlaylist) {
                videojs.registerPlugin('playlist', playlist);
                videojs.registerPlugin('playlistUi', playlistUi);
            }
        },
        methods:    {
            displayQuestionByCurrentTime() {
                const curTime = this.player.currentTime();
                let curSecInt = parseInt(curTime);
                if (this.shitiTimeArr) {
                    if (this.shitiTimeArr.indexOf(curSecInt) > -1
                        && this.dialogDisplay === false) {
                        if (this.clonedOptions.questionDoneShow) {
                            this.player.pause();
                            this.callShiti(this.shitiTimeArr.indexOf(curSecInt));
                        } else {
                            if (this.shitiTimeDoneArr.indexOf(curSecInt) === -1) {
                                this.player.pause();
                                this.callShiti(this.shitiTimeArr.indexOf(curSecInt));
                            }
                        }

                    }
                }

            },
            setVideoZhCN() {
                videojs.addLanguage('zh-CN', getZhcnOption());
            },
            dialogOpen() {
                this.dialogDisplay = true;
                this.lastOpenTime = this.player.currentTime();
                let ModalDialog = videojs.getComponent('ModalDialog');
                var contentEl = document.getElementById('wxyDialog');
                contentEl.style.visibility = 'visible';
                let opt = {
                    content:     contentEl,
                    description: 'description st9988',
                    fillAlways:  false,
                    label:       'stlabel',
                    pauseOnOpen: true,
                    temporary:   false,
                    uncloseable: false,
                };
                this.modalDialog = new ModalDialog(this.player, opt);
                this.player.addChild(this.modalDialog);
                this.modalDialog.on('dispose', () => {
                    this.player.removeChild(this.modalDialog);
                });
                this.modalDialog.on('modalclose', () => {
                    console.log('modalDialog closed');
                    this.dialogDisplay = false;
                });
                this.modalDialog.open();
                // this.render();
                // let stModalDialog = this.player.addChild(modalDialog);
                // this.divShow = true;
            },
            callShiti(index) {
                this.shiti = this.shitiList[index];
                this.shitiIndex = index;
                this.dialogOpen();
                this.preventStep();
            },
            /**
             * 弹出窗口时，防止步进
             */
            preventStep() {
                if (this.player.currentTime() - this.lastOpenTime < 1) {
                    console.log('preventStep');
                    this.player.currentTime(this.lastOpenTime);
                }
            },
            replyCallback(payLoad) {
                // console.log('replyCallback', payLoad);
                this.shitiList[this.shitiIndex].reply = payLoad.data;
            },
            isReplyRight() {
                // right
                // console.log(this.shitiList[this.shitiIndex].reply, this.shitiList[this.shitiIndex]);
                function checkAnswer(shiti) {
                    // console.log(shiti);
                    if (shiti.stTypeId === 1 || shiti.stTypeId === 3) { // 单选
                        if (shiti.reply === shiti.result) {
                            return true;
                        }
                    } else if (shiti.stTypeId === 2) { // 多选
                        const _r = shiti.result.join(',');
                        let _d = '';
                        if (shiti.reply === null) {
                            _d = '';
                        } else {
                            _d = shiti.reply.join(',');
                        }
                        if (_r === _d) {
                            return true;
                        } else {
                            return false;
                        }
                    } else if (shiti.stTypeId === 4) {
                        if (shiti.reply === null) {
                            return false;
                        }
                        const _r = [];
                        for (let i = 0; i < shiti.reply.length; i++) {
                            if (shiti.result[i].indexOf(shiti.reply[i]) !== -1) {
                                _r.push(true);
                            }
                        }
                        if (_r.length === shiti.reply.length) {
                            return true;
                        }
                        return false;
                    } else if (shiti.stTypeId === 5) {
                        return true;
                    } else {
                        throw new Error('checkAnswer没有类型匹配');
                    }
                }

                if (checkAnswer(this.shitiList[this.shitiIndex])) {
                    this.$message.success('答案正确');
                    this.shitiTimeDoneArr.push(this.shitiTimeArr[this.shitiIndex]);
                    // 由于现在不判断答案正确性，只判断视频是否播放完成
                    // 所以这里什么都不做

                    // close dialog
                    document.getElementById('wxyDialog').style.visibility = 'hidden';
                    this.modalDialog.close();
                    this.doneTempFlg = true;
                    this.$nextTick(() => {
                        this.player.play();
                        setTimeout(() => {
                            this.doneTempFlg = false;
                        }, 2000);
                    });

                } else {
                    // show error msg
                    this.answerDialogVisible = true;
                    setTimeout(()=>{
                        this.answerDialogVisible = false;
                    }, 1500)
                }
            },
            initShiti() {
                let hasShitiNull = false;
                this.clonedOptions = clone(this.options);
                if (this.clonedOptions.shitiList) {
                    this.shitiList = [];
                    this.shitiTimeArr = [];
                    for (const shiti of this.clonedOptions.shitiList) {
                        if (shiti === null) {
                            hasShitiNull = true;
                            break;
                        }
                        this.shitiTimeArr.push(shiti.showTime);
                        this.shitiList.push(shiti.shiti);
                    }
                    if (hasShitiNull) {
                        this.$message.error('业务逻辑错误: 试题实体没有取得');
                    }
                } else {
                    this.shitiTimeArr = null;
                    this.shitiTimeDoneArr = [];
                }
            },
            initPlayer() {
                if (this.hasInitPlayer) {
                    // do refresh
                    this.player.src(this.options.sources[0]);
                    this.maxPlayTime = 0;
                    this.maxPlayTimeRecord = 0;
                    return;
                }
                this.player = videojs(this.$refs.videoPlayer1, this.options, function onPlayerReady() {

                });


                this.player.on('play', () => {
                    if (!this.clonedOptions.progressControlEnable && this.clonedOptions.progressControlEnable === false) {
                        this.player.controlBar.progressControl.disable();
                    }
                    if (!this.doneTempFlg) {
                        this.displayQuestionByCurrentTime();
                    }

                    console.log(this.player.currentTime());
                    if (this.player.currentTime() === 0) {
                        // getTemp
                        let progressObj = getCourseProgress(this.duration);
                        this.maxPlayTime = progressObj.max;
                        let cur = this.duration - progressObj.cur < 20 ? 0 : progressObj.cur;
                        this.preTimeupdateTime = cur;
                        this.maxPlayTimeRecord = cur;
                        this.player.currentTime(cur);
                    }
                });

                this.player.on('loadedmetadata', () => {
                    this.duration = this.player.duration();
                });

                this.player.on('timeupdate', (event) => {
                    // console.log(this.preTimeupdateTime, this.player.currentTime(), this.clonedOptions.drugControl);

                    if (this.player.currentTime() - this.preTimeupdateTime > 0.6) { // 向后拖动
                        console.log(this.clonedOptions.drugControl);
                        if (this.clonedOptions.drugControl === 'forwardOnly') {
                            console.log('forwardOnly 2323');
                            if (this.player.currentTime() >= this.maxPlayTime) {
                                this.player.currentTime(this.maxPlayTime);
                            } else if (this.player.currentTime() < this.maxPlayTime) {
                                // default
                            } else {
                                this.player.currentTime(this.preTimeupdateTime);
                            }
                        }

                    } else if (this.preTimeupdateTime - this.player.currentTime() > 0) { // 向前拖动

                    } else { // 正常播放
                        this.maxPlayTime = this.preTimeupdateTime > this.maxPlayTime
                                           ? this.preTimeupdateTime
                                           : this.maxPlayTime;

                        // 每1分钟同步一下进度
                        if (this.maxPlayTime - this.maxPlayTimeRecord > 60 * 1) {
                            this.maxPlayTimeRecord = this.maxPlayTime;
                            // save course progress
                            saveCourseProgress(this.maxPlayTime, this.duration);
                            updateSectionProgress();
                        }

                        if (!this.doneTempFlg) {
                            this.displayQuestionByCurrentTime();
                        }
                    }
                    this.preTimeupdateTime = this.player.currentTime();

                });

                this.player.on('ended', () => {
                    videojs.log('播放结束了!');
                    // save to cache 课程 章 节 课件id 答案数组
                    saveCourseProgress(this.duration, this.duration);
                    updateSectionProgress();
                    this.$emit('sectionCompleted', true);
                });

                this.hasInitPlayer = true;
            },
            hidDialog() {
                if (this.dialogDisplay) {
                    this.dialogDisplay = false;
                    this.modalDialog.close();
                }
            },
        },
        beforeDestroy() {
            if (this.player) {
                this.player.dispose();
            }
        },
        watch:      {
            'options.playlist': {
                handler(newVal, oldVal) {
                    if (this.clonedOptions.hasPlaylist) {
                        this.initPlayer();
                        this.player.playlist(newVal);
                        // 延迟播放
                        this.player.playlist.autoadvance(5);
                        this.player.playlistUi();
                    }
                },
                immediate: false,
            },
            'options.sources':  {
                handler(newVal, oldVal) {
                    this.initPlayer();
                    this.initShiti();
                },
                immediate: false,
            },
        },
    };
</script>
<style lang="scss">
    .video-container {
        text-align: left;
        display: flex;
        width: 100%;

        .vjs-playlist {
            margin-left: 5px;
            width: 180px;
            flex-shrink: 0;

            .vjs-playlist-item {
                font-size: 12px;
                height: 95px;
            }
        }

        .vjs-play-control.vjs-control.vjs-button {
            outline-color: transparent;
        }

        .vjs-modal-dialog-content {
            margin: 0 auto;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #FFF;
        }

        /*.vjs-icon-hand {
            content:          "";
            display:          inline-block;
            width:            10px;
            height:           10px;
            background-color: rgba(132, 132, 132, 1);
            border-radius:    50%;
            margin-right:     8px;
        }*/

        /*.video-js .vjs-play-progress:before {
            top: -0.4em;
            background-color: red;
        }
        .video-js .vjs-play-progress:hover:before {
            top: -0.3333333333333333em;
            background-color: blue;
        }*/
        .video-main {
            position: relative;
            display: contents;

            .video-js {
                width: 100%;
            }
        }

    }

    #wxyDialog {
        width: 100%;
        height: 100%;
    }

    .dl-shiti {
        position: relative;
        width: 80%;
        margin: 15% auto auto auto;
    }

    .dl-btn {
        position: absolute;
        left: 48%;
        top: 90%;
        z-index: 500;
    }

</style>
