<template>
    <div class="lesson-test-pop">
        <!-- <loading :active.sync="isLoading"
                 :is-full-page="fullPage"
                 background-color="#000"
                 :opacity="opacity">
            <template slot="default">
                <svg-icon icon-class="loader" class="loader-icon" />
            </template>
        </loading> -->
        <Loading v-show="isLoading" bgColor="rgba(0, 0, 0, 0.3)"></Loading>
        <div v-if="WarmMessageisOpen" class="warmMessage">
            <div class="messageCard">
                <!---中途離開測驗之提示框---->
                <div class="messageCardContent1" v-if="showMessageNum == 1">
                    <h3>{{$t("studentWeb.exam.testpop.exitQuizhint")}}</h3>
                    <svg-icon icon-class="logoutComfirm" class="logoutComfirmIcon" />
                    <br />
                    <p v-show="closeTest">
                        {{$t("studentWeb.exam.testpop.exitQuizhintDe")}}
                        <br /> {{$t("studentWeb.exam.testpop.exitQuizhintDes")}}
                    </p>
                    <button class="messageCardBtn" @click="closeWarmMessage()">{{$t("studentWeb.exam.testpop.cancel")}}</button>
                    <button class="messageCardBtn" @click="quitTest()">{{$t("studentWeb.exam.testpop.ok")}}</button>
                </div>
                <!---每題都完成到最後一題交卷之提示框---->
                <div class="messageCardContent2" v-if="showMessageNum == 2">
                    <h3>{{$t("studentWeb.exam.testpop.submitQuizhint")}}</h3>
                    <svg-icon icon-class="finshedTest" class="handOnImg" />
                    <p>{{$t("studentWeb.exam.testpop.submitQuizhintDes1")}}</p>
                    <button class="messageCardBtn" @click="closeWarmMessage()">{{$t("studentWeb.exam.testpop.check")}}</button>
                    <button class="messageCardBtn" @click="closetest()">{{$t("studentWeb.exam.testpop.okSubmit")}}</button>
                </div>
                <!---有題目沒完成就交卷之提示框---->
                <div class="messageCardContent3" v-if="showMessageNum == 3">
                    <h3>{{$t("studentWeb.exam.testpop.submitQuizhint")}}</h3>
                    <svg-icon icon-class="unfinishedTest" class="handOnImg" />
                    <p>
                        {{$t("studentWeb.exam.testpop.conAnswer0")}}
                        <span style="color:rgb(250, 100, 0);font-weight:900">{{ undo }}{{$t("studentWeb.exam.testpop.conAnswer1")}}</span>{{$t("studentWeb.exam.testpop.conAnswer2")}}
                    </p>
                    <button class="messageCardBtn" @click="closeWarmMessage()">{{$t("studentWeb.exam.testpop.conAnswer")}}</button>
                    <button class="messageCardBtn" @click="closetest()">{{$t("studentWeb.exam.testpop.okSubmit")}}</button>
                </div>
                <!-- 离开错题练习之提示框 -->
                <div class="messageCardContent1" v-if="showMessageNum == 4">
                    <h3>{{$t("studentWeb.exam.testpop.exitWrong")}}</h3>
                    <svg-icon icon-class="logoutComfirm" class="logoutComfirmIcon" />
                    <br />
                    <p v-show="closeTest">
                        {{$t("studentWeb.exam.testpop.exitWrongDe")}}
                        <br /> {{$t("studentWeb.exam.testpop.exitWrongDes")}}
                    </p>
                    <button class="messageCardBtn" @click="closeWarmMessage()">{{$t("studentWeb.exam.testpop.cancel")}}</button>
                    <button class="messageCardBtn" @click="quitTest()">{{$t("studentWeb.exam.testpop.ok")}}</button>
                </div>
                <!-- 结束练习之提示框 -->
                <div class="messageCardContent1" v-if="showMessageNum == 5">
                    <h3>{{$t("studentWeb.exam.testpop.endPractice")}}</h3>
                    <svg-icon icon-class="logoutComfirm" class="logoutComfirmIcon" />
                    <br />
                    <p v-show="closeTest">
                        <span>答对：{{ this.rigAns }}</span>
                        <span style="margin-left: 30px; color: #ff651f">答错：{{ this.wrgAns }}</span>
                        <br />
                        <span style="color: #b7b7b7">未评分：{{ this.noAns }}</span>
                        <span style="margin-left: 30px; color: #FA6400; font-weight: 900">未答题：{{ this.noCheck }}</span>
                        <br />
                        {{$t("studentWeb.exam.testpop.endPracticeDe")}}
                        <!-- <br /> {{$t("studentWeb.exam.testpop.exitWrongDes")}} -->
                    </p>
                    <button class="messageCardBtn" @click="closeWarmMessage()">{{$t("studentWeb.exam.testpop.endPracticeBtn1")}}</button>
                    <button class="messageCardBtn" @click="quitTest()">{{$t("studentWeb.exam.testpop.endPracticeBtn2")}}</button>
                </div>
            </div>
        </div>

        <div class="testTitle">
            <span class="logoutIcon" @click="openWarmMessage(1)">
                <svg-icon icon-class="logout" />
            </span>
            <span class="testTitleText">{{$t("studentWeb.home.exam")}}：{{ getItemTitle.name }}</span>
            <div v-if="!isWrong">
                <div class="myTestProgresstitle" :style="{'right': $store.getters.getCurrentLaguage == 'en-us' ? '-69%' : '-74%'}">{{$t("studentWeb.exam.testpop.completion")}}</div>
                <div class="myProgressBar">
                    <Progress style="margin-top:15px" :percent="completeRate" />
                </div>
            </div>
            <button v-if="closeTest" class="submitBtn" @click="openWarmMessage(isWrong ? 5 : 2)" :class="{ hintClick: hintHandon() }">{{isWrong ? $t("studentWeb.exam.testpop.submitted1") : $t("studentWeb.exam.testpop.submitted")}}</button>
            <button v-if="!closeTest" class="submitBtn" :class="{ hintClick: hintHandon()}">{{$t("studentWeb.exam.testpop.finish")}}</button>
        </div>
        <Row :gutter="30">
            <!-- 题干 -->
            <i-col class="questionArea"
                   :xs="24"
                   :sm="24"
                   :md="18"
                   :lg="20">
                <div class="questionContent" ref="questionBox">
                    <!-- <span class="hintwrap">
                        <Tooltip :content="$t('studentWeb.exam.report.noSource')" theme="light" placement="left">
                            <span class="hintIcon">
                                <svg-icon icon-class="hint" />
                            </span>
                        </Tooltip>
                    </span> -->
                    <div class="questioDes">
                        <div class="questionType" v-if="!getQue(queNo).parent">
                            <span>{{getTestType(getQue(queNo).type)}}</span>
                        </div>
                        <div class="que-item" v-if="getQue(queNo).type != 'compose' && !getQue(queNo).parent">
                            <span>{{ queNo + 1 }}.</span>
                            <!--题目渲染-->
                            <div id="answer-box" v-html="getQue(queNo).question"></div>
                        </div>
                        <!--综合题-->
                        <div v-if="getQue(queNo).type == 'compose' || getQue(queNo).parent">
                            <div class="compose-content" v-if="getQue(queNo).parent">
                                <div class="questionType">
                                    <span>{{getTestType(getQue(queNo).parentInfo.type)}}</span>
                                </div>
                                <div class="compose-box">
                                    <span style="margin-left:10px;font-weight:800;font-size:15px">{{$t("studentWeb.exam.testpop.queNo")}}</span>
                                    <br />
                                    <div class="compose-item">
                                        <!--<span w>{{ getQue(queNo).parent + 1}}.</span>-->
                                        <!--题干渲染-->
                                        <div v-html="getQue(queNo).parentInfo.question"></div>
                                    </div>
                                </div>
                                <div class="que-content">
                                    <span style="width:51px">{{ getQue(queNo).paperIndex}}:</span>
                                    <!--题目渲染-->
                                    <div class="que-items" id="answer-box" v-html="getQue(queNo).question"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="answers">
                        <div class="questionNo">{{$t("studentWeb.exam.testpop.myAns")}}</div>
                        <div class="answers-box">
                            <!--问答题-->
                            <div class="compose-content" v-if="getQue(queNo).type != 'judge' && getQue(queNo).type != 'single'  && getQue(queNo).type != 'multiple'">
                                <Compose ref="compose" :itemInfo="getQue(queNo)" :close="!closeTest" :textData="checkers[queNo]" :index="queNo" @dataGet="getComposeAns"></Compose>
                            </div>
                            <!--判断题选项-->
                            <div v-if="getQue(queNo).type == 'judge'" align="center">
                                <!-- <div class="testButn">
                                    <Radio-group v-model="checkers[queNo][0]">
                                        <Radio label="A"><Icon type="md-checkmark" /></Radio>
                                        <Radio label="B"><Icon type="md-close" /></Radio>
                                    </Radio-group>
                                </div> -->
                                <label class="testBtn yesNoBtn">
                                    <input type="radio" value="A" v-model="checkers[queNo][0]" :disabled="!closeTest" />
                                    <div class="testbg">
                                        <Icon type="ios-radio-button-off" />
                                    </div>
                                </label>
                                <label class="testBtn yesNoBtn">
                                    <input type="radio" value="B" v-model="checkers[queNo][0]" :disabled="!closeTest" />
                                    <div class="testbg">
                                        <Icon type="md-close" />
                                    </div>
                                </label>
                            </div>
                            <!--选择题选项-->
                            <div class="select-box" v-if="getQue(queNo).type != 'judge'">
                                <label class="testBtn"
                                       v-for="(item, index) in getQue(queNo).option"
                                       :key="index">
                                    <input type="checkbox"
                                           :value="getQue(queNo).option[index].code"
                                           v-model="checkers[queNo]"
                                           @click="getAns(queNo,index)"
                                           :disabled="!closeTest" />
                                    <div class="testbg">
                                        <div style="display:flex">
                                            <span>{{ getQue(queNo).option[index].code }}.</span>
                                            <div v-html="item.value" @click="showImg($event)"></div>
                                        </div>
                                        <div style="clear:both"></div>
                                    </div>
                                </label>
                            </div>
                        </div>
                    </div>
                    <!-- <div :style="isCheckAns ? 'height: 250px' : ''"></div> -->
                    <!-- 答案解析 -->
                    <div v-if="isWrong" :class="['analysis', isCheckAns && checkers[queNo].length > 0 ? 'active' : '']">
                        <div>
                            <div class="questionNo">{{$t("studentWeb.exam.report.ansRes")}}</div>
                            <div v-for="(item, index) in checkers[queNo]" :key="index" v-html="item"></div>
                        </div>
                        <div>
                            <div class="questionNo">{{$t("studentWeb.exam.report.testAns")}}</div>
                            <div v-for="(item, index) in examInfo[queNo].answer" :key="index" v-html="item"></div>
                        </div>
                        <div>
                            <div class="questionNo">{{$t("studentWeb.exam.report.testAnalyse")}}</div>
                            <div v-html="examInfo[queNo].explain != '' ? examInfo[queNo].explain : $t('studentWeb.exam.report.noAnalyse')"></div>
                        </div>
                        <div>
                            <div class="questionNo">{{$t("studentWeb.exam.report.repairSource")}}</div>
                            <div v-if="examInfo[queNo].repair.length != 0">
                                <Collapse style="width:85%" accordion>
                                    <!-- 网络资源 -->
                                    <Panel name="1">
                                        {{$t("studentWeb.exam.report.linkSource")}}
                                        <p slot="content">
                                            <List border size="small">
                                                <ListItem v-for="(item, normalIndex) in repairSource.normal" :key="normalIndex">
                                                    <span style="margin-right: 10px;" v-show="item.blobUrl">
                                                        <Icon color="#0066FF" custom="iconfont icon-share_link" size="20" />
                                                    </span><a :href="item.blobUrl" target="_blank">{{item.name}}</a>
                                                </ListItem>
                                                <ListItem v-show="!repairSource.normal.length">
                                                    <span>{{$t("studentWeb.exam.report.noSource")}}</span>
                                                </ListItem>
                                            </List>
                                        </p>
                                    </Panel>
                                    <!-- 文件资源 -->
                                    <Panel name="2">
                                        {{$t("studentWeb.exam.report.fileSource")}}
                                        <p slot="content">
                                            <List border size="small">
                                                <ListItem v-for="(item, fileIndex) in repairSource.file" :key="fileIndex">
                                                    <div style="width:100%">
                                                        <span style="margin-right:10px;">
                                                            <Icon v-if="item.fileType == 'zip'" custom="iconfont icon-zip" size="20" />
                                                            <!-- <Icon v-else-if="item.fileType == 'zip'" color="#8199AF" custom="iconfont icon-zip" size="20" /> -->
                                                            <Icon v-else-if="item.fileType == 'pdf'" color="#FF6464" custom="iconfont icon-pdf" size="20" />
                                                            <Icon v-else-if="item.fileType == 'ppt'|| item.fileType == 'pptx'" color="#FF8976" custom="iconfont icon-ppt" size="20" />
                                                            <Icon v-else-if="item.fileType == 'mp3'" color="#FF5562" custom="iconfont icon-mp3" size="20" />
                                                            <Icon v-else-if="item.fileType == 'mp4'" color="#8E4C9E" custom="iconfont icon-video1" size="20" />
                                                            <!-- <Icon v-else-if="item.fileType == 'zip'" custom="iconfont icon-video1" size="20" /> -->
                                                            <Icon v-else-if="item.fileType == 'doc'||item.fileType =='docx'" color="#6CCBFF" custom="iconfont icon-word" size="20" />
                                                            <Icon v-else-if="item.fileType == 'csv'||item.fileType =='xlsx'||item.fileType =='xls'" color="#25C273" custom="iconfont icon-xlsx" size="20" />
                                                            <Icon v-else-if="item.fileType == 'jpg'||item.fileType =='png'||item.fileType =='jpeg'" color="#30D1CA" custom="iconfont icon-jpg" size="20" />
                                                            <Icon v-else custom="iconfont icon-V" size="20" />
                                                        </span><a @click="getItemData(item)">{{item.name}}</a>
                                                        <span style="display:block;float:right;cursor:pointer">
                                                            <Icon type="md-download" size="18" @click="downloadFile(item)" />
                                                        </span>
                                                    </div>
                                                </ListItem>
                                                <ListItem v-show="!repairSource.file.length">
                                                    <span>{{$t("studentWeb.exam.report.noSource")}}</span>
                                                </ListItem>
                                            </List>
                                        </p>
                                    </Panel>
                                </Collapse>
                            </div>
                            <div v-else-if="!examInfo[queNo].repair.length">
                                {{ $t('studentWeb.exam.report.noSource') }}
                            </div>
                        </div>
                    </div>
                </div>
            </i-col>
            <!--答题卡-->
            <i-col class="ansArea"
                   :xs="24"
                   :sm="12"
                   :md="6"
                   :lg="4">
                <div style="margin-top: 30px; font-weight: 800">{{$t("studentWeb.exam.testpop.myAnswerSheet")}}</div>
                <!--切換頁-->
                <div class="pageCtl2">
                    <button @click="preQ()" :disabled="!queNo" :class="{disable: !queNo}">
                        <Icon type="ios-arrow-back" />{{$t("studentWeb.exam.testpop.previous")}}
                    </button>
                    <button @click="changeAnalysisType(true)"
                            v-if="isWrong"
                            :disabled="!checkers[queNo].length > 0"
                            :class="checkers[queNo] == '' ? 'disable' : ''"
                    >
                        {{$t("studentWeb.exam.testpop.showAns")}}
                    </button>
                    <button @click="nextQ()"
                            :disabled="queNo == (examInfo.length-1)"
                            :class="{ hintClick:queNo != (examInfo.length-1) && checkers[queNo] != '',disable: queNo == (examInfo.length-1)}">
                        {{$t("studentWeb.exam.testpop.next")}}
                        <Icon type="ios-arrow-forward" />
                    </button>
                </div>
                <div class="checkAnswer">
                    <!-- <br />
                    <br /> -->
                    <span style="margin-top:10px;font-weight:800">{{$t("studentWeb.exam.testpop.qNo")}}</span>
                    <div class="que-box">
                        <div v-for="(item,index) in examInfo" :key="index"
                             @click="gototheQues(index +1)"
                             class="ans-box"
                             :class="getClassName(index)">
                            <span style="padding:5px 5px;cursor:pointer"> {{ !item.parent ? index + 1 : item.paperIndex }}</span>
                        </div>
                    </div>
                </div>
                
            </i-col>
        </Row>
        <!--图片放大显示-->
        <div class="imgDolg"
             v-show="imgPreview.show"
             @click.stop="imgPreview.show = false">
            <i class="el-icon-close"
               id="imgDolgClose"
               @click.stop="imgPreview.show = false"></i>
            <img @click.stop="imgPreview.show = true" :src="imgPreview.img" />
        </div>
        <!-- 补救资源 -->
        <Modal v-model="previewStatus" footer-hide width="65%" @on-cancel="closePreview">
            <p slot="header" 
               style="color:#f60;text-align:center">
                <Icon type="ios-information-circle"></Icon>
                <span>{{$t("studentWeb.exam.report.fileView")}}</span>
            </p>
            <div class="file-box" v-if="previewStatus">
                <video v-if="previewFile.file == 'video'"
                       id="previewVideo"
                       :src="previewFile.blobUrl"
                       width="870"
                       controls="controls"
                       style="max-height: 800px;">
                    {{$t('teachContent.tips8')}}
                </video>
                <audio v-else-if="previewFile.file == 'audio'" controls>
                    <source :src="previewFile.blobUrl">
                </audio>
                <img v-else-if="previewFile.fileType == 'jpg'||previewFile.fileType =='png'||previewFile.fileType =='jpeg' "
                     :src="previewFile.blobUrl"
                     style="border-radius: 5px;max-height: 800px;max-width:870px;" />
                <pdf ref="pdf"
                     v-else-if="previewFile.fileType == 'pdf'"
                     v-for="(page,index) in numPages"
                     :key="index"
                     :src="previewFile.blobUrl"
                     :page="page"></pdf>
                <!--<span v-else-if="previewFile.fileType == 'doc'||previewFile.fileType == 'csv'||previewFile.fileType == 'pptx' ">{{'https://view.officeapps.live.com/op/view.aspx?src=' + previewFile.blobUrl}}</span>-->
                <iframe v-else-if="previewFile.fileType == 'doc'||previewFile.fileType == 'csv'||previewFile.fileType == 'pptx'||previewFile.fileType == 'xls' " :src="'https://view.officeapps.live.com/op/view.aspx?src=' + previewFile.blobUrl" width='870' height='700' frameborder='1'></iframe>
                <span v-else>{{$t("studentWeb.exam.report.noReview")}}</span>
            </div>
        </Modal>
    </div>
</template>

<script>
    import pdf from 'vue-pdf'
    /* import Loading from "vue-loading-overlay";
    import "vue-loading-overlay/dist/vue-loading.css"; */
    import Loading from '@/common/Loading.vue'
    import Compose from './composePaper.vue'
    import Complete from './completePaper.vue'
    import { mapGetters } from 'vuex';
    export default {
        name: "PaperTest",
        components: {
            Loading,
            Compose,
            Complete,
            pdf
        },
        created() {
            this.WarmMessageisOpen = false;
            this.showMessageNum = 0;
            // this.papers = this.$route.params.papers
            if(!Object.keys(this.getItemTitle).length) {
                this.$store.commit("ChangeItemName", JSON.parse(localStorage.getItem("Item")));
                this.$store.commit("setUserInfo", JSON.parse(localStorage.getItem("userInfo")));
                this.$store.commit("SetExamInfo", JSON.parse(localStorage.getItem("examInfo")));
                this.$store.commit("SetPaperInfo", JSON.parse(localStorage.getItem("paperInfo")));
                this.$store.commit("ToggleLessonTestPopWithSubject", JSON.parse(localStorage.getItem("subjectNow")));
            }
        },
        mounted() {
            this.getPaper()
            this.formPaper()
            this.status = new Array(this.examInfo.length).fill(0)
            //如果进入页面不进行点击等操作，直接关闭，会不触发
            window.onbeforeunload = function (e) {
                e = e || window.event;
                // 兼容IE8和Firefox 4之前的版本
                if (e) {
                    e.returnValue = "关闭提示";
                }
                // Chrome, Safari, Firefox 4+, Opera 12+ , IE 9+
                return "关闭提示";
            }
        },
        data() {
            return {
                isLoading: false,
                fullPage: true,
                opacity: 0.6,
                showMessageNum: 0,
                WarmMessageisOpen: false,
                checkers: [], //作答数据
                status:[], //题目状态
                queNo: 0, // 当前第几题
                undo: 0,
                closeTest: true,
                paperData: {}, // 试卷信息，类型、id，学生得分、答案
                testType: [
                    {
                        label: this.$t('studentWeb.exam.queType.single'),
                        value: "single"
                    },
                    {
                        label: this.$t('studentWeb.exam.queType.multiply'),
                        value: "multiple"
                    },
                    {
                        label: this.$t('studentWeb.exam.queType.judge'),
                        value: "judge"
                    },
                    {
                        label: this.$t('studentWeb.exam.queType.complete'),
                        value: "complete"
                    },
                    {
                        label: this.$t('studentWeb.exam.queType.subjective'),
                        value: "subjective"
                    },
                    {
                        label: this.$t('studentWeb.exam.queType.compose'),
                        value: "compose"
                    },
                    {
                        label: this.$t('studentWeb.exam.queType.correct'),
                        value: "correct"
                    },
                    {
                        label: this.$t('studentWeb.exam.queType.connector'),
                        value: "connector"
                    },
                ],
                examInfo: [], // 所有题目信息
                judgeSelect: "",
                imgPreview: {
                    img: "",
                    show: false
                },
                isWrong: false, // 错题练习
                isCheckAns: false, // 选中答案
                rigAns: 0, //答对数
                wrgAns: 0, //答错数
                noAns: 0, //未评分数
                noCheck: 0, //未作答数
                repairSource: {
                    normal: [], //网络资源
                    file: [] //文件资源
                },
                previewStatus: false, //展示补救资源
                previewFile: {},
                numPages: null, //pdf的页数
                // papers: [],
            };
        },
        methods: {
            getClassName(index){
                let names = []
                if(this.queNo == index) {
                    names.push("select-item")
                }
                //错题练习
                if(this.isWrong) {
                    let status = this.status[index]
                    // 答题卡选项的颜色 0：未作答 1：正确 2：错误 3：未评分
                    switch(status) {
                        case 0:
                            names.push('')
                            break
                        case 1:
                            names.push('has-right-ans')
                            break
                        case 2:
                            names.push('has-wrong-ans')
                            break
                        case 3:
                            names.push('has-no-ans')
                            break
                    }
                    
                }
                // 正常作答
                else {
                    if(!this.status[index]) {
                        names.push('')
                    } else {
                        names.push('has-ans')
                    }
                }
                return names
// [status[index] != 0 ? (status[index] != 4 ? (status[index] != 3 ? (status[index] == 1 ? 'has-right-ans' : 'has-wrong-ans') : 'has-no-ans') : 'has-ans') : 'ans-box', index == queNo ? 'select-item' :'', checkers[queNo] == examInfo[queNo] ? 'select-item' : '']
            },
            //初始化試卷信息
            formPaper() {
                let paper = []
                this.examInfo.length = []
                let exam = this._.cloneDeep(this.getPaperInfo.item)
                if (exam.length) {
                    for (let i = 0; i < exam.length; i++) {
                        if (exam[i].type == 'compose') {
                            let k = 1
                            if (exam[i].children.length > 0) {
                                // 综合题有子题，k+1，并把子题放入paper 中作为单独的一题
                                for (let items of exam[i].children) {
                                    items.parentInfo = exam[i]
                                    items.parent = i
                                    items.paperIndex = (i + 1) + '-' + k //题号
                                    paper.push(items)
                                    k++
                                }
                            } 
                        } else {
                            exam[i].paperIndex = i
                            paper.push(exam[i])
                        }
                    }
                }
                // 有得分情况，就表示当前是错题练习
                if (this.paperData.stuAns[0]) {
                    this.isWrong = true
                    let wrongData = [] // 存放错题
                    for (let i = 0; i < this.paperData.stuScore.length; i++) {
                        if (this.paperData.stuScore[i] != paper[i].score && this.paperData.stuScore[i] != -1) {
                            if(!paper[i].repair) {
                                paper[i].repair = []
                            }
                            wrongData.push(paper[i])
                        }
                    }
                    this.examInfo = [...wrongData]
                } else {
                    this.examInfo = [...paper]
                }
            },
            //獲取富文本返回數據
            getComposeAns(data, index) {
                // index可能为0
                if (index !== undefined) {
                    this.checkers[index].splice(0)
                    if (data) {
                        this.checkers[index].push(data)
                    }
                    this.hintHandon()
                }
            },
            // 获取试卷信息，并给checkers 添加对应的长度
            getPaper() {
                this.paperData = this._.cloneDeep(this.getCurrentSubject)
                this.checkers.length = 0
                this.closeTest = true
                for (let i = 0; i < this.paperData.stuScore.length; i++) {
                    this.checkers.push([])
                }
            },
            // 判断题型
            getTestType(data) {
                for (let item of this.testType) {
                    if (item.value == data) {
                        return item.label
                    }
                }
            },
            // 获取对应的题目信息
            getQue(index) {
                if (this.examInfo.length) {
                    if (this.examInfo[index]) {
                        return this.examInfo[index];
                    } else {
                        return {
                            type: '',
                        }
                    }
                } else {
                    // 初始化时，this.examInfo 还没有赋值
                    return {
                        type: '',
                        parent: ''
                    }
                }
            },
            // 获得选择题——选中的答案
            getAns(data, index) {
                if (this.getQue(this.queNo).type == "single") {
                    this.checkers[data].length = 0
                    this.checkers[data].push(this.getQue(this.queNo).option[index].code)
                }
            },
            // 完成度的状态
            hintHandon() {
                let undoQuestion = 0
                for (var i = 0; i < this.examInfo.length; i++) {
                    if (this.checkers[i] == "") {
                        undoQuestion++
                    }
                }
                this.undo = undoQuestion
                if (undoQuestion != 0) return false
                else return true
            },
            // 点击答题卡跳转
            gototheQues(index) {
                this.queNo = index - 1
                this.changeAnalysisType(false)
            },
            preQ() {
                if (this.queNo > 0) {
                    this.queNo--
                    this.changeAnalysisType(false)
                }
            },
            nextQ() {
                if (this.queNo < (this.examInfo.length - 1)) {
                    this.queNo++
                    this.changeAnalysisType(false)
                }
            },
            //打开提示信息
            openWarmMessage(showMessageNum) {
                this.WarmMessageisOpen = true
                if (showMessageNum == 1) {
                    if(this.isWrong) {
                        this.showMessageNum = 4
                    } else {
                        this.showMessageNum = showMessageNum
                    }
                } else if (showMessageNum == 2) {
                    for (var i = 0; i <= this.examInfo.length; i++) {
                        if (this.checkers[i] == "" && this.getQue(i).type != 'compose') {
                            this.showMessageNum = 3
                            break;
                        }
                        if (this.checkers[i] != "") {
                            this.showMessageNum = 2
                        }
                    }
                } else if (showMessageNum == 5) {
                    this.status.map(item => {
                        if(item == 0) {
                            this.noCheck++
                        } else if(item == 1) {
                            this.rigAns++
                        } else if(item == 2) {
                            this.wrgAns++
                        } else {
                            this.noAns++
                        }
                    })
                    this.showMessageNum = 5
                } else return
            },
            //关闭提示信息
            closeWarmMessage() {
                this.WarmMessageisOpen = false
                this.showMessageNum = 0
            },
            //提交作答记录
            closetest() {
                this.WarmMessageisOpen = false
                if (this.checkers.length) {
                    this.isLoading = true;
                    // 选了个人课程：scope == 'private'
                    // 选了标准课程：scope == 'school'
                    let codes = this.getItemTitle.scope == 'school' ? this.getItemTitle.school : this.getItemTitle.creatorId
                    let req = {
                        id: this.getItemTitle.id,
                        answer: this.checkers,
                        studentId: this.getUserInfo.studentId,
                        classIds: this.getItemTitle.classIds,
                        subjectId: this.getExamInfo.subject.id,
                        multipleRule: this.getExamInfo.multipleRule, //阅卷规则
                        paperId: this.getPaperInfo.id,
                        code: codes,
                        scode: this.getItemTitle.scode
                    }
                    this.$api.studentWeb.SaveStuExamPaper(req).then(res => {
                        if (res) {
                            this.$Message.success(this.$t('studentWeb.exam.submitSuccess'))
                            this.$router.push({path: "/studentWeb/eventView"})
                        }
                    }, err => {
                        this.$Message.warning(this.$t('studentWeb.exam.submitFail'))
                        setTimeout(() => {
                            this.isLoading = false
                        }, 1000)
                    })
                } 
            },
            //退出测试
            quitTest() {
                this.isLoading = true
                this.$router.push({path: "/studentWeb/eventView"})
            },
            //处理学生作答数据blob地址
            formUrl(data) { 
                let a = ""
                if (data.blob.indexOf('https://teammodelstorage') > -1) {
                    a = data.blob
                } else {
                    let blobUrl = JSON.parse(decodeURIComponent(localStorage.student_profile, "utf-8")).blob_uri
                    let studentBlob = blobUrl.split('/')
                    let url = data.scope == 'school' ? blobUrl : "https://" + studentBlob[studentBlob.length - 2] + '/' + this.getItemTitle.creatorId
                    a = `${url}/exam/${data.blob}`
                }
                return a
            },
            //放大图片
            showImg(e) {
                this.imgPreview = {
                    img: "",
                    show: false
                }
                if (e.target.tagName == 'IMG') {
                    this.imgPreview.img = e.target.src
                    this.imgPreview.show = true
                }
            },
            // 错题模式下的解析
            changeAnalysisType(type) {
                if (this.isWrong) {
                    this.isCheckAns = type
                    // “我的作答” 跳转到顶部
                    if (type) {
                        document.getElementsByClassName("answers")[0].scrollIntoView();
                        if(this.examInfo[this.queNo].repair.length > 0) {
                            let source = this._.cloneDeep(this.examInfo[this.queNo].repair)
                            this.getSource(source)
                        }
                    }
                }
            },
            // 获取补救资源
            getSource(data) {
                this.repairSource = {
                    normal: [],
                    file: []
                }
                let source = {
                    normal: [],
                    file: []
                }
                for (let item of data) {
                    if (item.type == 'normal') {
                        source.normal.push(item)
                    } else if (item.blobUrl) {
                        let code = item.blobUrl.split('/')
                        let data = code[code.length - 1].split('?')
                        let type = data[0].split('.')
                        item.name = data[0]
                        item.file = code[code.length - 2]
                        item.fileType = type[type.length - 1]
                        source.file.push(item)
                    }
                }
                this.repairSource = source
            },
            // 关闭Modal
            closePreview() {
                this.previewStatus = false
                this.previewFile = {}
            },
            //下载补救文件资源
            async downloadFile(data) {
                // let blobData = await this.getFileSas(data)
                let blobData = data.blobUrl
                const downloadRes = async () => {
                    let response = await fetch(blobData); // 内容转变成blob地址
                    let blob = await response.blob();  // 创建隐藏的可下载链接
                    let objectUrl = window.URL.createObjectURL(blob);
                    let a = document.createElement('a');
                    a.href = objectUrl;
                    a.download = data.name;
                    a.click()
                    a.remove();
                }
                downloadRes();
            },
            // 点击文件资源
            async getItemData(data) {
                this.previewStatus = false
                if (data.file) {
                    this.previewFile = this._.cloneDeep(data)
                    // this.previewFile.blobUrl = await this.getFileSas(data)
                    if (this.previewFile.fileType == 'doc' || this.previewFile.fileType == 'csv'
                        || this.previewFile.fileType == 'xls' || this.previewFile.fileType == 'xlsx' ||
                        this.previewFile.fileType == 'pptx' || this.previewFile.fileType == 'ppt' || this.previewFile.fileType == 'docx') {
                        let url = escape(this.previewFile.blobUrl)
                        this.previewFile.blobUrl = url
                    }
                    if (this.previewFile.fileType == 'pdf') {
                        await this.getPdf(this.previewFile.blobUrl)
                    }
                    this.previewStatus = true
                }
            },
            getPdf(data) {
                let loadingTask = pdf.createLoadingTask(data)
                loadingTask.promise.then(pdf => {
                    this.numPages = pdf.numPages
                }).catch(err => {
                    this.$Message.warning(this.$t('studentWeb.exam.report.pdfErr'))
                })
            },

            /* ======未调用====== */
            getJudge() {
                this.checkers[this.queNo] = []
                this.checkers[this.queNo].push(this.judgeSelect)
            },
            async getItem(data) {
                let datas = []
                if (data) {
                    let key = this.getExamInfo.code.split('-')
                    let code = {
                        scope: this.getExamInfo.scope,
                        code: key[(key.length - 1)],
                        blob: data
                    }
                    let blob = this.formUrl(code)
                    code.blob = blob
                    console.log(code);
                    datas = await this.$evTools.getComposeItem(code)
                    console.log(datas);
                    return datas
                } else {
                    return []
                }
            },
        },

        watch: {
            checkers:{
                handler(n, o) {
                    // 未作答：0  对：1  错：2  主观题：3  已作答：4
                    // 已作答
                    if(n[this.queNo] && n[this.queNo].length) {
                        if(this.isWrong) {
                            let objectiveTypes = ["single", "multiple", "judge"]

                            if(objectiveTypes.includes(this.examInfo[this.queNo].type)) {
                                if(this.examInfo[this.queNo].type != "multiple") {
                                    if(n[this.queNo][0] == this.examInfo[this.queNo].answer[0]) {
                                        this.status[this.queNo] = 1
                                    } else {
                                        this.status[this.queNo] = 2
                                    }
                                }
                                // 多选
                                else {
                                    let ans = n[this.queNo]
                                    let answer = this.examInfo[this.queNo].answer
                                    let q = 0
                                    ans.map(item => {
                                        for (let i = 0; i < answer.length; i++) {
                                            if(item == answer[i]) {
                                                q += 1
                                                break
                                            }
                                        }
                                    })
                                    if(answer.length == q) {
                                        this.status[this.queNo] = 1
                                    } else {
                                        this.status[this.queNo] = 2
                                    }
                                } 
                            } 
                            else {
                                this.status[this.queNo] = 3
                            }
                        } else {
                            this.status[this.queNo] = 4
                        }
                    }
                    // 未作答
                    else{
                        this.status[this.queNo] = 0
                    }
                },
                deep:true
            },
            /* papers: {
                async handler(newV, oldV) {
                    if (newV.item.length) {
                        this.checkers.length = 0
                        this.closeTest = true
                        if (this.getCurrentSubject.stuAns[0] !== undefined) {
                            for (let i = 0; i < this.getCurrentSubject.stuScore.length; i++) {
                                this.checkers == this.checkers.push([])
                            }
                            // this.closeTest = false
                        } else {
                            for (let i = 0; i < this.getCurrentSubject.stuScore.length; i++) {
                                this.checkers == this.checkers.push([])
                            }
                        }
                    }
                },
                deep: true,
                immediate: true                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
            }, */
        },
        computed: {
            ...mapGetters([
                "getItemTitle",
                "getPaperInfo",
                "getCurrentSubject",
                "getExamInfo",
                "getUserInfo"
            ]),
            completeRate() {
                if (this.examInfo.length) {
                    let data = 0
                    data = Math.ceil(((this.examInfo.length - this.undo) / this.examInfo.length) * 100)
                    return data
                } else {
                    return 0
                }
            },

        },
        // 导航守卫监听
        beforeRouteLeave(to, from, next) {
            if(this.showMessageNum == 0) {
                this.$Modal.confirm({
                    title: this.$t("studentWeb.exam.testpop.exitQuizhint"),
                    content: this.$t("studentWeb.exam.testpop.exitQuizhintD"),
                    onOk: () => {
                        next(true)
                    },
                    onCancel: () => {
                        next(false)
                    },
                })
            } else {
                next(true)
            }
            
        },
    }
</script>

<style scoped>
    @import "~@/assets/student-web/component_styles/paper-test.css";
    .que-item /deep/ table {
        border-top: 1px solid #ccc;
        border-left: 1px solid #ccc;
    }

    .que-item /deep/ table td, table th {
        border-right: 1px solid #ccc;
        padding: 3px 5px;
    }

    .que-item /deep/ table th {
        border-bottom: 1px solid #ccc;
        border-right: 1px solid #ccc;
        text-align: center;
    }

    .que-items /deep/ table {
        border-top: 1px solid #ccc;
        border-left: 1px solid #ccc;
    }

    .que-items /deep/ table td, table th {
        border-right: 1px solid #ccc;
        padding: 3px 5px;
    }

    .que-items /deep/ table th {
        border-bottom: 1px solid #ccc;
        border-right: 1px solid #ccc;
        text-align: center;
    }

    .imgDolg {
        width: 100vw;
        height: 100vh;
        position: fixed;
        z-index: 9999;
        background-color: rgba(140, 134, 134, 0.6);
        top: 0;
        left: 0;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .imgDolg img {
        width: 60%;
        border: 1px solid #eee;
        height: 95%;
    }

    .imgDolg #imgDolgClose {
        position: fixed;
        top: 35px;
        cursor: pointer;
        right: 17%;
        font-size: 50px;
        color: white;
    }

    .file-box{
        text-align:center;
        height:100%;
        overflow:scroll;
    }
</style>