<template>
    <!-- 未做多语言 -->
    <div class="mark-area">
        <!-- 头部基础信息 -->
        <div class="mark-header">
            <span class="quit-marking-text">
                <Icon type="ios-arrow-back" class="quit-marking-icon" title="退出阅卷" @click="quit" />
            </span>
            <span class="info-label">考试名称：</span>
            <span class="info-value">{{taskInfo.name}}</span>
            <span class="info-label">阅卷方式：</span>
            <span class="info-value">按人阅卷</span>
            <span class="info-label">学生id：</span>
            <span class="info-value stu-id-info">{{stuId}}</span>
            <span class="info-label">分数：</span>
            <span class="info-value score-info">{{totalScore}}</span>
            <span class="info-label">当前题号：</span>
            <span class="info-value cur-qu-index" v-if="childIndex > -1">{{`${quIndex + 1}-${childIndex + 1}`}}</span>
            <span class="info-value cur-qu-index" v-else>{{quIndex + 1}}</span>
            <div class="btn-wrap">
                <span class="action-btn" @click="toggleStatus = !toggleStatus">
                    <Icon type="md-shuffle" class="action-btn-icon" />
                    切换
                </span>
                <span class="action-btn">
                    <Icon type="md-refresh" class="action-btn-icon" />
                    回评
                </span>
                <span class="action-btn">
                    <Icon custom="iconfont icon-exception" class="action-btn-icon" />
                    异常申报
                </span>
            </div>
        </div>
        <div class="mark-main">
            <!-- 工具条 -->
            <div class="mark-tools-wrap">
                <Icon custom="iconfont icon-move" class="tool-icon" title="移动" @click="mouseStatus = 'move'" />
                <Icon custom="iconfont icon-text" class="tool-icon" title="文字批注" @click="mouseStatus = 'text'" />
                <Icon custom="iconfont icon-mark" class="tool-icon" title="画笔" @click="mouseStatus = 'line'" />
                <Icon custom="iconfont icon-arrow-mark" class="tool-icon" title="箭头" @click="mouseStatus = 'arrow'" />
                <Icon custom="iconfont icon-oval" class="tool-icon" title="椭圆" @click="mouseStatus = 'oval'" />
                <Icon custom="iconfont icon-rect" class="tool-icon" title="方框" @click="mouseStatus = 'rect'" />
                <Poptip transfer placement="right">
                    <Icon custom="iconfont icon-smile" class="tool-icon" title="图标" />
                    <div slot="content" class="expression-box">
                        <img v-for="(item,index) in imgs" :key="index" :src="item" alt="" class="expression-img" @click="drawImg(index)">
                    </div>
                </Poptip>
                <Icon custom="iconfont icon-fresh" class="tool-icon" title="清除批注" @click="clear" />
                <!-- <Icon :custom="isFull ? 'iconfont icon-cancel-full' : 'iconfont icon-full-screen'" class="tool-icon" :title="isFull ? '取消全屏' : '全屏'" @click="togglefull" /> -->
            </div>
            <div class="mark-stage">
                <MarkCanvas :mouseStatus="mouseStatus" :bgImg="ansImg" :drawImgData="drawImgData" style="padding-bottom:85px"></MarkCanvas>
                <!-- 题号显示部分 -->
                <div class="qu-index-box">
                    <div class="qu-tips-box">
                        <span class="qu-tips-tag">
                            已阅
                        </span>
                        <span class="qu-tips-tag">
                            未阅
                        </span>
                    </div>
                    <div>
                        <span v-for="(item,index) in paperData.item" :key="index">
                            <!-- 综合题 -->
                            <span v-if="item.children.length" :key="index">
                                <span @click="toQu(index,childIndex)" v-for="(childItem,childIndex) in item.children" :key="childIndex" :class="['qu-index',stuScore[getScoreIndex(index,childIndex)] > -1 ? 'right-qu' : '']">
                                    {{(index + 1) + '-' + (childIndex + 1)}}
                                </span>
                            </span>
                            <!-- 其他题 -->
                            <span v-else @click="toQu(index)" :class="['qu-index',stuScore[getScoreIndex(index)] > -1 ? 'right-qu' : '']">
                                {{index + 1}}
                            </span>
                        </span>
                    </div>
                </div>
            </div>
            <!-- 打分部分 -->
            <div class="score-wrap">
                <div class="quick-score-box score-input-box">
                    <span>分数：</span>
                    <InputNumber style="flex:1" :max="10" :min="1" v-model="score" @on-change="setScore"></InputNumber>
                </div>
                <div class="quick-score-box">
                    <Button size="small" type="info" style="margin-right:8px" ghost @click="score = 10">满分</Button>
                    <Button size="small" type="error" ghost @click="score = 0">零分</Button>
                    <Icon :type="isShowNum ? 'md-eye-off' : 'md-eye'" class="toggle-num-status" @click="isShowNum = !isShowNum" />
                    <div :class="['score-key-box', isShowNum ? '':'hind-key-box']">
                        <vuescroll>
                            <span v-for="(item,index) in quScoreArr" :key="index" :class="['score-key', stuScore[getScoreIndex(quIndex,childIndex)] == index ? 'score-key-active':'']" @click="setScore(index)">
                                {{item}}
                            </span>
                        </vuescroll>
                    </div>
                </div>
                <Button type="success" class="submit-score" @click="submit()">提交分数</Button>
                <div class="score-setting-wrap">
                    <div class="score-setting-item">
                        <span>打分自动切换题目</span>
                        <i-switch v-model="autoQu" size="small" />
                    </div>
                    <div class="score-setting-item">
                        <span>完成阅卷自动获取新学生</span>
                        <i-switch v-model="autoStu" size="small" />
                    </div>
                </div>
            </div>
        </div>
        <!-- 用来单独渲染学生作答数据，提高tocanvas 的效率 -->
        <iframe id="markIframe" :srcdoc="curAnswer"></iframe>
        <Modal v-model="toggleStatus" title="切换学生" :width="800" footer-hide>
            <StuProg  @getStuId="toByStuView" class="light-stu-prog" :total="taskInfo.count" :stusData="stusData"></StuProg>
        </Modal>
    </div>
</template>

<script>
import html2canvas from 'html2canvas'
import MarkCanvas from './MarkCanvas'
import StuProg from './StuProg.vue'
export default {
    name: 'ByStu',
    components: {
        MarkCanvas, StuProg
    },
    data() {
        return {
            score: null,
            mouseStatus: 'move',
            drawImgData: '',
            ansImg: '',
            imgs: [],
            autoQu: true,//自动切换下一题
            autoStu: true,//自动获取下一学生
            toggleStatus: false,
            activeIcon: -1,
            isShowNum: true,
            quIndex: 0,
            childIndex: -1,
            stuData: {
                name: '',
                id: '',
            },
            paperData: {
                item: []
            },
            stuAnswer: [],
            stuScore: [],
            taskInfo: {},
            stusData: [],
            stuId: ''
        }
    },
    methods: {
        /**
         * 按人阅卷
         */
        toByStuView(stuId) {
            this.$Message.warning('这里切换学生逻辑暂未处理！')    
        },
        drawImg(imgIndex) {
            // this.activeIcon = imgIndex
            // this.curImg = new Image()
            // this.curImg.src = this.imgs[imgIndex]
            // this.curImg.onload = () => {
            //     this.mouseStatus = 'img'
            //     this.startImg({ x: 100, y: 100 })
            // }
        },
        //清除所有批注
        clear() {

            // this.markLayer.removeChildren()
            // this.stage.add(this.markLayer)
        },
        /**将答案绘制到canvas上 */
        ansToImg() {
            let answerIframe = document.getElementById('markIframe')
            answerIframe.onload = () => {
                answerIframe.style.width = '850px'
                // answerIframe.contentWindow.document.body.style.margin = '0px 20px'
                answerIframe.contentWindow.document.body.style.padding = '10px'
                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, {}).then((canvas) => {
                    canvas.id = "canvas" + this.getScoreIndex(this.quIndex, this.childIndex)
                    this.ansImg = canvas.toDataURL()
                    // 将转出来的答案绘制到canvas上
                })
            }
        },
        //将图片（答案）绘制到canvas
        imgToCanvas(img) {
            console.log('将图片（答案）绘制到canvas', img)
        },
        /** 打分 */
        setScore(score) {
            this.score = score
            this.$set(this.stuScore, this.getScoreIndex(this.quIndex, this.childIndex), score)
            if (this.autoQu) {
                this.submit()
            }
        },
        toQu(index, childIndex) {
            this.quIndex = index
            this.childIndex = childIndex
            this.score = this.stuScore[this.getScoreIndex(this.quIndex, this.childIndex)] == -1 ? null : this.stuScore[this.getScoreIndex(this.quIndex, this.childIndex)]
        },
        /**
         * index 题目index 必传
         * childIndex 小题index 非必传 
         */
        getScoreIndex(index, childIndex) {
            let realIndex = 0
            this.paperData.item.forEach((item, itemIndex) => {
                if (itemIndex <= index) {
                    //综合题
                    if (item.children.length) {
                        item.children.forEach((childItem, cIndex) => {
                            if (itemIndex < index) {
                                realIndex++
                            } else if (cIndex <= childIndex) {
                                realIndex++
                            }
                        })
                    }
                    else {
                        realIndex++
                    }
                }
            })
            console.log('输出', realIndex)
            return --realIndex
        },
        //提交分数
        submit() {
            if (this.score > -1 && this.score != null) {
                let requstData = {
                    id: this.taskInfo.id,
                    stuId: this.stuId,
                    subjectId: this.taskInfo.subject,
                    tmdId: this.$store.state.userInfo.TEAMModelId,
                    score: this.stuScore,
                    count: this.taskInfo.count,
                    code: this.taskInfo.ecode.replace('Exam-', ''),
                    mark: ''
                }
                this.$api.mark.saveScore(requstData).then(
                    res => {
                        this.$Message.success('保存成功')
                        // 按人阅卷自动跳转下一题
                        this.nextQuestion()
                        this.ansToImg()
                    },
                    err => {
                        this.$Message.error('保存失败')
                    }
                )
            } else {
                this.$Message.warning('请先打分')
            }
        },
        nextQuestion() {
            // 当前不是最后一题
            if (this.quIndex < this.paperData.item.length - 1) {
                //当前题目是综合题
                if (this.paperData.item[this.quIndex].children.length) {
                    //当前小题不是最后一个
                    if (this.childIndex < this.paperData.item[this.quIndex].children.length - 1) {
                        this.childIndex++
                    }
                    //当前小题是最后一个，需要判断下一个题目类型
                    //下一个题目是综合题
                    else if (this.childIndex == this.paperData.item[this.quIndex].children.length - 1 && this.paperData.item[this.quIndex + 1].children.length) {
                        this.quIndex++
                        this.childIndex = 0
                    }
                    // 下一个题目不是综合题
                    else {
                        this.quIndex++
                        this.childIndex = -1
                    }
                }
                //当前题目不是综合题
                else {
                    //下一个题目是综合题
                    if (this.paperData.item[this.quIndex + 1].children.length) {
                        this.quIndex++
                        this.childIndex = 0
                    }
                    // 下一个题目不是综合题
                    else {
                        this.quIndex++
                        this.childIndex = -1
                    }
                }
            }
            //如果是最后一题
            else {
                //当前题目是综合题，并且不是小题最后一题
                if (this.paperData.item[this.quIndex].children.length && this.childIndex < this.paperData.item[this.quIndex].children.length - 1) {
                    this.childIndex++
                }
                //当前目不是综合题 则代表题号已经到最后一个
                else {
                    //检查所有题目是否完成评测
                    if (this.stuScore.includes(-1)) {
                        let qu = ''
                        let quIndex = 0
                        let childIndex = -1
                        let realIndex = 0
                        // 检测具体未评分的题目
                        for (let i = 0; i < this.paperData.item.length; i++) {
                            if (this.paperData.item[i].children.length) {
                                let flag = false
                                for (let j = 0; j < this.paperData.item[i].children.length; j++) {
                                    if (this.stuScore[realIndex++] == -1) {
                                        quIndex = i
                                        childIndex = j
                                        flag = true
                                        break
                                    }
                                }
                                if (flag) {
                                    break
                                }
                            } else {
                                if (this.stuScore[realIndex++] == -1) {
                                    quIndex = i
                                    break
                                }
                            }
                        }
                        qu = childIndex > -1 ? `${(quIndex + 1)}-${(childIndex + 1)}` : quIndex
                        this.$Modal.confirm({
                            title: '未阅题目',
                            content: `${qu}题目尚未评分，是否跳转到对应题目继续评分？`,
                            onOk: () => {
                                this.quIndex = quIndex
                                this.childIndex = childIndex
                            }
                        })
                    } else {
                        this.$Message.success('已阅完')
                        if (this.autoStu) {
                            //TODE 随机获取下一位学生
                        }
                    }

                }
            }
            this.score = this.stuScore[this.getScoreIndex(this.quIndex, this.childIndex)] == -1 ? null : this.stuScore[this.getScoreIndex(this.quIndex, this.childIndex)]
        },

        quit() {
            // 返回页面
            this.$router.push({
                name: sessionStorage.getItem('markFrom')
            })
        },
        uuid() {
            function S4() {
                return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
            }
            return (S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4())
        },
    },
    mounted() {
        this.ansToImg()
    },
    created() {
        let routeData = this.$route.params
        this.paperData = routeData.fullPaper
        this.stuAnswer = routeData.answer
        this.stuScore = routeData.score
        this.stusData = routeData.stusData
        this.taskInfo = routeData.task
        this.stuId = routeData.stuId
        //初始化题目index
        if (this.paperData && this.paperData.item.length) {
            this.quIndex = 0
            if (this.paperData.item[this.quIndex] && this.paperData.item[this.quIndex].children.length) {
                this.childIndex = 0
            }
        }
        //默认表情包
        for (let i = 0; i < 9; i++) {
            this.imgs.push(require('@/assets/mark/' + i + '.jpg'))
        }
    },
    computed: {
        /**当期题目分数数组 */
        quScoreArr() {
            let score = 0
            if (this.childIndex > -1 && this.paperData.item[this.quIndex] && this.paperData.item[this.quIndex].children) {
                score = this.paperData.item[this.quIndex].children[this.childIndex].score
            } else {
                score = this.paperData.item[this.quIndex].score
            }
            return Array.from(new Array(score + 1).keys())
        },
        /**当前题目作答数据 */
        curAnswer() {
            if (this.stuAnswer.length) {
                let index = this.getScoreIndex(this.quIndex, this.childIndex)
                this.score = this.stuScore[index] == -1 ? null : this.stuScore[index]
                return this.stuAnswer[index]
            } else {
                return this.stuId + '未作答'
            }

        },
        totalScore() {
            return this.stuScore.reduce((a, b) => {
                a = a == -1 ? 0 : a
                b = b == -1 ? 0 : b
                return a + b
            }, 0)
        }
    }
}
</script>
<style scoped lang="less">
.light-stu-prog{
    margin-bottom: 15px;
}
.score-setting-wrap {
    margin-top: 50px;
    padding: 0px 5px;
}
.score-setting-item {
    margin-top: 15px;
    display: flex;
    justify-content: space-between;
}
.stu-id-info {
    color: black;
    font-size: 16px;
}
.score-info {
    background: #19be6b;
    color: white;
    padding: 1px 5px;
    border-radius: 4px;
    text-align: center;
    font-size: 16px;
}
.cur-qu-index {
    background: #2db7f5;
    color: white;
    padding: 1px 5px;
    border-radius: 4px;
    text-align: center;
    font-size: 16px;
}
#markIframe {
    position: fixed;
    top: 9990px;
    width: 850px;
    background: #f5f5f5;
}
.quit-marking-icon {
    display: inline-block;
    font-size: 18px;
    width: 40px;
    text-align: center;
    cursor: pointer;
    color: black;
}
.quit-marking-text {
    margin-right: 15px;
}
.expression-box {
    max-width: 300px;
    display: flex;
    flex-wrap: wrap;
    max-height: 600px;
}
.expression-img {
    width: 80px;
    margin: 10px;
    height: auto;
}

.qu-tips-box {
    & :nth-child(1)::before {
        background: #19be6b;
    }
    & :nth-child(2)::before {
        background: #e1e1e1;
    }
    & :nth-child(3)::before {
        background: #ed4014;
    }
    & :nth-child(4)::before {
        background: #e1e1e1;
    }
}

.qu-tips-tag {
    display: inline-block;
    margin-right: 15px;
    color: #909090;
    font-size: 12px;
    &::before {
        content: "";
        width: 15px;
        height: 10px;
        display: inline-block;
        border-radius: 3px;
        vertical-align: baseline;
    }
}
.qu-index {
    width: 30px;
    height: 22px;
    border-radius: 5px;
    display: inline-block;
    border: 1px solid #e1e1e1;
    line-height: 22px;
    text-align: center;
    margin-bottom: 5px;
    margin-top: 5px;
    margin-right: 5px;
    cursor: pointer;
    background: #f1f1f1;
    &:hover {
        // background: white;
        box-shadow: 0px 0px 4px rgba(70, 43, 43, 0.3);
    }
}
.right-qu {
    color: #fff;
    border-color: #19be6b;
    background: #19be6b;
}
.err-qu {
    color: #ed4014;
    border-color: #ed4014;
    background: white;
}
.half-qu {
    color: #ff9900;
    border-color: #ff9900;
    background: white;
}
.submit-score {
    width: 236px;
    margin-left: 2px;
}
.score-key-box {
    margin-top: 10px;
    height: 120px;
    transition: height 0.5s;
    -webkit-transition: height 0.5s;
    overflow: hidden;
}
.hind-key-box {
    height: 0px;
}
.score-key {
    display: inline-block;
    width: 30px;
    height: 30px;
    border-radius: 50%;
    border: 1px solid #e1e1e1;
    line-height: 30px;
    text-align: center;
    margin-top: 5px;
    margin-right: 5px;
    cursor: pointer;
    background: #f1f1f1;
}
.score-key-active {
    background: white;
    border-color: #1cc0f3;
    color: #1cc0f3;
}
.score-input-box {
    display: flex;
    align-items: center;
}
.score-wrap > :nth-child(2) {
    background: white;
}
.quick-score-box {
    padding: 10px 15px;
    border-bottom: 1px solid #e1e1e1;
}

.toggle-num-status {
    float: right;
    margin-right: 5px;
    font-size: 18px;
    cursor: pointer;
    margin-top: 2px;
    user-select: none;
}
.btn-wrap {
    float: right;
    // padding-right: 15px;
}
.action-btn {
    margin-left: 30px;
    cursor: pointer;
}
.action-btn-icon {
    display: inline-block;
    margin-right: 5px;
}
.tmd-logo {
    width: 35px;
    height: 35px;
    margin: 5px 18px 5px 13px;
    vertical-align: bottom;
}
.mark-area {
    width: 100%;
    height: 100%;
    user-select: none;
    // padding: 5px;
}
.mark-header {
    height: 50px;
    width: 100%;
    border-bottom: 1px solid #e1e1e1;
    background: #fafafa;
    line-height: 50px;
    text-align: left;
    padding: 0px 18px 0px 0px;
    box-shadow: 0px 2px 3px 0px rgba(100, 100, 100, 0.2);
    position: relative;
    z-index: 99;
    .info-label {
        color: #909090;
    }
    .info-value {
        margin-right: 30px;
    }
}
.mark-main {
    display: flex;
    flex-direction: row;
    height: calc(100% - 50px);
}
.mark-tools-wrap {
    position: relative;
    box-shadow: 2px 0px 5px 0px rgba(100, 100, 100, 0.2);
    z-index: 9;
    flex: 0 0 40px;
    height: 100%;
    display: flex;
    flex-direction: column;
    border-right: 1px solid #e1e1e1;
    background: #fafafa;
}
.mark-stage {
    flex: 1;
    overflow: hidden;
    background: white;
    text-align: center;
    position: relative;
    height: 100%;
}
.qu-index-box {
    position: absolute;
    bottom: 0px;
    background: #fafafa;
    width: 100%;
    left: 0px;
    height: fit-content;
    text-align: left;
    max-height: 180px;
    padding: 10px 10px 20px 10px;
    box-shadow: 0 -2px 20px -12px #595959;
    p {
        width: fit-content;
    }
}
.score-wrap {
    position: relative;
    box-shadow: -2px 0px 5px 0px rgba(100, 100, 100, 0.2);
    z-index: 9;
    flex: 0 0 241px;
    height: 100%;
    border-left: 1px solid #e1e1e1;
    background: #fafafa;
}
.tool-icon {
    font-size: 20px;
    cursor: pointer;
    height: 40px;
    line-height: 40px;
    // border-bottom: 1px solid #e1e1e1;
    width: 39px;
    &:hover {
        color: #1cc0f3;
        box-shadow: 0 5px 10px -8px #1cc0f3;
        background: white;
        border-color: transparent;
    }
}
.exception-icon:hover {
    box-shadow: 0 5px 10px -8px #ed4014;
}
.tool-icon-active {
    color: #1cc0f3;
    box-shadow: 0 5px 10px -8px #1cc0f3;
    background: white;
    border-color: transparent;
    &:last-child {
        box-shadow: 0 5px 10px -8px #ed4014;
    }
}
</style>
<style>
.mark-tools-wrap .ivu-poptip-title::after {
    display: none;
}
.textarea:focus {
    box-shadow: none;
    overflow: hidden;
    outline: none !important;
    line-height: 1.5;
}
.score-input-box .ivu-input-number-input {
    font-size: 18px;
    color: red;
    font-weight: 800;
}
.light-stu-prog .setting-content{
    background: #FFF;
    box-shadow: none;
    border-color: #e8eaec;
}
.light-stu-prog .filter-tab-item{
    border-color: #e8eaec;
}
.light-stu-prog .filter-tab-item-active{
    background: #FFF !important;
    color: black;
}
.light-stu-prog .filter-tab-item{
    background: #EEE;
}
.light-stu-prog .no-mark-text .no-mark-count{
    color: #515a6e;
}
.light-stu-prog .stu-name{
    background: #eee;
    color: #515a6e;
}
.light-stu-prog .stu-name:hover{
    color: #515a6e;
    box-shadow: 0px 0px 5px 2px #ccc;
}
</style>