<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">{{mode == 0 ? '按题阅卷' : '按人阅卷'}}</span>
            <span class="info-label">学生id：</span>
            <span class="info-value stu-id-info">{{stuId}}</span>
            <span class="info-label" v-show="mode == 1">分数：</span>
            <span class="info-value score-info" v-show="mode == 1">{{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>
            <!-- <span class="info-label">阅卷进度：</span>
            <span class="info-value">{{`${12}/${41}`}}</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="move" />
                <Icon custom="iconfont icon-text" class="tool-icon" title="文字批注" @click="drawText" />
                <Icon custom="iconfont icon-mark" class="tool-icon" title="画笔" @click="drawLine" />
                <Icon custom="iconfont icon-arrow-mark" class="tool-icon" title="箭头" @click="drawArrow" />
                <Icon custom="iconfont icon-oval" class="tool-icon" title="椭圆" @click="drawOval" />
                <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="iconfont icon-review" class="tool-icon" title="重阅" /> -->
                <Icon :custom="isFull ? 'iconfont icon-cancel-full' : 'iconfont icon-full-screen'" class="tool-icon" :title="isFull ? '取消全屏' : '全屏'" @click="togglefull" />
            </div>
            <div class="mark-stage" :style="{paddingBottom: mode == 1 ? '120px' : '0px'}">
                <vuescroll ref="canvasScroll">
                    <!-- canvas部分 -->
                    <div class="container-box">
                        <div id="container" @mousemove="canvasMouseMove" @mousedown="canvasMouseDown" @mouseup="canvasMouseUp"></div>
                    </div>
                </vuescroll>
                <!-- 题号显示部分 -->
                <div class="qu-index-box" v-show="mode == 1">
                    <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="stuScore[getScoreIndex(quIndex,childIndex)]"></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']">
                        <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>
                    </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" @on-change="change" size="small"/>
                    </div>
                </div>
            </div>
        </div>
        <!-- 用来单独渲染学生作答数据，提高tocanvas 的效率 -->
        <iframe id="markIframe" :srcdoc="curAnswer" v-if="curAnswer"></iframe>
        <Modal v-model="toggleStatus" title="切换学生">
            进行中
        </Modal>
    </div>
</template>

<script>
import Konva from 'konva'
import html2canvas from 'html2canvas';
export default {
    name: 'Home',
    data() {
        return {
            autoQu: true,//自动切换下一题
            autoStu:true,//自动获取下一学生
            toggleStatus: false,
            activeIcon: -1,
            score: 0,
            isShowNum: true,
            mode: '0',//阅卷模式 1:按人阅卷 0:按题阅卷
            quIndex: 0,
            childIndex: undefined,
            stage: undefined,
            orgLayer: undefined,
            markLayer: undefined,
            tr: undefined,
            scaleDefault: 1,
            maxScale: 5,
            minScale: 0.2,
            scaleStep: 0.2,
            imgWidth: 0,
            imgHeight: 0,
            isMouseDown: false,
            clickPoint: {
                x: 0,
                y: 0
            },
            mouseStatus: 'move', //move：移动  rect:画矩形 resize:调整图形
            resizeBefore: '',
            rect: undefined,
            oval: undefined,
            arrow: undefined,
            text: undefined,
            line: undefined,
            img: undefined,
            isDltText: false,
            imgs: [],
            curImg: undefined,
            counter: 0,
            isFull: false, //是否为全屏模式
            examData: {
                name: '期末考试',
            },
            stuData: {
                name: '',
                id: '',
            },
            paperData: {
                item: []
            },
            stuAnswer: [],
            stuScore: [],
            taskInfo: {},
            stuId: ''
        }
    },
    methods: {
        /**将答案绘制到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'
                console.log('markIframe', answerIframe)
                html2canvas(answerIframe.contentWindow.document.body, {}).then((canvas) => {
                    console.log('canvas', canvas)
                    canvas.id = "canvas" + this.getScoreIndex(this.quIndex, this.childIndex)
                    let markBg = canvas.toDataURL()
                    // 将转出来的答案绘制到canvas上
                    this.imgToCanvas(markBg)
                    console.log(markBg)
                })
            }
        },
        //将图片（答案）绘制到canvas
        imgToCanvas(img) {
            this.orgLayer.removeChildren()
            this.markLayer.removeChildren()
            let imageObj = new Image()
            let _this = this
            imageObj.onload = function () {
                //创建画布
                _this.imgWidth = imageObj.width
                _this.imgHeight = imageObj.height
                _this.stage.width(imageObj.width)
                _this.stage.height(imageObj.height)
                let img = new Konva.Image({
                    x: 0,
                    y: 0,
                    image: imageObj,
                    width: imageObj.width,
                    height: imageObj.height
                })
                _this.orgLayer.add(img)
                _this.orgLayer.batchDraw()
            }
            imageObj.src = img
            this.stage.add(this.orgLayer)
        },
        /** 打分 */
        setScore(score) {
            this.$set(this.stuScore, this.getScoreIndex(this.quIndex, this.childIndex), score)
        },
        toQu(index, childIndex) {
            this.quIndex = index
            this.childIndex = childIndex

        },
        /**
         * index 题目index 必传
         * childIndex 小题index 非必传 
         */
        getScoreIndex(index, childIndex) {
            let realIndex = index
            this.paperData.item.forEach((item, itemIndex) => {
                if (itemIndex < index && item.children.length) {
                    realIndex += item.children.length
                } else if (itemIndex == index && item.children.length) {
                    realIndex += childIndex
                }
            })
            return realIndex
        },
        togglefull() {
            this.$router.push({
                name: this.isFull ? 'MarkView' : 'FullMarkView'
            })
        },
        //提交分数
        submit() {
            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('保存成功')
                    // 按人阅卷自动跳转下一题
                    if (this.mode == 1 && this.autoQu) {
                        this.nextQuestion()
                        this.ansToImg()
                    }
                    //按题阅卷自动加载下一人
                    else {

                    }
                },
                err => {
                    this.$Message.error('保存失败')
                }
            )

        },
        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++
                    }
                    //当前小题是最后一个，需要判断下一个题目类型
                    //下一个题目是综合题
                    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 + 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('已阅完')
                    }

                }
            }
        },

        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())
        },
        move(index) {
            this.activeIcon = index
            this.mouseStatus = 'move'
        },
        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 })
            }
        },
        startImg(current) {
            let _this = this
            this.img = new Konva.Image({
                id: this.uuid(),
                draggable: false,
                strokeScaleEnabled: false,
                image: _this.curImg,
                width: 80,
                height: 80,
                x: current.x,
                y: current.y
            })
            // 监听点击事件设置选中状态
            this.img.on('click', (evt) => {
                _this.resizeBefore = _this.mouseStatus == 'resize' ? _this.resizeBefore : _this.mouseStatus//记录resize之前的状态
                _this.mouseStatus = 'resize'
                evt.target.draggable(true)
                evt.cancelBubble = true //阻止事件冒泡 
                _this.tr.nodes([evt.target])
                _this.markLayer.add(_this.tr)
            })
            // 优化一些绘制逻辑
            this.img.on('mouseout', (evt) => {
                evt.cancelBubble = true //阻止事件冒泡
                evt.target.draggable(false)
                let nodes = _this.tr.nodes()
                if (_this.mouseStatus == 'resize' && nodes.length == 0) _this.mouseStatus = _this.resizeBefore
            })
            // this.img.zIndex(1)
            this.markLayer.add(this.img)
            this.stage.add(this.markLayer)
            this.img = null
        },
        drawText(index) {
            this.activeIcon = index
            this.mouseStatus = 'text'
        },
        startText(current) {
            let _this = this
            let nodes = this.tr.nodes()
            if (nodes.length > 0) return
            if (!this.text) {
                this.text = new Konva.Text({
                    id: this.uuid(),
                    fontSize: 16,
                    text: '',
                    fill: 'red',
                    lineHeight: 1.5,
                    width: 180,
                    height: 30,
                    x: _this.clickPoint.x / _this.scaleDefault,
                    y: _this.clickPoint.y / _this.scaleDefault,
                    draggable: false
                })
                // 监听点击事件设置选中状态
                this.text.on('click', (evt) => {
                    _this.resizeBefore = _this.mouseStatus == 'resize' ? _this.resizeBefore : _this.mouseStatus//记录resize之前的状态
                    _this.mouseStatus = 'resize'
                    evt.target.draggable(true)
                    evt.cancelBubble = true //阻止事件冒泡 
                    _this.tr.nodes([evt.target])
                    _this.markLayer.add(_this.tr)
                })
                this.text.on('mouseout', (evt) => {
                    evt.cancelBubble = true //阻止事件冒泡
                    evt.target.draggable(false)
                    let nodes = _this.tr.nodes()
                    if (_this.mouseStatus == 'resize' && nodes.length == 0) _this.mouseStatus = _this.resizeBefore
                })
                this.text.on('dblclick dbltap', (evt) => {
                    let nodes = _this.tr.nodes()
                    if (nodes && nodes.length > 0) {
                        let text = nodes[0]
                        let textPosition = text.getAbsolutePosition()
                        let stageBox = _this.stage.container().getBoundingClientRect()
                        let areaPosition = {
                            x: stageBox.left + textPosition.x,
                            y: stageBox.top + textPosition.y,
                        }
                        let textarea = document.createElement('textarea');
                        document.body.appendChild(textarea)

                        textarea.value = text.text()
                        textarea.style.position = 'absolute'
                        textarea.style.top = areaPosition.y + 'px'
                        textarea.style.left = areaPosition.x + 'px'
                        textarea.style.background = 'transparent'
                        textarea.style.color = 'red'
                        textarea.style.fontSize = '16px'
                        textarea.style.borderColor = 'red'
                        textarea.style.boxShadow = 'none'
                        textarea.style.height = text.height() + 'px'
                        textarea.className = 'textarea'
                        textarea.style.width = text.width()

                        textarea.focus()
                        _this.isDltText = true //设置删除按键的状态，文本框状态应该是删除文字不能删除图形
                        text.hide()
                        _this.tr.hide()
                        textarea.addEventListener('input', () => {
                            textarea.style.height = 'auto'
                            textarea.style.height = textarea.scrollHeight + 'px'
                            _this.isDltText = true
                        })
                        textarea.addEventListener('blur', function (e) {
                            if (textarea.value) {
                                text.text(textarea.value)
                                text.width(textarea.clientWidth)
                                text.height(textarea.scrollHeight)
                                text.show()

                                _this.markLayer.draw()
                            } else {
                                text.remove()
                            }
                            _this.tr.nodes([])
                            _this.tr.show()
                            document.body.removeChild(textarea)
                            _this.isDltText = false
                        })
                    }
                })
            } else {
                this.text.x(current.x)
                this.text.y(current.y)
            }
            // this.text.zIndex(100)
            this.tr.nodes([this.text])
            this.markLayer.add(this.tr)
            this.markLayer.add(this.text)
            this.stage.add(this.markLayer)
        },
        drawLine(index) {
            this.activeIcon = index
            this.mouseStatus = 'line'
        },
        startLine(current) {
            let _this = this
            if (!this.line) {
                this.line = new Konva.Line({
                    id: this.uuid(),
                    stroke: 'red',
                    strokeWidth: 3,
                    draggable: false,
                    tension: 1,
                    points: [_this.clickPoint.x / _this.scaleDefault, _this.clickPoint.y / _this.scaleDefault]
                })
                // 监听点击事件设置选中状态
                this.line.on('click', (evt) => {
                    _this.resizeBefore = _this.mouseStatus == 'resize' ? _this.resizeBefore : _this.mouseStatus//记录resize之前的状态
                    _this.mouseStatus = 'resize'
                    evt.target.draggable(true)
                    evt.cancelBubble = true //阻止事件冒泡 
                    _this.tr.nodes([evt.target])
                    _this.markLayer.add(_this.tr)
                })
                // 优化一些绘制逻辑
                this.line.on('mouseout', (evt) => {
                    evt.cancelBubble = true //阻止事件冒泡
                    evt.target.draggable(false)
                    let nodes = _this.tr.nodes()
                    if (_this.mouseStatus == 'resize' && nodes.length == 0) _this.mouseStatus = _this.resizeBefore
                })
            } else {
                this.line.points(this.line.points().concat([current.x / _this.scaleDefault, current.y / _this.scaleDefault]))
            }
            // this.line.zIndex(1)
            this.markLayer.add(this.line)
            this.stage.add(this.markLayer)
        },
        drawArrow(index) {
            this.activeIcon = index
            this.mouseStatus = 'arrow'
        },
        // 绘制箭头
        startArrow(current) {
            let _this = this
            if (!this.arrow) {
                this.arrow = new Konva.Arrow({
                    id: this.uuid(),
                    fill: 'transparent',
                    stroke: 'red',
                    strokeWidth: 4,
                    pointerLength: 10,
                    pointerWidth: 8,
                    draggable: false,
                    fill: 'red',
                    lineCap: 'round',
                    strokeScaleEnabled: false,
                    points: [_this.clickPoint.x / _this.scaleDefault, _this.clickPoint.y / _this.scaleDefault, (current.x) / _this.scaleDefault, (current.y) / _this.scaleDefault]
                })
                // 监听点击事件设置选中状态
                this.arrow.on('click', (evt) => {
                    _this.resizeBefore = _this.mouseStatus == 'resize' ? _this.resizeBefore : _this.mouseStatus//记录resize之前的状态
                    _this.mouseStatus = 'resize'
                    evt.target.draggable(true)
                    evt.cancelBubble = true //阻止事件冒泡 
                    _this.tr.nodes([evt.target])
                    _this.markLayer.add(_this.tr)
                })
                // 优化一些绘制逻辑
                this.arrow.on('mouseout', (evt) => {
                    evt.cancelBubble = true //阻止事件冒泡
                    evt.target.draggable(false)
                    let nodes = _this.tr.nodes()
                    if (_this.mouseStatus == 'resize' && nodes.length == 0) _this.mouseStatus = _this.resizeBefore
                })
            } else {
                this.arrow.points([_this.clickPoint.x / _this.scaleDefault, _this.clickPoint.y / _this.scaleDefault, (current.x) / _this.scaleDefault, (current.y) / _this.scaleDefault])
            }
            // this.arrow.zIndex(1)
            this.markLayer.add(this.arrow)
            this.stage.add(this.markLayer)
        },
        drawOval(index) {
            this.activeIcon = index
            this.mouseStatus = 'oval'
        },
        startOval(current) {
            console.log('scale', this.scaleDefault)
            console.log('point', this.clickPoint)
            let _this = this
            //判断rect是否初始化
            let rx = (current.x - _this.clickPoint.x) / _this.scaleDefault * 0.5
            let ry = (_this.clickPoint.y - current.y) / _this.scaleDefault * 0.5
            if (!this.oval) {
                this.oval = new Konva.Ellipse({
                    id: this.uuid(),
                    // x: _this.clickPoint.x / _this.scaleDefault,
                    // y: _this.clickPoint.y / _this.scaleDefault,
                    x: _this.clickPoint.x,
                    y: _this.clickPoint.y,
                    radiusX: rx > 0 ? rx : -rx,
                    radiusY: ry,
                    fill: 'transparent',
                    stroke: 'red',
                    strokeWidth: 2,
                    draggable: false,
                    rotation: rx > 0 ? 0 : 180,
                    strokeScaleEnabled: false
                })
                // 监听点击事件设置选中状态
                this.oval.on('click', (evt) => {
                    _this.resizeBefore = _this.mouseStatus == 'resize' ? _this.resizeBefore : _this.mouseStatus//记录resize之前的状态
                    _this.mouseStatus = 'resize'
                    evt.target.draggable(true)
                    evt.cancelBubble = true //阻止事件冒泡 
                    _this.tr.nodes([evt.target])
                    _this.markLayer.add(_this.tr)
                })
                // 优化一些绘制逻辑
                this.oval.on('mouseout', (evt) => {
                    evt.cancelBubble = true //阻止事件冒泡
                    evt.target.draggable(false)
                    let nodes = _this.tr.nodes()
                    if (_this.mouseStatus == 'resize' && nodes.length == 0) _this.mouseStatus = _this.resizeBefore
                })
            } else {
                this.oval.x(_this.clickPoint.x / _this.scaleDefault + rx)
                this.oval.y(_this.clickPoint.y / _this.scaleDefault - ry)
                this.oval.radiusX(rx > 0 ? rx : -rx)
                this.oval.radiusY(ry)
                this.oval.rotation(rx > 0 ? 0 : 180)
            }
            this.oval.zIndex(1)
            this.markLayer.add(this.oval)
            this.stage.add(this.markLayer)
        },
        drawIcon(index) {
            this.activeIcon = index
        },
        review(index) {
            this.activeIcon = index
        },
        cancelFull(index) {
            this.activeIcon = index
        },
        //绘制矩形
        drawRect(index) {
            this.activeIcon = index
            this.mouseStatus = 'rect'
        },
        startRect(current) {
            let _this = this
            //判断rect是否初始化
            if (!this.rect) {
                this.rect = new Konva.Rect({
                    id: this.uuid(),
                    x: _this.clickPoint.x / _this.scaleDefault,
                    y: _this.clickPoint.y / _this.scaleDefault,
                    width: (current.x - _this.clickPoint.x) / _this.scaleDefault,
                    height: (current.y - _this.clickPoint.y) / _this.scaleDefault,
                    fill: 'transparent',
                    stroke: 'red',
                    strokeWidth: 2,
                    draggable: false,
                    strokeScaleEnabled: false
                })
                // 监听点击事件设置选中状态
                this.rect.on('click', (evt) => {
                    _this.resizeBefore = _this.mouseStatus == 'resize' ? _this.resizeBefore : _this.mouseStatus//记录resize之前的状态
                    _this.mouseStatus = 'resize'
                    evt.target.draggable(true)
                    evt.cancelBubble = true //阻止事件冒泡
                    //Transformer   
                    _this.tr.nodes([evt.target])
                    _this.markLayer.add(_this.tr)
                })
                // 优化一些绘制逻辑
                this.rect.on('mouseout', (evt) => {
                    evt.cancelBubble = true //阻止事件冒泡
                    evt.target.draggable(false)
                    let nodes = _this.tr.nodes()
                    if (_this.mouseStatus == 'resize' && nodes.length == 0) _this.mouseStatus = _this.resizeBefore
                })
            } else {
                this.rect.x(_this.clickPoint.x / _this.scaleDefault)
                this.rect.y(_this.clickPoint.y / _this.scaleDefault)
                this.rect.width((current.x - _this.clickPoint.x) / _this.scaleDefault)
                this.rect.height((current.y - _this.clickPoint.y) / _this.scaleDefault)
            }
            this.rect.zIndex(1)
            this.markLayer.add(this.rect)
            this.stage.add(this.markLayer)
        },
        //防抖函数
        debounce(func, delay) {
            return function () {
                window.clearTimeout(window.timeout)
                window.timeout = setTimeout(() => {
                    clearTimeout(window.timeout)
                    func.apply(this, arguments)
                }, delay)
            }
        },
        //还原比例
        restore() {
            this.scaleDefault = 1
            this.myScale()
        },
        // 缩小
        smaller() {
            console.log(this.stage)
            this.scaleDefault -= this.scaleStep
            if (this.scaleDefault < this.minScale) {
                this.scaleDefault += this.scaleStep
                //函数防抖，优化重复提示
                this.debounce(() => {
                    this.$Message.warning('已经缩小到最小比例')
                }, 400)()
            } else {
                this.myScale()
            }
        },
        //放大
        larger() {
            console.log(this.stage)
            this.scaleDefault += this.scaleStep
            if (this.scaleDefault > this.maxScale) {
                this.scaleDefault -= this.scaleStep
                //函数防抖，优化重复提示
                this.debounce(() => {
                    this.$Message.warning('已经放大到最大比例')
                }, 400)()
            } else {
                this.myScale()
            }
        },
        myScale() {
            this.stage.children.forEach(item => {
                item.scale({
                    x: this.scaleDefault,
                    y: this.scaleDefault
                })
            })
            this.stage.width(this.imgWidth * this.scaleDefault)
            this.stage.height(this.imgHeight * this.scaleDefault)
        },
        //绑定鼠标滚轮事件，操作缩放功能
        bundleScoll() {
            let stage = document.getElementById('container')
            let _this = this
            stage.addEventListener('mousewheel', function (e) {
                if (e.preventDefault) {
                    e.preventDefault()
                } else {
                    window.event.returnValue == false
                }
                _this.scrollFunc(e)
            }, false) || stage.addEventListener('DOMMouseScroll', function (e) {
                if (e.preventDefault) {
                    e.preventDefault()
                } else {
                    window.event.returnValue == false
                }
                _this.scrollFunc(e)
            }, false)
        },
        //判断鼠标放大还是缩小
        scrollFunc(e) {
            e = e || window.event
            if (e.wheelDelta) { // 判断浏览器IE，谷歌滑轮事件
                if (e.wheelDelta > 0) { // 当滑轮向上滚动时
                    this.larger()
                }
                if (e.wheelDelta < 0) { // 当滑轮向下滚动时
                    this.smaller()
                }
            } else if (e.detail) { // Firefox滑轮事件
                if (e.detail > 0) { // 当滑轮向上滚动时
                    this.larger()
                }
                if (e.detail < 0) { // 当滑轮向下滚动时
                    this.smaller()
                }
            }
        },
        //获取在canvas上的坐标
        getCanvasPoint(x, y) {
            // let canvas = document.getElementById('container')
            let canvas = document.getElementsByClassName('konvajs-content')
            let cs = canvas.length ? canvas[0] : null
            if (cs) {
                let canvasRect = cs.getBoundingClientRect()
                return {
                    x: x - canvasRect.left,
                    y: y - canvasRect.top
                }
            } else {
                return {
                    x, y
                }
            }

        },
        //按下鼠标事件
        canvasMouseDown(e) {
            this.isMouseDown = true
            this.clickPoint = this.getCanvasPoint(e.clientX, e.clientY)
        },
        //鼠标弹起事件
        canvasMouseUp() {
            this.isMouseDown = false
            switch (this.mouseStatus) {
                case 'move':
                    break
                case 'rect':
                    this.rect = null
                    break
                case 'oval':
                    this.oval = null
                    break
                case 'arrow':
                    this.arrow = null
                    break
                case 'text':
                    this.text = null
                    break
                case 'line':
                    this.line = null
                    break
                // case 'img':
                //     this.img = null
                //     break
                default:
                    break
            }
        },
        //鼠标移动事件
        canvasMouseMove(e) {
            if (this.isMouseDown) {
                let current = this.getCanvasPoint(e.clientX, e.clientY)
                switch (this.mouseStatus) {
                    case 'move':
                        this.$refs["canvasScroll"].scrollBy({
                            dx: this.clickPoint.x - current.x,
                            dy: this.clickPoint.y - current.y
                        }, 0)
                        break
                    case 'rect':
                        this.startRect(current)
                        break
                    case 'oval':
                        this.startOval(current)
                        break
                    case 'arrow':
                        this.startArrow(current)
                        break
                    case 'text':
                        this.startText(current)
                        break
                    case 'line':
                        this.startLine(current)
                        break
                    default:
                        break
                }
            }
        },

        //清除所有批注
        clear(index) {
            this.activeIcon = index
            this.markLayer.removeChildren()
            this.stage.add(this.markLayer)
        }
    },
    mounted() {
        let _this = this
        // let imageObj = new Image()
        // imageObj.onload = function () {
        //     //创建画布
        //     _this.imgWidth = imageObj.width
        //     _this.imgHeight = imageObj.height
        //     _this.stage = new Konva.Stage({
        //         container: 'container',
        //         id: 'canvas',
        //         width: imageObj.width,
        //         height: imageObj.height
        //     })
        //     _this.orgLayer = new Konva.Layer({
        //     })
        //     _this.markLayer = new Konva.Layer()
        //     _this.stage.add(_this.orgLayer)
        //     _this.stage.add(_this.markLayer)
        //     let img = new Konva.Image({
        //         x: 0,
        //         y: 0,
        //         image: imageObj,
        //         width: imageObj.width,
        //         height: imageObj.height
        //     })
        //     _this.orgLayer.add(img)
        //     _this.orgLayer.batchDraw()
        //     _this.bundleScoll()
        //     _this.stage.on('click', (evt) => {
        //         _this.tr.nodes([])
        //     })
        //     _this.stage.on('mouseover', (evt) => {
        //         let nodes = _this.tr.nodes()
        //         if (_this.mouseStatus == 'resize' && nodes.length == 0) _this.mouseStatus = _this.resizeBefore

        //     })

        // }
        // imageObj.src = require('@/assets/mark/img' + this.counter % 3 + '.jpg')

        //创建画布
        _this.stage = new Konva.Stage({
            container: 'container',
            id: 'canvas',
            width: 600,
            height: 240
        })
        _this.orgLayer = new Konva.Layer()
        _this.markLayer = new Konva.Layer()
        _this.stage.add(_this.orgLayer)
        _this.stage.add(_this.markLayer)
        _this.orgLayer.batchDraw()
        _this.bundleScoll()
        _this.stage.on('click', (evt) => {
            _this.tr.nodes([])
        })
        _this.stage.on('mouseover', (evt) => {
            let nodes = _this.tr.nodes()
            if (_this.mouseStatus == 'resize' && nodes.length == 0) _this.mouseStatus = _this.resizeBefore

        })

        this.tr = new Konva.Transformer({
            rotateEnabled: false,
            anchorStroke: 'red',
            enabledAnchors: ['top-center', 'top-left', 'top-right', 'middle-left', 'middle-right', 'bottom-left', 'bottom-center', 'bottom-right'],
            anchorSize: 8,
            borderStroke: 'red'
        })
        this.tr.borderEnabled(true)
        this.tr.anchorCornerRadius(10)
        this.ansToImg()

    },
    created() {
        //按题阅卷和整体阅卷
        let routeData = this.$route.params
        this.paperData = routeData.fullPaper
        this.stuAnswer = routeData.answer
        this.stuScore = routeData.score
        this.mode = routeData.type
        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
            }
        }
        if (routeData.name == 'FullMarkView') this.isFull = true
        // this.mode = 1

        //监听删除按键，删除图形
        document.onkeydown = e => {
            if (e.keyCode == 8 && !this.isDltText) {
                let shape = this.tr ? this.tr.nodes() : []
                if (shape.length) {
                    shape[0].remove()
                    this.tr.nodes([])
                }
            }
        }
        //默认表情包
        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() {
            let index = this.getScoreIndex(this.quIndex, this.childIndex)
            return this.stuAnswer[index]
        },
        totalScore() {
            if (this.mode == 1) {
                return this.stuScore.reduce((a, b) => {
                    return a + b
                }, 0)
            } else {
                return 0
            }
        }
    }
}
</script>
<style scoped lang="less">
.score-setting-wrap{
    margin-top: 50px;
    padding: 0px 5px;

}
.score-setting-item{
    margin-top: 15px;
    display: flex;
    justify-content: space-between;
    span{
        // font-size: 16px;
    }
}
.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;
}
.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>
.mark-tools-wrap .ivu-poptip-title::after {
    display: none;
}
.textarea:focus {
    box-shadow: none;
    overflow: hidden;
    outline: none !important;
    line-height: 1.5;
}
</style>