<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">当前题号：</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>
            <span class="info-label">题目进度：</span>
            <span class="info-value stu-id-info">{{curProg}}</span>
            <span class="info-label">学生：</span>
            <span class="info-value stu-id-info">{{stusInfo[stuIndex] ? stusInfo[stuIndex].stuId : ''}}</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"></MarkCanvas>
            </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" @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="autoStu" size="small" />
                    </div>
                    <div class="score-setting-item">
                        <span>完成整题批阅自动弹出切换</span>
                        <i-switch v-model="autoQu" size="small" />
                    </div>
                </div>
            </div>
        </div>
        <!-- 用来单独渲染学生作答数据，提高tocanvas 的效率 -->
        <iframe id="markIframe1" :srcdoc="curAnswer" v-if="curAnswer"></iframe>
        <Modal v-model="toggleStatus" title="切换题目" :width="800" footer-hide>
            <div class="qu-prog-wrap" style="height:600px">
                <vuescroll>
                    <QuProg :paperData="paperData" :stusData="stusInfo" :total="taskInfo.count || 1" @getQuIndex="setQuIndex"></QuProg>
                </vuescroll>
            </div>
        </Modal>
    </div>
</template>
<script>
import html2canvas from 'html2canvas';
import MarkCanvas from './MarkCanvas';
import QuProg from './QuProg';
export default {
    name: 'ByStu',
    components: {
        MarkCanvas, QuProg
    },
    data() {
        return {
            score: null,
            mouseStatus: 'move',
            drawImgData: '',
            ansImg: '',
            imgs: [],
            autoQu: true,//自动切换下一题
            autoStu: true,//自动获取下一学生
            toggleStatus: false,
            activeIcon: -1,
            isShowNum: true,
            quIndex: 0,
            childIndex: -1,
            paperData: {
                item: []
            },
            taskInfo: {},
            stusInfo: [],
            stuIndex: 0
        }
    },
    methods: {
        setQuIndex(data) {
            let { quIndex, childIndex } = data
            this.quIndex = quIndex
            this.childIndex = childIndex
            this.toggleStatus = false
        },
        drawImg(imgIndex) {
        },
        //清除所有批注
        clear() {
        },
        /**将答案绘制到canvas上 */
        ansToImg() {
            let answerIframe = document.getElementById('markIframe1')
            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"
                    // 将转出来的答案绘制到canvas上c
                    this.ansImg = canvas.toDataURL()

                })
            }
        },
        //将图片（答案）绘制到canvas
        imgToCanvas(img) {
            console.log('将图片（答案）绘制到canvas', img)
        },
        /** 打分 */
        setScore(score) {
            this.score = score
            let index = this.getScoreIndex(this.quIndex, this.childIndex)
            this.$set(this.stusInfo[this.stuIndex].info.score, index, score)
            if (this.autoStu) {
                this.submit()
            }
        },
        //提交分数
        submit() {
            if (this.score > -1 && this.score != null) {
                let requstData = {
                    id: this.taskInfo.id,
                    stuId: this.stusInfo[this.stuIndex].stuId,
                    subjectId: this.taskInfo.subject,
                    tmdId: this.$store.state.userInfo.TEAMModelId,
                    score: this.stusInfo[this.stuIndex].info.score,
                    count: this.taskInfo.count,
                    code: this.taskInfo.ecode.replace('Exam-', ''),
                    mark: ''
                }
                this.$api.mark.saveScore(requstData).then(
                    res => {
                        // this.$Message.success('保存成功')
                        //按题阅卷自动加载下一人
                        this.getDefStu()
                    },
                    err => {
                        this.$Message.error('保存失败')
                    }
                )
            } else {
                this.$Message.warning('请先打分')
            }
        },
        quit() {
            // 返回页面
            this.$router.push({
                name: sessionStorage.getItem('markFrom')
            })
        },
        /**
         * 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++
                    }
                }
            })
            return --realIndex
        },
        //获取批阅学生数据
        getDefStu() {
            let scoreIndex = this.getScoreIndex(this.quIndex, this.childIndex)
            let has = false //当前数据是否有当前题目没有评分的学生
            for (let i = 0; i < this.stusInfo.length; i++) {
                if (this.stusInfo[i].info.score[scoreIndex] == -1) {
                    this.stuIndex = i
                    this.score = null
                    has = true
                }
            }
            //当前数据没有未评，并且人数==阅卷任务量 —> 说明这道题目已阅完
            if (!has && this.stusInfo.length == this.taskInfo.count) {
                // 提示当前题目已阅完,切换题目
                if (this.autoQu) {
                    this.toggleStatus = true
                } else {
                    this.$Message.warning('当前题目已阅完,请切换题目')
                }
            } else if (!has && this.stusInfo.length < this.taskInfo.count) {
                //当前学生数据已阅，需要继续随机获取学生进行阅卷
                this.getNextStu()
            }
        },
        /**
         * 批阅下个学生
         * @param stuId 如果传了stuid则会获取对应学生的数据，否则随机获取一个学生
         */
        getNextStu(stuId) {
            let requestData = {
                code: this.taskInfo.ecode.replace('Exam-', ''),
                id: this.taskInfo.id,
                subjectId: this.taskInfo.subject,
                tmdId: this.$store.state.userInfo.TEAMModelId,
                count: this.taskInfo.count,
                stuId: stuId
            }
            this.$api.mark.FindNextStu(requestData).then(
                async res => {
                    let sas = this.$store.state.user.schoolProfile.blob_sas //目前只有校本评测安排阅卷任务
                    let blobUrl = JSON.parse(decodeURIComponent(localStorage.school_profile, "utf-8")).blob_uri //目前只有校本评测安排阅卷任务
                    this.stusInfo.push({
                        stuId: res.stuId,
                        info: {
                            ans: res.ans.ans,
                            answer: res.ans.ans ? await this.$tools.getFile(`${blobUrl}/exam/${res.ans.ans}?${sas}`) : [],
                            score: res.ans.score
                        }
                    })
                    this.stuIndex = this.stusInfo.length - 1
                    this.score = res.ans.score[this.getScoreIndex(this.quIndex, this.childIndex)] == -1 ? null : res.ans.score[this.getScoreIndex(this.quIndex, this.childIndex)]
                },
                err => {
                    console.log(err)
                }
            )
        }
    },
    mounted() {
        this.ansToImg()

    },
    created() {
        let routeData = this.$route.params
        this.paperData = routeData.paperData
        this.stusInfo = routeData.stusInfo
        this.taskInfo = routeData.task
        this.quIndex = routeData.quIndex
        this.childIndex = routeData.childIndex
        //获取一个学生数据
        this.getDefStu()

        //默认表情包
        for (let i = 0; i < 9; i++) {
            this.imgs.push(require('@/assets/mark/' + i + '.jpg'))
        }
    },
    computed: {
        //当前题目进度
        curProg(){
            let index = this.getScoreIndex(this.quIndex,this.childIndex)
            let marked = 0
            this.stusInfo.forEach(item=>{
                if(item.info.score[index] != -1){
                    marked++
                }
            })
            return `${marked}/${this.taskInfo.count}`
        },
        curAnswer() {
            if (this.stusInfo && this.stusInfo[this.stuIndex]) {
                this.score = this.stusInfo[this.stuIndex].info.score[this.getScoreIndex(this.quIndex, this.childIndex)]
                if (this.stusInfo[this.stuIndex].info.answer) {
                    return this.stusInfo[this.stuIndex].info.answer[this.getScoreIndex(this.quIndex, this.childIndex)]
                } else {
                    return this.stusInfo[this.stuIndex].stuId + '未作答'
                }
            } else {
                return '学生信息异常'
            }
        },
        /**当期题目分数数组 */
        quScoreArr() {
            let score = 0
            console.log(this.quIndex, this.childIndex)
            if (this.paperData.item) {
                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())
        },
    }
}
</script>
<style scoped lang="less">
#container {
    max-width: 100%;
}
.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;
}
#markIframe1 {
    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;
}
.container-box {
    display: flex;
    justify-content: center;
    width: 100%;
    padding: 10px;
}
#container {
    max-width: 100%;
}
.qu-tips-box {
    & :nth-child(1)::before {
        background: #19be6b;
    }
    & :nth-child(2)::before {
        background: #ff9900;
    }
    & :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;
    }
}
.right-qu {
    color: #19be6b;
    border-color: #19be6b;
    background: white;
}
.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>
.qu-prog-wrap .qu-info-item {
    border-color: #e8eaec;
}
.qu-prog-wrap .obj-index {
    color: #c1c1c1;
}
.qu-prog-wrap .other-index {
    color: #606060;
}
.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;
}
</style>