<template>
    <div>
        <div class="header_tab">
            <el-tabs v-model="activeName" @tab-click="tabChange" :before-leave="saveActive">
                <el-tab-pane label="首页" name="index">
                    
                </el-tab-pane>
                <el-tab-pane label="课前预习" name="first">
                    
                </el-tab-pane>
                <el-tab-pane label="练习模式" name="second">
                    
                </el-tab-pane>
                <el-tab-pane label="考核模式" name="third">
                    
                </el-tab-pane>
                <el-tab-pane label="实验记录" name="fourth">
                    
                </el-tab-pane>
            </el-tabs>
            <Index v-if="activeName=='index'"></Index>
            <TeachingVideo v-if="!showProject && activeName!='fourth' && activeName!='index'"></TeachingVideo>
            <Project v-if="showProject"></Project>
            <Record v-if="activeName=='fourth'"></Record>
        </div>

        <!-- 答题弹框 -->
        <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 Index from './Index';
import TeachingVideo from './TeachingVideo';
import Project from './Project';
import Record from './Record';
import bus from '../common/bus';
export default {
    name: 'dashboard',
    data() {
        return {
            name: sessionStorage.getItem('ms_username'),
            activeName: 'index',
            routeName: '#/dashboard',
            tabNameList: ['index','first','second','third','fourth'],
            userId: this.$store.state.userId,
            evaluationVisible: false,
            resultVisible: false,
            detailVisible: false,
            lastOne: false,
            question: {
                options: {}
            },
            countdown: '',
            selected: '',
            result: {},
            detail: {},
            timer: null,
            totalScore: 0,
            detailData: [],
            isDone: false,
            history: [],
            btnType: 1,
            showProject: false,
            lastClick: ''
        };
    },
    watch: {
        question: {
            handler(newVal,oldVal) {
                for(let n in newVal.options) {
                    if(newVal.options[n] == '') delete(newVal.options[n])
                }
            },
            deep: true
        }
    },
    mounted() {
        this.addDefault()
        this.$once('hook:beforeDestroy', function () {
            clearInterval(this.timer)
            this.timer = null
        })
        bus.$on('tabChange',(tab,isIndex) => {
            this.tabChange(tab,isIndex)
        })
    },
    components: {
        Index,
        TeachingVideo,
        Project,
        Record
    },
    methods: {
        tabChange(tab,isIndex){
            let index = tab.index
            if(index == 2){
                this.toEvaluation(1,2)
            }else if(index == 3){
                this.toEvaluation(1,3)
            }else{
                this.showProject = false
            }

            let hash = location.hash
            if(hash == this.routeName){
                location.hash = `${hash}#${index}`
            }else{
                location.hash = `${this.routeName}#${index}`
            }
            isIndex && this.addDefault(isIndex)
        },
        addDefault(isIndex){
            let hash = location.hash
            if(hash == this.routeName){
                location.hash = `${hash}#0`
            }else{
                let index = hash.replace(`${this.routeName}#`,'')
                this.activeName = this.tabNameList[index]

                if(index == 3 && !isIndex){
                    this.toEvaluation(1,3)
                }
            }
        },
        saveActive(activeName,oldActiveName){
            this.lastClick = oldActiveName
            if(activeName == 'second'){
                return false
            }
        },
        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.openExerciseOrTeaching, { userId: this.userId })
                }else{
                    res = await this.$get(this.api.openExerciseOrTeaching, { userId: this.userId })
                }
                if(res.errmessage == 'true'){
                    if(btn == 2){
                        this.core.toSubSystem()
                    }
                    if(btn == 3){
                        this.showProject = true
                    }
                }else{
                    this.activeName = this.lastClick
                    this.$alert('请先完成能力测评并达到80分以上才可以进行实验', '提示', {
                        confirmButtonText: '进入测评',
                        callback: action => {
                            if(action == 'confirm'){
                                this.toEvaluation(0)
                            }else{
                                // this.activeName = btn == 2 ? 'second' : 'third'
                            }
                        }
                    });
                }
            }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.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)
                }
            },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
            })
            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
                })
                if(res.data){
                    this.question = res.data
                    this.selected = this.history[this.question.currentQuestionSortNo-1]
                    this.handleQues()
                }
            }
        },
        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,
                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
            }
        },
        toSonSys() {
            if(this.btnType == 2){
                this.core.toSubSystem()
            }else if(this.btnType == 3){
                this.resultVisible = false
                this.activeName = 'third'
                this.showProject = true
            }
        }
    }
};
</script>
<style scoped>
/deep/.el-tabs__item:focus{
    outline: none;
    box-shadow: none !important;
}
h3{
    color: #328aff;
    margin-bottom: 10px;
}
.mar0{
    margin-top: 0;
}
/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;
}
</style>