<template>
    <div class="qu-mark-container">
        <Loading :top="200" type="1" style="text-align:center" v-show="dataLoading"></Loading>
        <div class="scoring-paper-header">
            <span class="base-info-item" style="white-space: nowrap;">
                {{$t('learnActivity.score.quIndex')}}
            </span>
            <span class="qu-no-value qu-no-active" @click="toggleQuIndex">
                {{quNoList.length ? quNoList[quIndex].label : '-'}}
            </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="markByStu">
                <Icon type="ios-create" />
                {{$t('learnActivity.score.byStuMark')}}
            </span>
        </div>
        <!-- 学生列表 -->
        <div class="student-wrap">
            <span @click="selectStudent(index)" v-for="(item,index) in studentsData" :key="index" :class="['qu-order-tag', stuIndex == index ? 'qu-order-tag-active' : '']">
                {{item.name}}
            </span>
        </div>
        <!-- 题目显示区域 -->
        <div class="question-wrap" v-show="showQu">
            <p class="qu-info-title" style="display:block">{{$t('learnActivity.score.question')}}</p>
            <!-- 题号 -->
            <span>{{ quNoList.length ? quNoList[quIndex].label : '' }} .</span>
            <!-- 题干 -->
            <span v-html="questionInfo.question"></span>
            <!-- 选项 -->
            <div v-for="(option,optionIndex) in questionInfo.option" :key="'op' + optionIndex" class="item-options">
                <div style="margin-top:10px">
                    <span class="item-option-order">{{String.fromCharCode(64 + parseInt(optionIndex+1))}} :</span>
                    <span class="item-option-text" v-html="option.value"></span>
                </div>
            </div>
        </div>
        <!-- 学生作答显示区域 -->
        <div class="answer-wrap">
            <div>
                <span class="stu-answer-label">{{$t('learnActivity.score.stuAns')}}</span>
                <template v-if="studentsData[stuIndex] && studentsData[stuIndex].data">
                    <InputNumber @on-change="setUpdStatus" v-model="studentsData[stuIndex].data[quIndex]" size="small" :formatter="value => value < 0 ? '' : `${value}${$t('learnActivity.score.scoreUnit')}`" :parser="value => value.replace($t('learnActivity.score.scoreUnit'), '')" :min="0" :max="questionInfo.score" :placeholder="$t('learnActivity.score.zeroScore1')" class="score-input" />
                </template>
                <span class="mark-action-item" style="background:#ed4014" @click="markStuAnswer()" v-if="quNoList.length && quNoList[quIndex] && !quNoList[quIndex].disabled">
                    <Icon type="md-create" />
                    <span style="margin-left:5px;">{{$t('learnActivity.score.mark')}}</span>
                </span>
                <span v-if="studentsData[stuIndex] && studentsData[stuIndex].mark && studentsData[stuIndex].mark[quIndex].length" class="mark-action-item" style="background:#19be6b" @click="viewMark()">
                    <Icon type="md-eye" />
                    <span style="margin-left:5px;">{{$t('learnActivity.score.view')}}</span>
                </span>
            </div>
            <div class="answer-box" v-if="studentsData[stuIndex] && studentsData[stuIndex].answer && studentsData[stuIndex].answer[quIndex]" v-html="studentsData[stuIndex].answer[quIndex].toString()"></div>
            <div v-else class="answer-box" style="color:#ed4014">
                {{$t('learnActivity.score.noStuAnswer')}}
            </div>
        </div>
        <!-- 参考答案区域 -->
        <div class="solution-wrap" v-show="showAnswer">
            <!-- 答案展示部分 -->
            <div class="item-explain">
                <span class="qu-info-title">{{$t('learnActivity.score.quAns')}}</span>
                <div class="item-explain-details">
                    <!-- 问答题答案 -->
                    <div v-if="questionInfo.type === 'subjective'">
                        <span v-for="(answer,index) in questionInfo.answer" :key="index" v-html="questionInfo.answer.length ? answer : $t('learnActivity.score.noAnswer')"></span>
                    </div>
                    <!-- 填空题答案 -->
                    <div v-else-if="questionInfo.type === 'complete'">
                        <span :class="[ questionInfo.type === 'complete' ? 'item-answer-item':'']" v-for="(answer,index) in questionInfo.answer" :key="index" v-html="answer"></span>
                    </div>
                    <!-- 其余题型答案 -->
                    <div v-else>
                        <span v-for="(answer,index) in questionInfo.answer" :key="index" v-html="answer"></span>
                    </div>
                </div>
            </div>
            <!-- 解析部分 -->
            <div class="item-explain">
                <span class="qu-info-title">{{$t('learnActivity.score.anaLabel')}}</span>
                <div class="item-explain-details">
                    <span v-html="questionInfo.explain || $t('learnActivity.score.noAna')"></span>
                </div>
            </div>
            <!-- 知识点部分 -->
            <div class="item-explain">
                <span class="qu-info-title">{{$t('learnActivity.score.kdLabel')}}</span>
                <div class="item-explain-details">
                    <span v-if="!questionInfo.knowledge || (_.compact(questionInfo.knowledge).length)">{{$t('learnActivity.score.noKd')}}</span>
                    <div v-else>
                        <span v-for="(point,index) in questionInfo.knowledge" :key="index" class="item-point-tag">
                            {{ point }}
                        </span>
                    </div>
                </div>
            </div>
        </div>
        <Modal v-model="toggleQuStatus" :title="$t('learnActivity.score.toggleQu')" @on-ok="quIndex = selectIndex" @on-cancel="selectIndex = quIndex">
            <span :class="['qu-no-value', selectIndex == index ? 'qu-no-active' : '' ]" v-for="(item,index) in quNoList" :key="index" @click="selectIndex = index">
                {{item.label}}
            </span>
        </Modal>
        <Modal v-model="markStatus" fullscreen :title="$t('learnActivity.score.mark')" class-name="mark-modal" @on-ok="saveMark()" @on-cancel="closeModal">
            <BaseMark2 v-if="markStatus" defaultStatus="line" :bgImg="markBg" @onMarkChange="getMarkData"></BaseMark2>
        </Modal>
        <!-- 用来单独渲染学生作答数据，提高tocanvas 的效率 -->
        <iframe id="byQuIframe" :srcdoc="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 BaseMark2 from '@/components/mark/BaseMark.vue'
import BlobTool from '@/utils/blobTool.js'
export default {
    components: {
        BaseMark2
    },
    props: {
        examInfo: {
            type: Object,
            default: () => {
                return {}
            },
            required: true
        },
        subjectId: {
            type: String,
            default: '',
            required: true
        },
        classId: {
            type: String,
            default: '',
            required: true
        },
        stusInfo: {
            type: Array,
            default: () => {
                return []
            }
        },
        stusMark: {
            type: Array,
            default: () => {
                return []
            }
        },
        paper: {
            type: Object,
            default: () => { }
        },
        defaultQuIndex: {
            type: Number,
            default: 0
        }

    },
    data() {
        return {
            isUpd: false,
            viewStatus: false,
            viewMarks: [],
            markBg: '',
            markStatus: false,
            studentsData: [],
            toggleQuStatus: false,
            dataLoading: false,
            showAnswer: false,
            showQu: false,
            paperInfo: {
                item: []
            },
            quIndex: 0,
            selectIndex: 0,
            stuIndex: 0
        }
    },
    methods: {
        setUpdStatus() {
            this.isUpd = true
        },
        //查看批注数据
        viewMark(index) {
            this.viewIndex = index
            this.viewStatus = true
            if (this.studentsData[this.stuIndex] && this.studentsData[this.stuIndex].mark) {
                let sas = this.examInfo.scope == 'school' ? this.$store.state.user.schoolProfile.blob_sas : this.$store.state.user.userProfile.blob_sas
                let blobUrl = this.examInfo.scope == '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.studentsData[this.stuIndex].mark[this.quIndex])
                d.forEach(item => {
                    item.url = blobUrl + '/' + item.mark + '?' + sas
                })
                this.viewMarks = d
            } else {
                this.viewMarks = []
            }
        },
        closeModal() {
            this.markStatus = false
            let answerIframe = document.getElementById('byQuIframe')
            answerIframe.onload = () => { }
        },
        saveMark() {
            if (!this.markData.base64) {
                return
            }
            // 判断当前教师是否已有批注
            let fileName, hasMarked
            if (this.studentsData[this.stuIndex].mark && this.studentsData[this.stuIndex].mark[this.quIndex]) {
                let d = this._.cloneDeep(this.studentsData[this.stuIndex].mark[this.quIndex])
                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(this.markData.base64, fileName)
            //保存批注图片
            let sas = this.examInfo.scope == 'school' ? this.$store.state.user.schoolProfile.blob_sas : this.$store.state.user.userProfile.blob_sas
            let blobUrl = this.examInfo.scope == '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.examInfo.scope)
            let path = `exam/${this.examInfo.id}/${this.subjectId}/${this.studentsData[this.stuIndex].id}`
            blobTool.upload(markPng, path).then(
                res => {
                    if (!hasMarked) {
                        this.studentsData[this.stuIndex].mark[this.quIndex].push({
                            mark: path + '/' + fileName,
                            tmdId: this.$store.state.userInfo.TEAMModelId
                        })
                    }
                    this.markStatus = false
                    //保存批注数据
                    this.$api.learnActivity.upsertAnswer({
                        "id": this.examInfo.id,
                        "studentId": this.studentsData[this.stuIndex].id,
                        "subjectId": this.subjectId,
                        "classId": this.studentsData[this.stuIndex].classId,
                        "code": this.examInfo.scope == 'school' ? this.$store.state.userInfo.schoolCode : this.$store.state.userInfo.TEAMModelId,
                        "tmdId": this.$store.state.userInfo.TEAMModelId,
                        "index": this.quIndex,//题号
                        "mark": {
                            sc: 0,//分数
                            tmdId: this.$store.state.userInfo.TEAMModelId,
                            mark: path + '/' + fileName,//批注BLOB地址
                            identity: 'admin',//老师身份，这是是固定管理员身份
                            index: this.quIndex //题号
                        }
                    }).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'))
                }
            )
        },
        getMarkData(data) {
            this.markData = data
        },
        // 批注学生作答数据
        markStuAnswer() {
            this.$nextTick(() => {
                let answerIframe = document.getElementById('byQuIframe')
                answerIframe.srcdoc = this.answerOrMark
                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
                    bodyWidth = bodyWidth == 0 ? 600 : bodyWidth
                    answerIframe.style.width = (bodyWidth + 20) + 'px'
                    answerIframe.contentWindow.document.body.style.backgroundColor = '#f5f5f5'
                    html2canvas(answerIframe.contentWindow.document.body, {
                        useCORS: true
                    }).then(
                        (canvas) => {
                            this.markBg = canvas.toDataURL()
                        },
                        err => {
                            console.log('转换失败', err)
                        }
                    )
                }
            })
            this.markStatus = true
        },
        markByStu() {
            this.$emit('toggleMarkType', 'byStu')
        },
        saveScore() {
            let requestData = {
                "id": this.examInfo.id,
                "code": this.examInfo.owner == 'school' ? this.$store.state.userInfo.schoolCode : this.$store.state.userInfo.TEAMModelId,
                "point": this.studentsData[this.stuIndex].data,
                "studentId": this.studentsData[this.stuIndex].id,
                "classId": this.classId,
                "school": this.examInfo.scope == '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
                    if (this.stuIndex < this.studentsData.length - 1) {
                        this.stuIndex++
                        this.selectStudent(this.stuIndex)
                    }
                } else {
                    this.$Message.error(this.$t('learnActivity.score.saveSocreErr'))
                }
            })
        },
        toggleQuIndex() {
            this.selectIndex = this.quIndex
            this.toggleQuStatus = !this.toggleQuStatus
        },
        selectStudent(index) {
            if (this.isUpd) {
                this.$Modal.confirm({
                    title: this.$t('learnActivity.score.saveScoreTitle'),
                    content: this.$t('learnActivity.score.saveScoreContent'),
                    okText: this.$t('learnActivity.mark.yes'),
                    cancelText: this.$t('learnActivity.mark.no'),
                    onOk: () => {
                        this.saveScore()
                        this.stuIndex = index
                        if (this.studentsData[index] && !this.studentsData[index].answer) {
                            this.getStuAnswer(this.studentsData[index].ansBlob)
                        }
                    },
                    onCancel: () => {
                        this.isUpd = false
                        this.stuIndex = index
                        if (this.studentsData[index] && !this.studentsData[index].answer) {
                            this.getStuAnswer(this.studentsData[index].ansBlob)
                        }
                    }
                })
            } else {
                this.stuIndex = index
                if (this.studentsData[index] && !this.studentsData[index].answer) {
                    this.getStuAnswer(this.studentsData[index].ansBlob)
                }
            }
        },
        async getStuAnswer(ansBlob) {
            if (!ansBlob || !ansBlob.length) {
                return
            }
            try {
                let sas = this.examInfo.scope == 'school' ? this.$store.state.user.schoolProfile.blob_sas : this.$store.state.user.userProfile.blob_sas
                let blobUrl = this.examInfo.scope == '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/${ansBlob[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.studentsData[this.stuIndex], 'answer', ans)
                } else {
                    this.$set(this.studentsData[this.stuIndex], 'answer', [])
                }
            } catch (e) {
                console.log(e)
                this.$Message.error('获取学生作答数据异常')
            }
        }
    },
    watch: {
        stusInfo: {
            handler(n, o) {
                this.studentsData = this._.cloneDeep(n)
                if (this.studentsData.length) {
                    this.selectStudent(0)
                }
            },
            deep: true
        },
        paper: {
            handler(newValue, oldValue) {
                this.paperInfo = newValue
            },
            deep: true,
            immediate: true
        },
        defaultQuIndex: {
            handler(n, o) {
                this.quIndex = this.defaultQuIndex
            }
        }
    },
    computed: {
        //当前题目信息
        questionInfo() {
            if (this.paperInfo.item && this.paperInfo.item.length) {
                let data
                for (let item of this.paperInfo.item) {
                    if (item.index != undefined) {
                        if (item.index == this.quIndex) {
                            data = this._.cloneDeep(item)
                            break
                        }
                    } else if (item.children) {
                        item.children.forEach(child => {
                            if (child.index == this.quIndex) {
                                data = this._.cloneDeep(child)
                            }
                        })
                        if (data) {
                            break
                        }
                    }
                }
                return data ? data : {}
            }
            return {}
        },
        //试卷题号列表
        quNoList() {
            if (this.paperInfo.item && this.paperInfo.item.length) {
                let objectiveQu = ['single', 'multiple', 'judge']
                let data = []
                let realIndex = 0
                this.paperInfo.item.forEach((item, index) => {
                    if (item.children.length) {
                        item.children.forEach((childItem, childIndex) => {
                            let i = realIndex++
                            data.push({
                                label: (index + 1) + '-' + (childIndex + 1),
                                value: i,
                                disabled: objectiveQu.includes(childItem.type)
                            })
                        })
                    } else {
                        let i = realIndex++
                        data.push({
                            label: (index + 1) + '',
                            value: i,
                            disabled: objectiveQu.includes(item.type)
                        })
                    }
                })
                return data
            }
            return []
        },
        answerOrMark() {
            //如果当前老师已经批注过，再次批注就复用前面的批注数据
            if (this.studentsData[this.stuIndex] && this.studentsData[this.stuIndex].mark) {
                let d = this._.cloneDeep(this.studentsData[this.stuIndex].mark[this.quIndex])
                let markData = d.find(item => {
                    return item.tmdId == this.$store.state.userInfo.TEAMModelId
                })
                if (markData) {
                    let sas = this.examInfo.scope == 'school' ? this.$store.state.user.schoolProfile.blob_sas : this.$store.state.user.userProfile.blob_sas
                    let blobUrl = this.examInfo.scope == '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.studentsData[this.stuIndex] && this.studentsData[this.stuIndex].answer ? this.studentsData[this.stuIndex].answer[this.quIndex] : this.$t('learnActivity.score.noStuAnswer')
        }
    }
}
</script>
<style lang="less" scoped>
.solution-wrap {
    padding: 10px;
}
.question-wrap {
    padding: 10px;
}
#byQuIframe {
    position: fixed;
    top: 9990px;
    width: 850px;
    background: #f5f5f5;
}
.qu-info-title {
    color: #00ad25;
    margin-left: -6px;
    margin-top: 20px;
    display: inline-block;
}
.stu-answer-label {
    color: #00ad25;
    margin-left: -6px;
}
.mark-action-item {
    color: white;
    padding: 5px 12px;
    float: right;
    // margin-top: -7px;
    cursor: pointer;
}
.answer-box {
    border: 2px solid #01b4ef;
    padding: 15px;
    margin-top: 7px;
    min-height: 200px;
}
.answer-wrap {
    margin-top: 30px;
    padding: 10px;
}
.qu-no-value {
    font-size: 14px;
    font-weight: 600;
    color: #515a6e;
    width: 40px;
    height: 24px;
    line-height: 24px;
    display: inline-block;
    border-radius: 12px;
    // border: 1px solid #515a6e;
    text-align: center;
    box-shadow: 0px 0px 5px #515a6e;
    cursor: pointer;
    margin-bottom: 10px;
    margin-right: 10px;
    user-select: none;
}
.qu-no-active {
    color: #2d8cf0;
    box-shadow: 0px 0px 5px #2d8cf0;
}
.qu-mark-container {
    width: 100%;
    padding: 15px;
    min-height: 600px;
}
.base-info-btn {
    margin-left: 5px;
    margin-right: 10px;
    float: right;
    user-select: none;
    cursor: pointer;
}
.qu-order-tag {
    display: inline-block;
    user-select: none;
    border-radius: 2px;
    background-color: #1cc0f3;
    color: white;
    cursor: pointer;
    margin-right: 5px;
    line-height: 16px;
    text-align: center;
    font-size: 12px;
    padding: 2px 6px;
}
.qu-order-tag-def {
    display: inline-block;
    height: 18px;
    border-radius: 4px;
    background-color: #e5e5e5;
    color: black;
    cursor: pointer;
    margin-right: 5px;
    line-height: 16px;
    text-align: center;
    font-size: 12px;
    padding: 2px 6px;
}
.qu-order-tag-active {
    background-color: #19be6b;
    color: white;
    box-shadow: 0px 0px 5px #aaa;
}
.student-wrap {
    border-bottom: 1px dashed #c3c3c34d;
    padding-bottom: 20px;
    margin-top: 10px;
}
</style>
<style lang="less">
</style>