<template>
    <div class="paper-score-container">
        <!-- 题目列表部分 -->
        <Loading :top="200" type="1" style="text-align:center" v-show="dataLoading"></Loading>
        <div class="scoring-paper-header">
            <div>
                <span class="base-info-item">
                    {{$t('learnActivity.score.stuName')}}
                    <span class="analysis-info">{{studentAnswer.name}}</span>
                </span>
                <span class="base-info-item">
                    {{$t('learnActivity.score.score')}}
                    <span class="analysis-info">
                        {{scoreTotal}}{{$t('learnActivity.score.scoreUnit')}}
                    </span>
                </span>
                <span class="base-info-btn" type="success" @click="saveScore">
                    <Icon type="ios-albums-outline" />
                    {{$t('learnActivity.score.saveScore')}}
                </span>
                <span class="base-info-btn" @click="showAnswer = !showAnswer">
                    <Icon :type="showAnswer ? 'md-eye-off':'md-eye'" />
                    {{ showAnswer ? $t('learnActivity.score.hideAns') : $t('learnActivity.score.showAns')}}
                </span>
                <span class="base-info-btn" @click="showQu = !showQu">
                    <Icon :type="showQu ? 'md-eye-off':'md-eye'" />
                    {{ showQu ? $t('learnActivity.score.hideQu') : $t('learnActivity.score.showQu')}}
                </span>
                <span class="base-info-btn" @click="markByQu">
                    <Icon type="ios-create" />
                    {{$t('learnActivity.score.byQuMark')}}
                </span>
            </div>
            <!-- 题号 -->
            <div class="question-index-box" v-if="studentAnswer.scores">
                <div class="base-info-item" style="white-space: nowrap;">{{$t('learnActivity.score.quIndex')}}</div>
                <div>
                    <template v-for="(typeItem,typeIndex) in groupList">
                        <template v-for="(item,index) in typeItem.list">
                            <span :key="typeIndex+''+index" @click="goToQuestion(getScoreIndex(typeIndex,index))" :class="studentAnswer.scores[item.index] >= 0 ? 'qu-order-tag':'qu-order-tag-def'" v-if="typeItem.type !== 'compose'">
                                {{getQuIndex(typeIndex,index)}}
                            </span>
                            <span :key="index" v-else>
                                <span @click="goToQuestion(getScoreIndex(typeIndex,index,childIndex))" v-for="(childItem,childIndex) in item.children" :key="childIndex" :class="studentAnswer.scores[childItem.index] >= 0 ? 'qu-order-tag':'qu-order-tag-def'">
                                    {{getQuIndex(typeIndex,index) + '-' + (childIndex + 1)}}
                                </span>
                            </span>
                        </template>
                    </template>
                </div>
            </div>
        </div>
        <div class="qu-list-wrap scoring-exercise-wrap" ref="mathJaxContainer" v-show="!dataLoading">
            <!-- 按题型排序 -->
            <div v-show="!isComplete" class="list-view" :key="'group'+ typeIndex" v-for="(typeItem,typeIndex) in groupList">
                <p class="type-name">
                    {{ numberConvertToUppercase(getLatestTypeIndex(typeItem.type) + 1) }}
                    {{ exersicesType[typeItem.type] }}
                    ({{ typeItem.score || 0 }} {{$t('learnActivity.score.scoreUnit')}})
                </p>
                <div ref="ques" v-for="(item,index) in typeItem.list" :key="'qu'+ index" :class='["exercise-item"]'>
                    <!-- 非综合题-->
                    <div v-if="item.type != 'compose'" style="display:flex;width:100%;padding-top:15px;" :class="['not-compose-box', activeIndex == getScoreIndex(typeIndex,index) ? 'active-qu-wrap' : '']" :id="'qustion'+ getScoreIndex(typeIndex,index)" @click="activeIndex = getScoreIndex(typeIndex,index)">
                        <div class="scoring-input-box" @click.stop v-if="studentAnswer.scores && studentAnswer.scores.length">
                            <InputNumber @on-change="setUpdStatus" v-model="studentAnswer.scores[item.index]" size="small" :formatter="value => value < 0 ? '' : `${value}${$t('learnActivity.score.scoreUnit')}`" :parser="value => value.replace($t('learnActivity.score.scoreUnit'), '')" :min="0" :max="item.score" :placeholder="$t('learnActivity.score.zeroScore1')" class="score-input" />
                            <!-- 快速打分 满分 零分 -->
                            <div style="display:flex;justify-content: space-evenly;margin-top:5px;">
                                <span class="fast-score-tag" :title="$t('learnActivity.score.fullScore')" @click="fastSetScore(item.index,item.score)">
                                    <!-- 题目分数 -->{{item.score}}
                                </span>
                                <span class="fast-score-tag" :title="$t('learnActivity.score.zeroScore')" @click="fastSetScore(item.index,0)" style="background:#ed4014">
                                    0
                                </span>
                            </div>
                            <!-- 加分 减分 -->
                            <div style="display:flex;justify-content: space-evenly;margin-top:5px;">
                                <span class="fast-score-tag" @click="scoreUp(item.index,item.score)">
                                    <Icon type="md-add" />
                                </span>
                                <span class="fast-score-tag" @click="scoreDown(item.index)" style="background:#ed4014">
                                    <Icon type="md-remove" />
                                </span>
                            </div>
                        </div>
                        <div class="qu-info-box">
                            <!-- 题干部分 -->
                            <div class="item-question item-question-flex" v-show="showQu">
                                <div class="item-question-order">{{ getQuIndex(typeIndex,index) }} .</div>
                                <div class="item-question-text" v-html="item.question"></div>
                            </div>
                            <!-- 选项部分 -->
                            <div v-for="(option,optionIndex) in item.option" :key="'op' + optionIndex" class="item-options" v-show="showQu">
                                <div class="item-option-content">
                                    <div class="item-option-order">{{String.fromCharCode(64 + parseInt(optionIndex+1))}} :</div>
                                    <div class="item-option-text" v-html="option.value"></div>
                                </div>
                            </div>
                            <div class="stu-answer-detail">
                                <p class="answer-title">
                                    <span v-show="!showQu" class="item-question-order">{{$t('learnActivity.score.quIndex1')}} {{ getQuIndex(typeIndex,index)}} </span>
                                    <span v-show="showAnswer || showQu">
                                        {{$t('learnActivity.score.stuAns')}}
                                    </span>
                                    <!-- <Icon type="md-checkmark" v-show="studentAnswer.scores[item.index] == item.score" />
                                    <Icon type="md-close" color="#ed4014" v-show="studentAnswer.scores[item.index] == 0" />
                                    <Icon custom="iconfont icon-half-right" color="#ff9900" v-show="studentAnswer.scores[item.index] > 0 && studentAnswer.scores[item.index] < item.score" /> -->
                                    <!-- 标记是否有批注，暂不需要 -->
                                    <!-- <Icon custom="iconfont icon-mark" color="#1cc0f3" @click="viewMark(item.index)" v-if="studentAnswer.mark && studentAnswer.mark[item.index] && studentAnswer.mark[item.index].length" style="margin-left:10px" /> -->
                                </p>
                                <!--学生作答答案显示区域-->
                                <div class="stu-answer-box item-explain-details" v-if="studentAnswer.answers && studentAnswer.answers.length">
                                    <!-- 批注 主观题才会有批注功能 -->
                                    <div class="mark-btn-box" v-if="item.type !== 'single' && item.type !== 'multiple' && item.type !== 'judge'">
                                        <span class="mark-action-item" v-if="studentAnswer.mark && studentAnswer.mark[item.index] && studentAnswer.mark[item.index].length" style="background:#19be6b" @click="viewMark(item.index)">
                                            <Icon type="md-eye" />
                                            <span style="margin-left:5px;">{{$t('learnActivity.score.view')}}</span>
                                        </span>
                                        <span class="mark-action-item" style="background:#ed4014" @click="markStuAnswer(item.index)">
                                            <Icon type="md-create" />
                                            <span style="margin-left:5px;">{{$t('learnActivity.score.mark')}}</span>
                                        </span>
                                    </div>
                                    <!--多选题答案-->
                                    <div v-if="item.type === 'multiple'" :id="'answer'+ getScoreIndex(typeIndex,index)">
                                        <!-- <span v-for="(answerItem,answerIndex) in studentAnswer.answers[getScoreIndex(typeIndex,index)]" :key="'an'+ (answerIndex+index)" v-html="answerItem" style="display:inline;">
                                        </span> -->
                                        <span v-for="(answerItem,answerIndex) in studentAnswer.answers[item.index]" :key="'an'+ (answerIndex+index)" v-html="answerItem" style="display:inline;">
                                        </span>
                                    </div>
                                    <!--其余题型答案-->
                                    <div v-else-if="studentAnswer.answers[item.index]" :id="'answer'+ getScoreIndex(typeIndex,index)">
                                        <div>
                                            <span v-html="studentAnswer.answers[item.index].toString()"></span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <!-- 答案以及解析 -->
                            <transition name="slide">
                                <div class="toggle-area" v-show="showAnswer">
                                    <div v-if="item.type !== 'compose'">
                                        <!-- 答案展示部分 -->
                                        <div class="item-explain">
                                            <span class="explain-title">{{$t('learnActivity.score.quAns')}}</span>
                                            <div class="item-explain-details">
                                                <!-- 问答题答案 -->
                                                <div v-if="item.type === 'subjective'">
                                                    <span v-for="(answer,index) in item.answer" :key="index" v-html="item.answer.length ? answer : $t('learnActivity.score.noAnswer')"></span>
                                                </div>
                                                <!-- 填空题答案 -->
                                                <div v-else-if="item.type === 'complete'">
                                                    <span :class="[ item.type === 'complete' ? 'item-answer-item':'']" v-for="(answer,index) in item.answer" :key="index" v-html="answer"></span>
                                                </div>
                                                <!-- 其余题型答案 -->
                                                <div v-else>
                                                    <span v-for="(answer,index) in item.answer" :key="index" v-html="answer"></span>
                                                </div>
                                            </div>
                                        </div>
                                        <!-- 解析部分 -->
                                        <div class="item-explain">
                                            <span class="explain-title">{{$t('learnActivity.score.anaLabel')}}</span>
                                            <div class="item-explain-details">
                                                <span v-html="item.explain || $t('learnActivity.score.noAna')"></span>
                                            </div>
                                        </div>
                                        <!-- 知识点部分 -->
                                        <div class="item-explain">
                                            <span class="explain-title">{{$t('learnActivity.score.kdLabel')}}</span>
                                            <div class="item-explain-details">
                                                <span v-if="!item.knowledge || (_.compact(item.knowledge).length)">{{$t('learnActivity.score.noKd')}}</span>
                                                <div v-else>
                                                    <span v-for="(point,index) in item.knowledge" :key="index" class="item-point-tag">
                                                        {{ point }}
                                                    </span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </transition>
                        </div>
                    </div>
                    <!-- 综合题 -->
                    <div v-else style="width:100%;" class="compose-box">
                        <div class="item-question item-question-flex" style="margin-left:90px; margin-top:20px;" v-show="showQu">
                            <div class="item-question-order">{{ getQuIndex(typeIndex,index)}}.</div>
                            <div class="item-question-text" v-html="item.question"></div>
                        </div>
                        <div :class="['child-item', activeIndex == getScoreIndex(typeIndex,index,childIndex) ? 'active-qu-wrap' : '']" v-for="(childItem,childIndex) in item.children" :key="childIndex" style="padding-top:15px;" :id="'qustion'+getScoreIndex(typeIndex,index,childIndex)" @click="activeIndex = getScoreIndex(typeIndex,index,childIndex)">
                            <div class="scoring-input-box" @click.stop v-if="studentAnswer.scores && studentAnswer.scores.length">
                                <InputNumber @on-change="setUpdStatus" v-model="studentAnswer.scores[childItem.index]" size="small" :formatter="value => value < 0 ? '' : `${value}${$t('learnActivity.score.scoreUnit')}`" :parser="value => value.replace($t('learnActivity.score.scoreUnit'), '')" :min="0" :max="childItem.score" :placeholder="$t('learnActivity.score.zeroScore1')" class="score-input" />
                                <!-- 快速打分 满分 零分 -->
                                <div style="display:flex;justify-content: space-evenly;margin-top:5px;">
                                    <span class="fast-score-tag" :title="$t('learnActivity.score.fullScore')" @click="fastSetScore(childItem.index,childItem.score)">
                                        <!-- 题目分数 -->{{childItem.score}}
                                    </span>
                                    <span class="fast-score-tag" :title="$t('learnActivity.score.zeroScore')" @click="fastSetScore(childItem.index,0)" style="background:#ed4014">
                                        0
                                    </span>
                                </div>
                                <!-- 加分 减分 -->
                                <div style="display:flex;justify-content: space-evenly;margin-top:5px;">
                                    <span class="fast-score-tag" @click="scoreUp(childItem.index,childItem.score)">
                                        <Icon type="md-add" />
                                    </span>
                                    <span class="fast-score-tag" @click="scoreDown(childItem.index)" style="background:#ed4014">
                                        <Icon type="md-remove" />
                                    </span>
                                </div>
                            </div>
                            <div class="qu-info-box">
                                <div class="child-item-question child-item-question-flex" v-show="showQu">
                                    <span class="child-item-question-order">{{$t('learnActivity.score.sQuLabel1')}}{{ childIndex + 1 }}{{$t('learnActivity.score.sQuLabel2')}}</span>
                                    <p class="child-item-question-content" v-html="childItem.question"></p>
                                </div>
                                <!-- 选项部分 -->
                                <div v-for="(option,optionIndex) in childItem.option" :key="optionIndex" class="child-item-option" style="pointer-events:none;" v-show="showQu">
                                    <div>
                                        <div class="child-item-option-order">{{String.fromCharCode(64 + parseInt(optionIndex+1))}} : </div>
                                        <div class="child-item-option-text" v-html="option.value"></div>
                                    </div>
                                </div>
                                <div class="stu-answer-detail">
                                    <p class="answer-title">
                                        <span class="child-item-question-order" v-show="!showQu">{{$t('learnActivity.score.quIndex1')}} {{getQuIndex(typeIndex,index)+'-'+ (childIndex + 1) }}</span>
                                        <span v-show="showAnswer || showQu">
                                            {{$t('learnActivity.score.stuAns')}}
                                        </span>
                                        <!-- <Icon type="md-checkmark" v-show="studentAnswer.scores[childItem.index] == childItem.score" />
                                        <Icon type="md-close" color="#ed4014" v-show="studentAnswer.scores[childItem.index] == 0" />
                                        <Icon custom="iconfont icon-half-right" color="#ff9900" v-show="studentAnswer.scores[childItem.index] > 0 && studentAnswer.scores[childItem.index] < childItem.score" /> -->
                                        <!-- 标记是否有批注，暂不需要 -->
                                        <!-- <Icon custom="iconfont icon-mark" color="#1cc0f3" @click="viewMark(childItem.index)" v-if="studentAnswer.mark && studentAnswer.mark[childItem.index] && studentAnswer.mark[childItem.index].length" style="margin-left:10px" /> -->
                                    </p>
                                    <!--学生作答答案显示区域-->
                                    <div class="stu-answer-box item-explain-details" v-if="studentAnswer.answers && studentAnswer.answers.length">
                                        <!-- 批注 主观题才会有批注功能 -->
                                        <div class="mark-btn-box" v-if="childItem.type !== 'single' && childItem.type !== 'multiple' && childItem.type !== 'judge'">
                                            <span v-if="studentAnswer.mark && studentAnswer.mark[childItem.index] && studentAnswer.mark[childItem.index].length" class="mark-action-item" style="background:#19be6b" @click="viewMark(childItem.index)">
                                                <Icon type="md-eye" />
                                                <span style="margin-left:5px;">{{$t('learnActivity.score.view')}}</span>
                                            </span>
                                            <span class="mark-action-item" style="background:#ed4014" @click="markStuAnswer(childItem.index)">
                                                <Icon type="md-create" />
                                                <span style="margin-left:5px;">{{$t('learnActivity.score.mark')}}</span>
                                            </span>
                                        </div>
                                        <!--多选题答案-->
                                        <div v-if="childItem.type === 'multiple'" :id="'answer'+ getScoreIndex(typeIndex,index,childIndex)">
                                            <span v-for="(answerItem,answerIndex) in studentAnswer.answers[childItem.index]" :key="'an'+ (index+answerIndex+childIndex)" v-html="answerItem" style="display:inline-block;"></span>
                                        </div>
                                        <!--其余题型答案-->
                                        <div v-else-if="studentAnswer.answers[childItem.index]" :id="'answer'+ getScoreIndex(typeIndex,index,childIndex)">
                                            <div>
                                                <span v-html="studentAnswer.answers[childItem.index].toString()"></span><br />
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <!-- 答案展示部分 -->
                                <div class="item-explain" v-show="showAnswer">
                                    <span class="explain-title">{{$t('learnActivity.score.quAns')}}</span>
                                    <div class="item-explain-details">
                                        <!-- 问答题答案 -->
                                        <div v-if="item.type === 'subjective' || item.type === 'complete'">
                                            <span v-for="(answer,index) in childItem.answer" :key="index" v-html="childItem.answer.length ? answer : $t('learnActivity.score.noAnswer')"></span>
                                        </div>
                                        <!-- 判断题答案 -->
                                        <div v-else-if="item.type === 'judge'">
                                            <span>{{ childItem.answer.length ? (childItem.answer[0] === 'A' ? $t('learnActivity.score.trueAns') : $t('learnActivity.score.falseAns')) : $t('learnActivity.score.noAnswer') }}</span>
                                        </div>
                                        <!-- 其余题型答案 -->
                                        <div v-else>
                                            <span :class="[ item.type === 'complete' ? 'item-answer-item':'']" v-for="(answer,index) in childItem.answer" :key="index" v-html="answer"></span>
                                        </div>
                                    </div>
                                </div>
                                <!-- 解析部分 -->
                                <div class="item-explain" v-show="showAnswer">
                                    <span class="explain-title">{{$t('learnActivity.score.anaLabel')}}</span>
                                    <div class="item-explain-details">
                                        <span v-html="childItem.explain || $t('learnActivity.score.noAna')"></span>
                                    </div>
                                </div>
                                <!-- 知识点部分 -->
                                <div class="item-explain" v-show="showAnswer">
                                    <span class="explain-title">{{$t('learnActivity.score.kdLabel')}}</span>
                                    <div class="item-explain-details">
                                        <span v-if="!childItem.knowledge || !childItem.knowledge.length">{{$t('learnActivity.score.noKd')}}</span>
                                        <div v-else>
                                            <span v-for="(point,index) in childItem.knowledge" :key="index" class="item-point-tag">
                                                <span>{{ point }}</span>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div v-show="isComplete" class="complete-score-box">
                <Icon class="complete-icon" type="md-checkmark-circle" />
                <p class="complete-stu-info">{{studentAnswer.name}} ({{scoreTotal}}{{$t('learnActivity.score.scoreUnit')}})</p>
                <p class="complete-next" @click="nextStu">{{$t('learnActivity.score.nextStu')}}</p>
            </div>
        </div>
        <Modal v-model="markStatus" fullscreen :title="$t('learnActivity.score.mark')" class-name="mark-modal" @on-ok="saveMark(markData)" @on-cancel="closeModal">
            <BaseMark1 v-if="markStatus" defaultStatus="line" :bgImg="markBg" @onMarkChange="getMarkData"></BaseMark1>
        </Modal>
        <!-- 用来单独渲染学生作答数据，提高tocanvas 的效率 -->
        <iframe id="answerIframe" :srcdoc="answerOrMark" v-if="answerOrMark"></iframe>
        <Modal v-model="viewStatus" :title="$t('learnActivity.score.viewMark')" width='800'>
            <div v-for="(item,index) in viewMarks" :key="index">
                <p class="mark-label" v-show="viewMarks.length > 1">{{$t('learnActivity.score.markLabel')}}{{index + 1}}:</p>
                <img v-if="viewStatus" :src="item.url" style="width:100%;margin-bottom:20px">
            </div>
        </Modal>
    </div>
</template>
<script>
import html2canvas from 'html2canvas'
import BaseMark1 from '@/components/mark/BaseMark.vue'
import BlobTool from '@/utils/blobTool.js'
export default {
    components: {
        BaseMark1
    },
    props: {
        examId: {
            type: String,
            default: '',
            required: true
        },
        examScope: {
            type: String,
            default: '',
            required: true
        },
        // 用于判断是个人还是校本评测
        owner: {
            type: String,
            default: '',
            required: true
        },
        subjectId: {
            type: String,
            default: '',
            required: true
        },
        paper: {
            type: Object,
            default: () => { }
        },
        pStudentAnswer: {
            type: Object,
            default: () => { }
        },
        defaultIndex: {
            type: Number,
            default: 0
        }
    },
    data() {
        return {
            isUpd: false,
            studentAnswer: {},
            viewIndex: 0,
            viewStatus: false,
            isDefOrder: false, //是否默认排序  默认/题型
            activeIndex: 0,
            curAnIndex: -1,
            markStatus: false,
            isComplete: false,
            isAllOpen: true,
            paperInfo: {},
            dataLoading: false,
            exerciseList: [],
            exersicesType: this.$GLOBAL.EXERCISE_TYPES(),
            collapseList: [],
            groupList: [],
            typeList: ['single', 'multiple', 'judge', 'complete', 'subjective', 'connector', 'correct', 'compose'],
            showAnswer: false,
            showQu: false,
            showOption: false,
            scope: '',
            markBg: undefined,
            viewMarks: [],
            markData: {}
        }
    },
    methods: {
        setUpdStatus() {
            this.isUpd = true
        },
        markByQu() {
            this.$emit('toggleMarkType', 'byQu')
        },
        closeModal() {
            this.markStatus = false
            this.curAnIndex = -1
            let answerIframe = document.getElementById('answerIframe')
            answerIframe.onload = () => { }
        },
        getMarkData(data) {
            this.markData = data
        },
        saveMark(data) {
            // 判断当前教师是否已有批注
            if (!data.base64) {
                return
            }
            let fileName, hasMarked
            if (this.studentAnswer.mark && this.studentAnswer.mark[this.curAnIndex]) {
                let d = this._.cloneDeep(this.studentAnswer.mark[this.curAnIndex])
                let markData = d.find(item => {
                    return item.tmdId == this.$store.state.userInfo.TEAMModelId
                })
                if (markData) {
                    let blob = markData.mark
                    fileName = blob.substring(blob.lastIndexOf('/') + 1, blob.length)
                    hasMarked = true
                } else {
                    fileName = this.$jsFn.uuid() + '.png'
                }
            } else {
                fileName = this.$jsFn.uuid() + '.png'
            }
            let markPng = this.$jsFn.dataURLtoFile(data.base64, fileName)
            //保存批注图片
            let sas = this.examScope == 'school' ? this.$store.state.user.schoolProfile.blob_sas : this.$store.state.user.userProfile.blob_sas
            let blobUrl = this.examScope == 'school' ? JSON.parse(decodeURIComponent(localStorage.school_profile, "utf-8")).blob_uri : JSON.parse(decodeURIComponent(localStorage.user_profile, "utf-8")).blob_uri
            let host = blobUrl.substring(0, blobUrl.lastIndexOf('/'))
            let cont = blobUrl.substring(blobUrl.lastIndexOf('/') + 1)
            let blobTool = new BlobTool(host, cont, '?' + sas, this.examScope)
            let path = `exam/${this.examId}/${this.subjectId}/${this.studentAnswer.id}`
            blobTool.upload(markPng, path).then(
                res => {
                    if (!hasMarked) {
                        this.studentAnswer.mark[this.curAnIndex].push({
                            mark: path + '/' + fileName,
                            tmdId: this.$store.state.userInfo.TEAMModelId
                        })
                    }
                    this.markStatus = false
                    //保存批注数据
                    this.$api.learnActivity.upsertAnswer({
                        "id": this.examId,
                        "studentId": this.studentAnswer.id,
                        "subjectId": this.subjectId,
                        "classId": this.studentAnswer.classId,
                        "code": this.examScope == 'school' ? this.$store.state.userInfo.schoolCode : this.$store.state.userInfo.TEAMModelId,
                        "tmdId": this.$store.state.userInfo.TEAMModelId,
                        "index": this.curAnIndex,//题号
                        "mark": {
                            sc: 0,//分数
                            tmdId: this.$store.state.userInfo.TEAMModelId,
                            mark: path + '/' + fileName,//批注BLOB地址
                            identity: 'admin',//老师身份，这是是固定管理员身份
                            index: this.curAnIndex //题号
                        }
                    }).then(
                        res => {
                            this.$Message.success(this.$t('learnActivity.score.markOk'))
                        },
                        err => {
                            this.$Message.error(this.$t('learnActivity.score.markErr'))
                        }
                    ).finally(() => {
                        this.curAnIndex = -1
                    })
                },
                err => {
                    this.$Message.error(this.$t('learnActivity.mark.saveErr'))
                }
            )
        },
        //查看批注数据
        viewMark(index) {
            this.viewIndex = index
            this.viewStatus = true
            if (this.studentAnswer.mark && this.studentAnswer.mark[this.viewIndex]) {
                let sas = this.examScope == 'school' ? this.$store.state.user.schoolProfile.blob_sas : this.$store.state.user.userProfile.blob_sas
                let blobUrl = this.examScope == 'school' ? JSON.parse(decodeURIComponent(localStorage.school_profile, "utf-8")).blob_uri : JSON.parse(decodeURIComponent(localStorage.user_profile, "utf-8")).blob_uri
                let d = this._.cloneDeep(this.studentAnswer.mark[this.viewIndex])
                d.forEach(item => {
                    item.url = blobUrl + '/' + item.mark + '?' + sas
                })
                this.viewMarks = d
            } else {
                this.viewMarks = []
            }
        },
        // 批注学生作答数据
        markStuAnswer(index) {
            this.curAnIndex = index
            this.$nextTick(() => {
                let answerIframe = document.getElementById('answerIframe')
                answerIframe.onload = () => {
                    answerIframe.style.width = '850px'
                    answerIframe.contentWindow.document.body.style.margin = '0px'
                    answerIframe.contentWindow.document.body.style.padding = '0px'
                    answerIframe.contentWindow.document.body.style.minWidth = '600px'
                    answerIframe.contentWindow.document.body.style.minHeight = '240px'
                    answerIframe.contentWindow.document.body.style.height = 'fit-content'
                    answerIframe.contentWindow.document.body.style.width = 'fit-content'
                    let bodyWidth = answerIframe.contentWindow.document.body.clientWidth
                    answerIframe.style.width = (bodyWidth + 20) + 'px'
                    answerIframe.contentWindow.document.body.style.backgroundColor = '#f5f5f5'

                    html2canvas(answerIframe.contentWindow.document.body, {
                        useCORS: true
                    }).then(
                        (canvas) => {
                            canvas.id = "canvas" + index
                            this.markBg = canvas.toDataURL()
                            this.markStatus = true
                        },
                        err => {
                            console.log('转换失败')
                        }
                    )
                }
            })
        },
        // 获取题号
        getQuIndex(typeIndex, index) {
            let sum = 0
            let _this = this
            function count(typeIndex) {
                if (typeIndex == 0) {
                    sum += index + 1
                } else if (typeIndex > 0) {
                    typeIndex--
                    sum += _this.groupList[typeIndex].list.length
                    count(typeIndex)
                }
            }
            count(typeIndex)
            return sum
        },
        //获取socre和answer Index
        getScoreIndex(typeIndex, index, childIndex = 0) {
            let sum = childIndex
            let _this = this
            if (_this.groupList[typeIndex].type == 'compose') {
                for (let qIndex = 0; qIndex < index; qIndex++) {
                    sum += _this.groupList[typeIndex].list[qIndex].children.length - 1
                }
            }
            function count(typeIndex) {
                if (typeIndex == 0) {
                    sum += index
                } else if (typeIndex > 0) {
                    typeIndex--
                    sum += _this.groupList[typeIndex].list.length
                    count(typeIndex)
                }
            }
            count(typeIndex)
            return sum
        },
        //点评下一位学生
        nextStu() {
            this.$emit('nextStu')
        },
        //快速定位题目
        goToQuestion(index) {
            this.activeIndex = index
            let dom = this.$el.querySelector('#qustion' + index)
            if (dom) {
                dom.scrollIntoView({
                    behavior: "smooth",  // 平滑过渡
                    block: "center"  // 上边框与视窗顶部平齐。默认值
                })
            }
        },
        //快速打分
        fastSetScore(index, score) {
            this.$set(this.studentAnswer.scores, index, score)
            this.setUpdStatus()
        },
        // 加分
        scoreUp(index, totalScore) {
            if (this.studentAnswer.scores[index] < totalScore) {
                this.$set(this.studentAnswer.scores, index, ++this.studentAnswer.scores[index])
                this.setUpdStatus()
            } else {
                this.$Message.warning(this.$t('learnActivity.score.isFullTips'))
            }
        },
        // 减分
        scoreDown(index) {
            if (this.studentAnswer.scores[index] > 0) {
                this.$set(this.studentAnswer.scores, index, --this.studentAnswer.scores[index])
                this.setUpdStatus()
            } else {
                this.$Message.warning(this.$t('learnActivity.score.isZeroTips'))
            }
        },

        //保存学生分数
        saveScore() {
            let requestData = {
                "id": this.examId,
                // "code": this.examScope == 'school' ? this.$store.state.userInfo.schoolCode : this.$store.state.userInfo.TEAMModelId,//暂时取代上面的方式
                "code": this.owner == 'school' ? this.$store.state.userInfo.schoolCode : this.$store.state.userInfo.TEAMModelId,//暂时取代上面的方式
                "point": this.studentAnswer.scores,
                "studentId": this.studentAnswer.id,
                "classId": this.studentAnswer.classId,
                "school": this.examScope == 'school' ? this.$store.state.userInfo.schoolCode : this.$store.state.userInfo.TEAMModelId,//暂时取代上面的方式
                "subjectId": this.subjectId
            }
            this.$api.learnActivity.UpsertAllRecord(requestData).then(res => {
                if (res.error == null) {
                    this.$Message.success(this.$t('learnActivity.score.saveScoreOk'))
                    this.isUpd = false
                    this.$emit('updScore', this.studentAnswer)
                    if (!this.studentAnswer.scores.includes(-1)) {
                        this.isComplete = true
                    }
                } else {
                    this.$Message.error(this.$t('learnActivity.score.saveSocreErr'))
                }
            })
        },
        openAnswer() {
            this.$refs.exPaper.onHandleToggles(this.isAllOpen)
            this.isAllOpen = !this.isAllOpen
        },

        /**
         * 数字与中文转换
         * @param num
         */
        numberConvertToUppercase(num) {
            num = Number(num)
            var upperCaseNumber = [
                this.$t('learnActivity.score.zero'),
                this.$t('learnActivity.score.one'),
                this.$t('learnActivity.score.two'),
                this.$t('learnActivity.score.three'),
                this.$t('learnActivity.score.four'),
                this.$t('learnActivity.score.five'),
                this.$t('learnActivity.score.six'),
                this.$t('learnActivity.score.seven'),
                this.$t('learnActivity.score.eight'),
                this.$t('learnActivity.score.nine'),
                this.$t('learnActivity.score.ten'),
                this.$t('learnActivity.score.hundred'),
                this.$t('learnActivity.score.thousand'),
                this.$t('learnActivity.score.tenThd'),
                this.$t('learnActivity.score.hMillion')
            ]
            var length = String(num).length
            if (length === 1) {
                return upperCaseNumber[num]
            } else if (length === 2) {
                if (num === 10) {
                    return upperCaseNumber[num]
                } else if (num > 10 && num < 20) {
                    return this.$t('learnActivity.score.ten') + upperCaseNumber[String(num).charAt(1)]
                } else {
                    return upperCaseNumber[String(num).charAt(0)] + this.$t('learnActivity.score.ten') + upperCaseNumber[String(num).charAt(1)].replace(this.$t('learnActivity.score.zero'), '')
                }
            }
        },
        getLatestTypeIndex(type) {
            let arr = []
            this.groupList.forEach(i => {
                if (i.list.length) {
                    arr.push(i.type)
                }
            })
            return arr.indexOf(type)
        }
    },
    watch: {
        paper: {
            handler(newValue, oldValue) {
                this.paperInfo = newValue
            },
            deep: true
        },
        paperInfo: {
            handler(newPaper) {
                if (newPaper && newPaper.item) {
                    this.dataLoading = true
                    let that = this
                    this.groupList = []
                    this.exerciseList = []
                    if (newPaper.item.length) {
                        let index = 0
                        newPaper.item.forEach((i) => {
                            //记录题目原始位置
                            if (i.type == 'compose') {
                                i.children.forEach((cItem) => {
                                    cItem.index = index
                                    index++
                                })
                            } else {
                                i.index = index
                                index++
                            }
                            if (!i.score) i.score = 0
                        })
                        /* 处理试卷内题目按照题型排序 */
                        this.typeList.forEach(item => {
                            this._.mapKeys(this._.groupBy(newPaper.item, 'type'), function (value, key) {
                                if (key === item) { /* 按照题型排序，并且计算每种题型的总分 */
                                    that.groupList.push({
                                        type: key,
                                        list: value,
                                        score: value.reduce((p, e) => parseInt(p) + parseInt(e.score), 0)
                                    })
                                    that.exerciseList = that.exerciseList.concat(value)
                                }
                            })
                        })
                    }
                    this.dataLoading = false
                }
            },
            deep: true
        },
        pStudentAnswer: {
            async handler(newValue, oldValue) {
                this.studentAnswer = this._.cloneDeep(newValue || {})
                console.log(this.studentAnswer)
                if (!this.studentAnswer.status && this.studentAnswer.answers && this.studentAnswer.scores) {
                    if (this.studentAnswer.answers.length) {
                        try {
                            let sas = this.examScope == 'school' ? this.$store.state.user.schoolProfile.blob_sas : this.$store.state.user.userProfile.blob_sas
                            let blobUrl = this.examScope == 'school' ? JSON.parse(decodeURIComponent(localStorage.school_profile, "utf-8")).blob_uri : JSON.parse(decodeURIComponent(localStorage.user_profile, "utf-8")).blob_uri
                            let a = null
                            /**
                             * 1、批注逻辑调整，每个题目的批注单独保存成图片；
                             * 2、这里就直接读取原始作答数据；
                             * 3、在渲染的时候再判断当前题目是否有批注数据。
                             */
                            a = await this.$tools.getFile(`${blobUrl}/exam/${this.studentAnswer.answers[0]}?${sas}`)

                            if (a) {
                                let ans = JSON.parse(a)
                                ans.forEach((item, index) => {
                                    if (!item.length) ans[index] = [this.$t('learnActivity.score.noStuAns')]
                                })
                                this.$set(this.studentAnswer, 'answers', ans)
                            } else {
                                this.$set(this.studentAnswer, 'answers', [])
                            }
                        } catch (e) {
                            console.log('error', e)
                        }
                    } else {
                        let a = this.studentAnswer.scores.map(item => {
                            return [this.$t('learnActivity.score.noStuAns1')]
                        })
                        this.$set(this.studentAnswer, 'answers', a)
                    }
                    this.studentAnswer.status = true
                    this.$nextTick(() => {
                        this.activeIndex = this.defaultIndex
                        this.goToQuestion(this.defaultIndex)
                    })
                }
            },
            deep: true,
            immediate: true
        }
    },
    computed: {
        scoreTotal() {
            if (this.studentAnswer && this.studentAnswer.scores) {
                let s = this.studentAnswer.scores.reduce((prev, cur) => {
                    cur = cur < 0 ? 0 : cur
                    return prev + cur
                }, 0)
                return s
            }
            return 0
        },
        answerOrMark() {
            //如果当前老师已经批注过，再次批注就复用前面的批注数据
            if (this.studentAnswer.mark && this.studentAnswer.mark[this.curAnIndex]) {
                let d = this._.cloneDeep(this.studentAnswer.mark[this.curAnIndex])
                let markData = d.find(item => {
                    return item.tmdId == this.$store.state.userInfo.TEAMModelId
                })
                if (markData) {
                    let sas = this.examScope == 'school' ? this.$store.state.user.schoolProfile.blob_sas : this.$store.state.user.userProfile.blob_sas
                    let blobUrl = this.examScope == 'school' ? JSON.parse(decodeURIComponent(localStorage.school_profile, "utf-8")).blob_uri : JSON.parse(decodeURIComponent(localStorage.user_profile, "utf-8")).blob_uri
                    let url = blobUrl + '/' + markData.mark + '?' + sas
                    let h = `<img src=\"${url}\"/>`
                    return [h]
                }
            }
            return this.studentAnswer && this.studentAnswer.answers ? this.studentAnswer.answers[this.curAnIndex] : undefined
        }
    },
    created() {
        if (this.$route.name == 'privateEvaluation') {
            this.scope = 'private'
        } else {
            this.scope = 'school'
        }
    }
}
</script>

<style scoped lang="less">
@import "./ByStuMark.less";
</style>
<style lang="less">
.scoring-input-box .ivu-input-number-handler-wrap {
    display: none;
}
.stu-answer-box img {
    max-width: 100%;
}
.mark-modal .ivu-modal-body {
    padding: 0px;
}
</style>
<style scoped>
#answerIframe {
    position: fixed;
    top: 9990px;
    width: 850px;
    background: #f5f5f5;
}
</style>

