<template>
    <div class="task-container custom-iview-split">
        <Split v-model="split1">
            <!-- 阅卷任务列表  -->
            <div class="ev-list" slot="left">
                <div class="ev-list-header">
                    <span>
                        {{$t('task.markTask')}}
                    </span>
                </div>
                <vuescroll class="ev-list-content">
                    <div :class="['ev-item','block-bg',index == curTaskIndex ? 'block-bg-active':'']" v-for="(item,index) in markList" :key="index" @click="selectTask(index)">
                        <p class="ev-name">
                            <span>{{item.name}}</span>
                            <span class="mark-status-tag">{{item.type == 3 ? '未开始' : $t('task.markStatus1')}}</span>
                            <span class="mark-status-tag" :class="item.type === 1 ? 'success-color' : item.type == 2 ? 'err-color' : 'warning-color'">
                                {{item.type === 1 ? '阅卷任务' : item.type == 2 ? '异常卷处理' : '仲裁卷处理'}}
                            </span>
                        </p>
                        <p class="ev-info">
                            <Icon type="md-time" style="margin-right:5px;" size="16" />
                            <span>{{$t('learnActivity.mgtScEv.endTime')}}{{dateFormat(item.endTime)}}</span>
                        </p>
                        <p class="ev-info">
                            <Icon type="ios-cube" style="margin-right:5px;" size="14" />
                            <span>批阅科目：{{item.subjectName}}</span>
                        </p>
                    </div>
                    <EmptyData v-show="markList.length == 0" textContent="暂无阅卷任务" style="margin-top:80px"></EmptyData>
                </vuescroll>
            </div>
            <!-- 没有任务    -->
            <div slot="right" v-if="!markList[curTaskIndex]" class="ev-mark-info">
                <EmptyData :top="140" slot="right" textContent="暂无任务"></EmptyData>
            </div>
            <!-- 阅卷老师 -->
            <div slot="right" class="ev-mark-info" v-else-if="markList[curTaskIndex].type == 1">
                <div class="ev-mark-header tab-box">
                    <span :class="curBarIndex == 1 ? 'task-bar-item pane active':'task-bar-item pane'" @click="selectBar(1)">
                        {{$t('task.markMode2')}}
                    </span>
                    <span :class="curBarIndex == 0 ? 'task-bar-item pane active':'task-bar-item pane'" @click="selectBar(0)">
                        {{$t('task.markMode1')}}
                    </span>
                </div>
                <vuescroll class="mark-info-content" v-if="markList.length > 0" style="padding-bottom:10px">
                    <!-- 按人阅卷学生信息 -->
                    <StuProg :quNoList="quNoList" v-show="curBarIndex == 1" @getStuId="toByStuView" :stusData="markData ? markData.objs : []" :total="markList[curTaskIndex] ? markList[curTaskIndex].count : 1" :qus="markList[curTaskIndex] ? markList[curTaskIndex].qu : []"></StuProg>
                    <!-- 按题 批阅进度 -->
                    <div class="setting-block" v-show="curBarIndex == 0" style="margin-top:15px">
                        <p class="block-title">
                            {{$t('task.markProg')}}
                            <span class="objective-tips">
                                （温馨提示：客观题已由系统自动评分，下面只显示了需要人工评分的主观题题号。）
                            </span>
                            <Icon type="ios-arrow-down" :class="['show-full-icon', fullQuProg ? 'full-qu-prog' : '']" @click="fullQuProg = !fullQuProg" />
                        </p>
                        <div class="setting-content" :style="{height: fullQuProg ? 'fit-content' : '420px'}">
                            <vuescroll>
                                <!-- 按题阅卷题目进度条 -->
                                <QuProg :paperData="fullPaper" :stusData="markData ? markData.objs : []" :total="markList[curTaskIndex] ? markList[curTaskIndex].count : 1" @getQuIndex="toByQuView" :qus="markList[curTaskIndex] ? markList[curTaskIndex].qu : []"></QuProg>
                            </vuescroll>
                        </div>
                    </div>
                    <!-- 数据统计 平均分、最高分、最低分、标准差 -->
                    <div class="setting-block">
                        <p class="block-title">数据统计</p>
                        <div class="setting-content data-content dark-iview-table">
                            <DataCompare></DataCompare>
                            <ProgPie :count="[marked.length,marking.length,unmarked]"></ProgPie>
                        </div>
                    </div>
                    <!-- 异常申报统计 -->
                    <div class="setting-block" v-show="errData.length">
                        <p class="block-title">异常统计</p>
                        <div class="setting-content dark-iview-table">
                            <Table :columns="errCol" :data="errData">
                                <template slot-scope="{ row }" slot="status">
                                    <strong :style="{color: row.status ? '#19be6b' : '#ed4014'}">{{ row.status ? '已处理' : '处理中'}}</strong>
                                </template>
                            </Table>
                        </div>
                    </div>
                </vuescroll>
                <EmptyData textContent="暂无阅卷任务" :top="90" style="height:fit-content"></EmptyData>
            </div>
            <!-- 异常卷任务 -->
            <ErrPaper slot="right" :taskInfo="markList[curTaskIndex]" v-else-if="markList[curTaskIndex].type == 2"></ErrPaper>
            <!-- 仲裁卷任务 -->
            <Arbitration slot="right" v-else-if="markList[curTaskIndex].type == 3"></Arbitration>
        </Split>
    </div>
</template>
<script>
import DataCompare from './mark/Compare.vue'
import ProgPie from './mark/ProgPie.vue'
import QuProg from './mark/QuProg.vue'
import StuProg from './mark/StuProg.vue'
import Arbitration from './arb/Arbitration.vue'
import ErrPaper from './err/ErrPaper.vue'
export default {
    components: {
        DataCompare, ProgPie, QuProg, StuProg, Arbitration, ErrPaper
    },
    data() {
        return {
            objectiveQu: ['single', 'multiple', 'judge'],
            errCol: [
                {
                    title: '学号',
                    key: 'id',
                    align: 'center',
                    width: 120
                },
                {
                    title: '题号',
                    key: 'index',
                    align: 'center'
                },
                {
                    title: '异常原因',
                    key: 'err',
                    align: 'center'
                },
                {
                    title: '反馈建议',
                    key: 'feedback',
                    align: 'center'
                },
                {
                    title: '状态',
                    slot: 'status',
                    align: 'center',
                    width: 120
                }
            ],
            columns2: [
                {
                    title: '学号',
                    key: 'id',
                    align: 'center',
                    width: 120
                },
                {
                    title: '题号',
                    key: 'quNo',
                    align: 'center',
                    // width:70
                },
                {
                    title: '我的评分',
                    key: 'myScore',
                    align: 'center',
                    // width:180
                },
                {
                    title: '其他老师评分',
                    key: 'otScore',
                    align: 'center',
                    // width:180
                },
                {
                    title: '状态',
                    key: 'status',
                    align: 'center',
                    width: 120
                }
            ],
            tabIndex: 0,
            split1: 0.2,
            curBarIndex: 1,
            markList: [],
            curTaskIndex: 0,
            fullQuProg: false,
            markData: undefined,
            fullPaper: {
                item: []
            }
        }
    },
    methods: {
        /**
         * index 题目index 必传
         * childIndex 小题index 非必传 
         */
        getScoreIndex(index, childIndex) {
            let realIndex = 0
            this.fullPaper.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
        },
        rowClassName(row, index) {
            if (index % 2 == 0) {
                return 'stripe-row'
            } else {
                return ''
            }
        },
        /**
         * 按人阅卷
         */
        async toByStuView(stuId) {
            sessionStorage.setItem('markFrom', this.$route.name)
            let sas = this.$store.state.user.schoolProfile.blob_sas //目前只有校本评测安排阅卷任务
            let blobUrl = JSON.parse(decodeURIComponent(localStorage.school_profile, "utf-8")).blob_uri //目前只有校本评测安排阅卷任务

            let answer, score, sId, quScore, stuData, markArr
            //批阅已经分配的学生
            if (stuId) {
                let stuInfo = this.markData.objs.find(item => {
                    return item.stuId == stuId
                })
                stuData = stuInfo
                let index = stuInfo.tIds.indexOf(this.$store.state.userInfo.TEAMModelId)
                // let ansBlob = index > -1 ? stuInfo.marks[index] || stuInfo.blob : stuInfo.blob
                let ansBlob = stuInfo.blob
                answer = ansBlob ? JSON.parse(await this.$tools.getFile(`${blobUrl}/exam/${ansBlob}?${sas}`)) : []
                score = stuInfo.item.map(scoreItem => {
                    return scoreItem.sc
                })
                markArr = stuInfo.item.map(item => {
                    return item.blob
                })
                quScore = stuInfo.item.map(scoreItem => {
                    return scoreItem.ssc
                })
                sId = stuId
            }
            // 获取新学生
            else {
                let resData = await this.getNextStu()
                if (resData.blob && !resData.msg) {
                    let index = resData.tIds.indexOf(this.$store.state.userInfo.TEAMModelId)
                    // let ansBlob = index > -1 ? resData.marks[index] || resData.blob : resData.blob //批注数据结构调整，不是完整的作答数据了
                    let ansBlob = resData.blob
                    answer = ansBlob ? JSON.parse(await this.$tools.getFile(`${blobUrl}/exam/${ansBlob}?${sas}`)) : []
                    resData.answer = answer
                    score = resData.item.map(item => {
                        return item.sc
                    })
                    markArr = resData.item.map(item => {
                        return item.blob
                    })
                    quScore = resData.item.map(item => {
                        return item.ssc
                    })
                    sId = resData.stuId
                    stuData = resData

                } else {
                    this.$Message.warning('暂无可选学生')
                }
            }
            this.$router.push({
                name: 'ByStu',
                params: {
                    from: this.$route.name,
                    task: this.markList[this.curTaskIndex],
                    stuId: sId,
                    fullPaper: this.fullPaper,
                    stusData: this.markData.objs,
                    stuData,
                    answer,
                    score,
                    quScore,
                    markArr
                }
            })
        },
        /**
        * 按题阅卷
        * quIndex 必传
        * childIndex 非必传
        */
        async toByQuView(data) {
            let quIndex = data
            sessionStorage.setItem('markFrom', this.$route.name)
            let sas = this.$store.state.user.schoolProfile.blob_sas //目前只有校本评测安排阅卷任务
            let blobUrl = JSON.parse(decodeURIComponent(localStorage.school_profile, "utf-8")).blob_uri //目前只有校本评测安排阅卷任务
            // 获取学生作答数据
            this.markData.objs.forEach(async item => {
                // let index = item.tIds.indexOf(this.$store.state.userInfo.TEAMModelId)
                // let ansBlob = index > -1 ? item.marks[index] || item.blob : item.blob
                let ansBlob = item.blob
                this.$set(item, 'answer', ansBlob ? JSON.parse(await this.$tools.getFile(`${blobUrl}/exam/${ansBlob}?${sas}`)) : [])
                item.markArr = item.item.map(i => {
                    return i.blob
                })
            })
            this.$router.push({
                name: 'ByQu',
                params: {
                    from: this.$route.name,
                    task: this.markList[this.curTaskIndex], //阅卷任务数据
                    stusInfo: this.markData.objs, //已阅和进行中的学生数据
                    paperData: this.fullPaper, //试卷数据
                    quIndex
                }
            })
        },
        /**
         * 批阅下个学生
         * @param stuId 如果传了stuid则会获取对应学生的数据，否则随机获取一个学生
         */
        getNextStu(stuId) {
            let requestData = {
                code: this.markList[this.curTaskIndex].ecode.replace('Exam-', ''),
                id: this.markList[this.curTaskIndex].cid,
                subjectId: this.markList[this.curTaskIndex].subject,
                count: this.markList[this.curTaskIndex].count,
                tmdId: this.$store.state.userInfo.TEAMModelId,
                stuId
            }
            return this.$api.mark.FindNextStu(requestData)
        },
        /**获取type对应的label */
        getTypeLabel(code) {
            for (let item of this.$GLOBAL.EV_TYPE()) {
                if (item.value == code) {
                    return item.label
                }
            }
        },
        dateFormat(timestamp) {
            var date = new Date(timestamp)
            var Y = date.getFullYear() + '-'
            var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
            var D = date.getDate() + ' '
            return Y + M + D;
        },
        selectBar(index) {
            this.curBarIndex = index
            sessionStorage.setItem('markMode', index)
        },
        //查询阅卷任务
        findTask() {
            let requestData = {
                code: this.$store.state.userInfo.TEAMModelId
            }
            this.$api.mark.FindTask(requestData).then(
                res => {
                    if (!res.error) {
                        this.markList = res.tasks
                        let ch = sessionStorage.getItem('markIndex')
                        ch = ch || 0
                        ch = ch > this.markList.length - 1 ? 0 : ch
                        this.curTaskIndex = ch || 0
                        if (this.markList.length > 0) {
                            let type = this.markList[this.curTaskIndex].type
                            console.log('type', type)
                            switch (type) {
                                case 1:
                                    this.findTaskData()
                                    break
                                // case 2:
                                //     this.findErrData()
                                //     break
                                // case 3:
                                //     this.findArbData()
                                //     break
                                default:
                                    break
                            }
                        }
                    } else {
                        this.$Message.error('API error!')
                    }
                },
                err => {
                    this.$Message.error('API error!')
                }
            )
        },
        //查询当前阅卷任务数据
        findTaskData() {
            let requestData = {
                code: this.markList[this.curTaskIndex].ecode.replace('Exam-', ''),
                id: this.markList[this.curTaskIndex].cid,
                subjectId: this.markList[this.curTaskIndex].subject,
                tmdId: this.$store.state.userInfo.TEAMModelId,
                type: this.markList[this.curTaskIndex].type
            }
            this.$api.mark.FindTeaData(requestData).then(
                async res => {
                    if (!res.error) {
                        //获取试卷完整信息
                        this.fullPaper = await this.$evTools.getFullPaper({
                            blob: res.paper
                        }, 'school')

                        //处理异常题目数据
                        res.objs.forEach(sItem => {
                            sItem.qs.forEach(eItem => {
                                sItem.item[eItem.index].err = eItem.err
                                sItem.item[eItem.index].improve = eItem.improve
                            })
                        })
                        this.markData = res
                    }
                },
                err => {
                    console.log(err)
                }
            )
        },

        findArbData() {

        },
        selectTask(index) {
            this.curTaskIndex = index
            sessionStorage.setItem('markIndex', index)
            if (this.markList.length > 0) {
                let type = this.markList[this.curTaskIndex].type
                console.log('type', type)
                switch (type) {
                    case 1:
                        console.log('task')
                        this.findTaskData()
                        break
                    // case 2:
                    //     this.findErrData()
                    //     break
                    // case 3:
                    //     this.findArbData()
                    //     break
                    default:
                        break
                }
            }
        },

    },
    created() {
        this.findTask()
        this.curBarIndex = sessionStorage.getItem('markMode') || 1
    },
    computed: {
        //试卷题号列表
        quNoList() {
            if (this.fullPaper.item.length) {
                let objectiveQu = ['single', 'multiple', 'judge']
                let data = []
                let realIndex = 0
                this.fullPaper.item.forEach((item, index) => {
                    if (item.children.length) {
                        item.children.forEach((childItem, childIndex) => {
                            let i = realIndex++
                            data.push({
                                label: (index + 1) + '-' + (childIndex + 1),
                                value: i,
                                disabled: objectiveQu.includes(childItem.type)
                            })
                        })
                    } else {
                        let i = realIndex++
                        data.push({
                            label: (index + 1) + '',
                            value: i,
                            disabled: objectiveQu.includes(item.type)
                        })
                    }
                })
                return data
            }
            return []
        },
        //异常数据
        errData() {
            let data = []
            if (this.markData && this.markData.objs) {
                this.markData.objs.forEach(item => {
                    item.qs.forEach(errItem => {
                        data.push({
                            id: item.stuId,
                            index: errItem.index,
                            feedback: errItem.improve || '--',
                            err: errItem.err,
                            status: !!errItem.improve
                        })
                    })
                })
            }
            return data
        },
        //当前阅卷任务未阅数量
        unmarked() {
            if (this.markList.length > 0) {
                let total = this.markList[this.curTaskIndex].count
                let marked = this.markData ? this.markData.objs.length : 0
                return total - marked
            } else {
                return 0
            }
        },
        //当前阅卷任务已阅学生信息
        marked() {
            if (this.markData) {
                console.log('数据', this.markData)
                return this.markData.objs.filter((item) => {
                    let scores = item.item.map(scoreItem => {
                        return scoreItem.sc
                    })
                    //如果是按题分配的任务，只验证指定给老师的题目
                    if (this.markList[this.curTaskIndex].qu.length) {
                        scores = scores.filter((sItem, sIndex) => {
                            return this.markList[this.curTaskIndex].qu.includes(sIndex)
                        })
                    }
                    return !scores.includes(-1)
                })
            } else {
                return []
            }
        },
        //当前阅卷任务进行中学生信息
        marking() {
            if (this.markData) {
                return this.markData.objs.filter((item) => {
                    let scores = item.item.map(scoreItem => {
                        return scoreItem.sc
                    })
                    //如果是按题分配的任务，只验证指定给老师的题目
                    if (this.markList[this.curTaskIndex].qu.length) {
                        scores = scores.filter((sItem, sIndex) => {
                            return this.markList[this.curTaskIndex].qu.includes(sIndex)
                        })
                    }
                    return scores.includes(-1)
                })
            } else {
                return []
            }
        }
    }
}
</script>
<style scoped lang="less">
@import "./index.less";
</style>
<style lang="less">
.stripe-row {
    background: #0000001a;
}
.my-stripe-table .ivu-table td,
.my-stripe-table .ivu-table tr th {
    border-color: transparent !important;
}
</style>