<template>
    <div class="box">
        <el-page-header @back="core.goBack" ></el-page-header>
        <!-- 项目介绍与视频导航栏 -->
         <div class="nav_wrap">
            <div class="introduce" @click="toPreview">项目介绍</div>
            <div class="preview" >课前预习</div>
        </div>
        <!-- 视频区 -->
        <el-row :gutter="24">
            <el-col :span="18">
                <div>
                    <!-- <video controls class="video_wid">
                        <source :src="videoSrc">
                    </video> -->
                    <video ref="video" controls class="video_wid" :src="videoSrc" controlsList="nodownload"></video>
                    <p class="tips">备注：本课程资料是由电子科技大学李平教授和李强教授负责制作的《金融学基础》国家级精品课程中的期货期权部分。</p>
                </div>
            </el-col>
            <el-col :span="6">
                <div class="catalog">
                    <div class="btns mgb20">
                        <!-- <el-button type="primary" @click="toEvaluation(1,2)">虚拟仿真实验</el-button>
                        <el-button type="primary" @click="toEvaluation(1,3)">教学实验</el-button> -->
                        <el-button type="primary" @click="toEvaluation(0,2)"></el-button>
                    </div>
                    <div class="list_he">
                        <h4 class="list_title">学习资源</h4>
                        <div v-for="(item,index) in videoList" :key="index">
                            <div class="flex-between list_catalog">
                                <p class="experimental_title" :class="{active: curLink == item.title}" @click="play(item)">{{index + 1}}.{{item.title}}</p>
                            </div>
                        </div>
                    </div>
                </div>
            </el-col>
        </el-row>

        <!-- 答题弹框 -->
        <el-dialog :visible.sync="evaluationVisible" width="30%" custom-class="evaluation_dialog" center :close-on-click-modal="false">
            <div class="title">能力测评</div>

            <div class="content">
                <p class="serial">{{question.currentQuestionSortNo}}/{{question.totalQuestionNum}}</p>
                <p class="type">({{question.questionTypeName}})</p>
                <div class="ques">{{question.questionStem}}</div>
                <div class="countdown flex-center">
                    <img src="../../assets/img/hourglass.png" alt="">
                    <span>倒计时：{{countdown}}</span>
                </div>
                <ul class="options" :class="{isDone}">
                    <li v-for="(item,key) in question.options" :key="key" :class="{active: selected.includes(key)}" @click="selectOption(key)"><em>{{key}}.</em><span>{{item}}</span></li>
                </ul>
            </div>
            
            <div slot="footer" class="dialog-footer" v-if="!isDone">
                <template v-if="lastOne">
                    <el-button @click="prevQues">上一题</el-button>
                    <el-button type="primary" @click="submitQues">提交</el-button>
                </template>
                <template v-else>
                    <el-button class="first" @click="prevQues">上一题</el-button>
                    <el-button class="second" type="primary" @click="nextQues">下一题</el-button>
                </template>
            </div>
        </el-dialog>

        <!-- 提交成绩弹框 -->
        <el-dialog :visible.sync="resultVisible" width="30%" custom-class="result_dialog" center :close-on-click-modal="false">
            <div class="result"><span>{{result.isPassed}}</span></div>

            <div class="content">
                <div class="point">
                    <span>{{result.totalScore}}</span>分
                </div>
                <p class="tips">{{result.isPassed == '通过' ? '恭喜' : ''}}你答对{{result.correctQuestionNum}}题，正确率{{result.correctRate}}！</p>
            </div>
            
            <div slot="footer" class="dialog-footer">
                <el-button class="first" @click="toEvaluation(0)">再试一次</el-button>
                <el-button class="second" type="primary" @click="getDetail">成绩详情</el-button>
                <el-button v-if="result.isPassed == '通过'" class="third" type="primary" @click="toSonSys">进入实训</el-button>
            </div>
        </el-dialog>

        <!-- 成绩详情弹框 -->
        <el-dialog :visible.sync="detailVisible" width="30%" custom-class="detail_dialog" center :close-on-click-modal="false">
            <div class="title">成绩详情</div>
            <div style="min-height: 370px">
                <el-table
                    :data="detailData"
                    height="340"
                    border
                    style="width: 100%">
                    <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
                    <el-table-column prop="date" label="正误" min-width="45" align="center">
                        <template slot-scope="scope">
                            <img v-if="scope.row.questionScore" width="15" src="../../assets/img/true.png" alt="">
                            <img v-else width="15" src="../../assets/img/false.png" alt="">
                        </template>
                    </el-table-column>
                    <el-table-column prop="questionScore" label="得分" min-width="45" align="center"></el-table-column>
                    <el-table-column prop="answer" label="正确答案" min-width="70" align="center"></el-table-column>
                    <el-table-column prop="userAnswer" label="你的答案" min-width="70" align="center"></el-table-column>
                    <el-table-column prop="answerAnalysis" label="解析" min-width="80"></el-table-column>
                </el-table>
            </div>
            <p class="total">得分：{{totalScore}}分</p>
        </el-dialog>
    </div>
</template>

<script>
import { link } from 'fs';
import { mapState } from 'vuex';
export default {
    data() {
        return {
            video: 'http://liuwanr.oss-cn-shenzhen.aliyuncs.com/mp4/20200519/1589871025648.mp4',
            videoSrc: '',
            userId: this.$store.state.userId,
            videoList: [{
                "id": 1,
                "links": "https://huoran.oss-cn-shenzhen.aliyuncs.com/video/technology/期权交易概述.mp4",
                "isdel": 0,
                "title": "期权交易概述"
            }, {
                "id": 3,
                "links": "https://huoran.oss-cn-shenzhen.aliyuncs.com/video/technology/期权交易策略.mp4",
                "isdel": 0,
                "title": "期权交易策略"
            },{
                "id": 1,
                "links": "https://huoran.oss-cn-shenzhen.aliyuncs.com/20201209/mp4/1336580023842791424.mp4",
                "isdel": 0,
                "title": "期货-现货平价关系"
            }, {
                "id": 3,
                "links": "https://huoran.oss-cn-shenzhen.aliyuncs.com/20201209/mp4/1336581691573559296.mp4",
                "isdel": 0,
                "title": "期货的套期保值"
            }, {
                "id": 6,
                "links": "https://huoran.oss-cn-shenzhen.aliyuncs.com/20201209/mp4/1336598531863502848.mp4",
                "isdel": 0,
                "title": "期货投机与杠杆交易"
            }, {
                "id": 5,
                "links": "https://huoran.oss-cn-shenzhen.aliyuncs.com/20201209/mp4/1336581832917409792.mp4",
                "isdel": 0,
                "title": "期权的价格特征"
            }, {
                "id": 2,
                "links": "https://huoran.oss-cn-shenzhen.aliyuncs.com/20201209/mp4/1336598228112007168.mp4",
                "isdel": 0,
                "title": "看涨-看跌期权平价关系"
            }, {
                "id": 7,
                "links": "https://huoran.oss-cn-shenzhen.aliyuncs.com/20201209/mp4/1336581976211611648.mp4",
                "isdel": 0,
                "title": "二项式/二叉树期权定价模型"
            }, {
                "id": 4,
                "links": "https://huoran.oss-cn-shenzhen.aliyuncs.com/20201209/mp4/1336598396169379840.mp4",
                "isdel": 0,
                "title": "两阶段（两步）二项式期权定价"
            }, {
                "id": 9,
                "links": "https://huoran.oss-cn-shenzhen.aliyuncs.com/20201209/mp4/1336582100195237888.mp4",
                "isdel": 0,
                "title": "杠杆企业的期权特征（或有权益分析）"
            }],
            evaluationVisible: false,
            resultVisible: false,
            detailVisible: false,
            lastOne: false,
            question: {
                options: {}
            },
            countdown: '',
            selected: '',
            result: {},
            detail: {},
            timer: null,
            totalScore: 0,
            detailData: [],
            isDone: false,
            history: [],
            btnType: 1,
            curLink: ''
        };
    },
    computed: {
        ...mapState({
            courseId: state => state.courseId,
            classId: state => state.classId,
        }),
    },
    watch: {
        question: {
            handler(newVal,oldVal) {
                for(let n in newVal.options) {
                    if(newVal.options[n] == '') delete(newVal.options[n])
                }
            },
            deep: true
        }
    },
    mounted() {
        // this.getData()
        this.play(this.videoList[0])
        this.$once('hook:beforeDestroy', function () {
            clearInterval(this.timer)
            this.timer = null
        })
    },
    methods: {
        toPreview(){
            this.$router.push(`ProjectIntro`)
        },
        async getData(){
            let res = await this.$get(this.api.getCoursevideo, { 
                page: 1,
                size: 10
            })
            this.videoList = res.data.list
        },
        async toEvaluation(type,btn) {
            clearInterval(this.timer)
            this.lastOne = false
            this.selected = ''
            this.resultVisible = false
            this.history = []
            if(btn) this.btnType = btn
            if(type){
                let res = null
                if(btn == 2){
                    res = await this.$get(this.api.openExercise, { userId: this.userId })
                }else{
                    res = await this.$get(this.api.openTeaching, { userId: this.userId })
                }
                if(res.errmessage == 'true'){
                    if(btn == 2){
                        location.href = this.$config.subSystem
                    }
                    if(btn == 3){
                        this.$router.push('/project')
                    }
                }else{
                    this.$alert('请先完成能力测评并达到80分以上才可以进行实验', '提示', {
                        confirmButtonText: '进入测评',
                        callback: action => {
                            action == 'confirm' && this.toEvaluation(0)
                        }
                    });
                }
            }else{
                this.start()
                this.getCountdown()
            }
        },
        handleQues() {
            this.question.options = {}
            for(let n in this.question) {
                if(n.includes('option') && n != 'options') {
                    this.question.options[n.replace('option','')] = this.question[n]
                }
            }
            if(this.question.currentQuestionSortNo == this.question.totalQuestionNum){
                this.lastOne = true
            }else{
                this.lastOne = false
            }
        },
        async start() {
            let res = await this.$get(this.api.experimentStart, { userId: this.userId,types: this.btnType })
            if(res.data){
                this.question = res.data
                this.isDone = false
                this.question.currentQuestionSortNo == 1 && this.$store.commit("answerHistoryData", { answerHistory : []})
                this.handleQues()
                this.$refs.video.pause()
                this.evaluationVisible = true
            }else{
                this.$message.warning(res.message)
            }
        },
        async getCountdown() {
            let res = await this.$get(this.api.experimentRemaining, { userId: this.userId })
            res.data && this.countDown(res.data)
            // this.countDown('00:00:05')
        },
        countDown(time) {
            this.countdown = time
            this.timer = setInterval(() => {
                let timeList = this.countdown.split(':')
                let total = Number.parseInt(timeList[1] * 60) + Number.parseInt(timeList[2])
                if(total > 0){
                    --total
                    let minutes = Math.floor(total / 60)
                    let seconds = Math.floor(total % 60)
                    this.countdown = `00:${this.core.formateTime(minutes)}:${this.core.formateTime(seconds)}`
                }else{
                    this.isDone = true
                    this.$message.warning('测评时间结束');
                    clearInterval(this.timer)
                    this.prevQues()
                }
            },1000)
        },
        selectOption(option) {
            if(!this.isDone) {
                if(this.selected.includes(option)) {
                    this.selected = this.selected.replace(option,'')
                }else{
                    if(this.question.questionType == 2) {
                        this.selected += option
                    }else{
                        this.selected = option
                    }
                }
            }
        },
        getHistory() {
            this.history = this.$store.state.answerHistory
        },
        async nextQues() {
            if(!this.selected) return this.$message.warning('请选择答案')
            this.getHistory()
            if(this.history.length > this.question.currentQuestionSortNo){
                this.history[this.question.currentQuestionSortNo-1] = this.selected
            }else if(this.history.length < this.question.currentQuestionSortNo){
                this.history.push(this.selected)
            }
            this.$store.commit("answerHistoryData", { answerHistory : this.history})
            let res = await this.$post(this.api.experimentNext, { 
                id: this.question.id,
                currentQuestionSortNo: this.question.currentQuestionSortNo,
                // userAnswer: this.selected.split('').sort().join(',')
                userAnswer: this.selected
            })
            if(res.data){
                this.question = res.data
                this.selected = ''
                if(this.history.length >= this.question.currentQuestionSortNo){
                    this.selected = this.history[this.question.currentQuestionSortNo-1]
                }else{
                    this.selected = ''
                }
                this.handleQues()
            }
        },
        async prevQues() {
            if(this.question.currentQuestionSortNo > 1){
                this.getHistory()
                let res = await this.$post(this.api.experimentPrevious, { 
                    id: this.question.id,
                    currentQuestionSortNo: this.question.currentQuestionSortNo,
                    // userAnswer: this.selected.split('').sort().join(',')
                    userAnswer: this.selected
                })
                if(res.data){
                    this.question = res.data
                    this.selected = this.history[this.question.currentQuestionSortNo-1]
                    this.isDone ? this.submitQues() : this.handleQues()
                }
            }else if(this.isDone){
                if(!this.selected) this.selected = 'A'
                this.submitQues()
            }
        },
        async submitQues() {
            if(!this.selected) return this.$message.warning('请选择答案');
            let res = await this.$post(this.api.experimentSubmit, { 
                id: this.question.id,
                currentQuestionSortNo: this.question.currentQuestionSortNo,
                // userAnswer: this.selected.split('').sort().join(','),
                userAnswer: this.selected,
                userId: this.userId,
                types: this.btnType
            })
            if(res.data) {
                this.result = res.data
                this.evaluationVisible = false
                this.resultVisible = true
            }
        },
        async getDetail() {
            let res = await this.$get(this.api.experimentDetail, { 
                evaluationRecordId: this.question.id
            })
            if(res.data){
                this.totalScore = res.data.totalScore
                this.detailData = res.data.evaluationDetailVOS
                this.resultVisible = false
                this.detailVisible = true
            }
        },
        play(row) {
            this.curLink = row.title
            let links = row.links
            if(links.endsWith('.mp4') || links.endsWith('.rmvb') || links.endsWith('.avi')){
                this.videoSrc = links
            }
        },
        toPython(item) {
            this.setCookie('staffId', this.$store.state.staffId);
            this.setCookie('projectId', item.projectId);
            this.setCookie('courseId', this.courseId);
            window.location.href = 'http://www.occupationlab.com/pythonview/';
        },
        toSonSys() {
            location.href = this.$config.subSystem
        }
    }
};
</script>

<style lang="scss" scoped>
.box{
    height: calc(100vh - 60px);
    padding: 20px;
    background: url(../../assets/img/eva-bg.jpg) 0 0/100% 100% no-repeat;
    overflow: auto;
}
.back_index:hover{
    opacity: 0.8;
    cursor: pointer;
}
.nav_wrap{
    height: 50px;
    display: flex;
    justify-content: center;
    color: white;
    margin-bottom: 20px;
    .introduce{
        background: #004590;
    }
    div:hover{
        opacity: 0.8;
    }
    div{
        width: 200px;
        line-height: 50px;
        text-align: center;
        font-size: 26px;
        cursor: pointer;
    }
    .preview{
        background: #FF5288;
    }
}
.video_wid{
    width: 100%;
    height: 650px;
    border: 0;
}
.video_wid:focus{
    outline: none;
}
.title_view{
    background-color: #2F3236;
    padding: 12px 10px;
}
h3{
    color: #9076FF;
    margin-bottom: 10px;
}
.catalog .title_view .el-button{
    padding: 8px 20px;
}
.btns{
    display: flex;
    justify-content: space-between;
}
.btns .el-button{
    flex: 1;
    height: 90px;
    font-size: 30px;
    background: transparent url(../../assets/img/ques1.png) 0 0/100% 100% no-repeat;
    border: 0;
}
.list_he{
    height: 540px;
    overflow-y: scroll;
    padding: 20px 12px;
    background: #3f4449;
}
.list_he::-webkit-scrollbar {
    width: 4px;
}
.list_he::-webkit-scrollbar-thumb {
    border-radius: 10px;
    -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: #328aff;
}
.list_he::-webkit-scrollbar-track {
    -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    border-radius: 0;
    background: rgba(0, 0, 0, 0.1);
}
.list_he ul{
    padding: 20px 0;
}
.list_he ul li:first-child{
    margin-top: 0;
}
.list_he ul li{
    margin-top: 10px;
    font-size: 14px;
}
.list_title{
    color: #328aff;
    font-size: 20px;
    margin-left: 12px;
}
.list_catalog{
    padding: 0 8px;
    font-size: 14px;
    /* background-color: #2F3236; */
    margin-top: 15px;
    cursor: pointer;
}
.mar0{
    margin-top: 0;
}
.list_catalog .catalog_button .el-button{
    background-color: #2F3236;
    border:1px solid rgba(144,118,255,1);
    color: #328aff;
    padding: 6px 8px;
}
.experimental_title{
    color: #fff;
    word-wrap: break-word;
    &.active{
        color: #328aff;
    }
}
.experimental_status{
    margin-right: 10px;
    color: #7A7A7A;
}
.curriculum_name{
    color: #fff;
}
.curriculum_name i{
    margin-left: 5px;
    margin-right: 5px;
}
.curriculum_status{
    color: #7A7A7A;
}
/deep/.evaluation_dialog{
    min-height: 700px;
    background: url(../../assets/img/evaluation_bg1.png) 0 0/100% 100% no-repeat;
}
/deep/.evaluation_dialog .el-dialog__headerbtn,/deep/.evaluation_dialog .el-dialog__headerbtn,/deep/.detail_dialog .el-dialog__headerbtn{
    font-size: 28px;
}
/deep/.evaluation_dialog .title,/deep/.detail_dialog .title{
    margin-bottom: 45px;
    text-align: center;
    font-size: 24px
}
/deep/.evaluation_dialog .title{
    margin-bottom: 55px;
}
/deep/.evaluation_dialog .serial{
    font-size: 12px;
    text-align: center;
}
/deep/.evaluation_dialog .content{
    width: 80%;
    margin: 0 auto;
}
/deep/.evaluation_dialog .type{
    color: #666;
}
/deep/.evaluation_dialog .ques{
    margin: 20px 0;
    min-height: 145px;
    color: #666;
    font-size: 16px;
}
/deep/.evaluation_dialog .countdown{
    margin-bottom: 20px;
    justify-content: center;
    text-align: center;
    color: #DC3434;
    font-size: 14px;
}
/deep/.evaluation_dialog .countdown img{
    width: 15px !important;
    margin-right: 10px;
}
/deep/.evaluation_dialog .options{
    display: flex;
    flex-direction: column;
    min-height: 340px;
}
/deep/.evaluation_dialog .options.isDone{
    min-height: 395px;
}
/deep/.evaluation_dialog .options li{
    padding: 0 15px;
    margin-bottom: 15px;
    line-height: 40px;
    border: 1px solid #9070FF;
    border-radius: 20px;
    color: #666;
    cursor: pointer;
}
/deep/.evaluation_dialog .options li:hover{
    color: #fff;
    background-color: #b038bb;
    border-color: #b038bb;
}
/deep/.evaluation_dialog .options li.active{
    color: #fff;
    background-color: #916CFF;
    border-color: #916CFF;
}
/deep/.evaluation_dialog .options em{
    margin-right: 10px;
    font-weight: bold;
    font-style: normal;
    font-size: 16px;
}
/deep/.evaluation_dialog .options span{
    font-size: 16px;
}
/deep/.evaluation_dialog .el-dialog__footer{
    text-align: center;
}
/deep/.evaluation_dialog .first,/deep/.result_dialog .first{
    color: #fff;
    background-color: #9268FF;
    border-color: #9268FF;
}
/deep/.evaluation_dialog .second,/deep/.result_dialog .second{
    color: #fff;
    background-color: #E371DA;
    border-color: #E371DA;
}

/deep/.result_dialog{
    min-height: 500px;
    background: url(../../assets/img/evaluation_bg2.png) 0 0/100% 100% no-repeat;
}
/deep/.result_dialog .el-dialog__headerbtn .el-dialog__close{
    color: #5a5a5a;
    font-size: 28px;
}
/deep/.result_dialog .result{
    margin-top: 60px;
    text-align: center;
    color: #fff;
    font-size: 24px;
}
/deep/.result_dialog .point{
    margin: 30px 0 20px;
    text-align: center;
    font-size: 30px;
    color: #666;
}
/deep/.result_dialog .point span{
    font-size: 120px;
    font-weight: bold;
}
/deep/.result_dialog .tips{
    color: #666;
    text-align: center;
    font-size: 14px;
}
/deep/.result_dialog .third{
    color: #fff;
    background-color: #418cf5;
    border-color: #418cf5;
}

/deep/.detail_dialog{
    background: url(../../assets/img/evaluation_bg3.png) 0 0/100% 100% no-repeat;
}
/deep/.detail_dialog .title{
    margin-top: -20px;
}
/deep/.detail_dialog .el-table__header th:nth-last-child(2){
    text-align: center;
}
/deep/.detail_dialog .total{
    margin-top: 20px;
    text-align: center;
    font-size: 30px;
    color: #DC3434;
}
/deep/.evaluation_dialog{
    margin:0 !important;
    position:absolute;
    top:50%;
    left:50%;
    transform:translate(-50%,-50%);
    max-height:calc(100% - 30px);
    max-width:calc(100% - 30px);
}
/deep/.evaluation_dialog .el-dialog__body{
    flex:1;
    overflow: auto;
}
.tips{
    margin-top: 5px;
    font-size: 12px;
    color: #fff;
}
</style>