<template>
    <div class="manage-evaluation-container dark-iview-split">
        <Loading :top="200" type="1" style="text-align:center" v-show="isLoading"></Loading>
        <Split v-model="split1">
            <!--评测列表-->
            <div class="evaluation-list-wrap" slot="left">
                <div class="evaluation-list-title">
                    <!-- <span v-if="!$store.state.userInfo.isHeadmaster">{{$t('learnActivity.mgtScEv.listLabel')}}</span> -->
                    <span>{{$t('learnActivity.mgtScEv.listLabel')}}</span>
                    <!-- <Dropdown v-else class="sort-dropdown" trigger="click" placement="bottom-start" @on-click="function(e){ curEvValue = e }" @on-visible-change="dropdownStates">
                        <span style="cursor: pointer;">
                            <b class="title">{{ curEvLabel }}</b>
                            <Icon type="ios-arrow-down" style="margin-left:8px;"></Icon>
                        </span>
                        <DropdownMenu slot="list" v-for="(item,index) in evFilter" :value="item.value" :key="index">
                            <DropdownItem :name="item.value">{{ item.label }}</DropdownItem>
                        </DropdownMenu>
                    </Dropdown> -->
                    <Icon type="md-add" class=" to-create-icon" @click="goToCreate" :title="$t('learnActivity.mgtScEv.create')" />
                    <Icon type="md-trash" v-show="evaListShow.length" class="to-create-icon" :title="$t('learnActivity.mgtScEv.delete')" @click="deleteEvaluation" />
                    <Icon type="md-create" v-show="evaListShow.length && evaListShow[curEvaIndex].progress == 'pending'" class="to-create-icon" @click="editEvaluation" :title="$t('learnActivity.mgtScEv.edit')" />
                </div>
                <div class="evaluation-list-main">
                    <vuescroll>
                        <div v-for="(item,index) in evaListShow" @click="selectEvaluation(index)" :class="['evaluation-item','block-bg',index == curEvaIndex ? 'block-bg-active':'']" :key="index">
                            <p class="evaluation-name">
                                {{item.name}}
                            </p>
                            <p class="evaluation-type">
                                <Icon type="md-time" style="margin-right:5px;" size="16" />
                                <span>{{$t('learnActivity.mgtScEv.createTime')}}{{dateFormat(item.startTime)}}</span>
                            </p>
                            <p class="evaluation-type">
                                <Icon type="md-time" style="margin-right:5px;" size="16" />
                                <span>{{$t('learnActivity.mgtScEv.endTime')}}{{dateFormat(item.endTime)}}</span>
                            </p>
                            <div style="display:inline-flex">
                                <p class="evaluation-type">
                                    <span class="ev-info-tag">{{getTypeLabel(item.type)}}</span>
                                </p>
                                <!-- 评测模式 -->
                                <p class="evaluation-type">
                                    <span class="ev-info-tag">{{getModeLabel(item.source)}}</span>
                                </p>
                                <!-- 活动状态 -->
                                <p class="evaluation-type">
                                    <span class="evaluation-status-tag" :style="{ borderColor: item.progress == 'pending' ? '#0BADD4' : item.progress == 'going' ? '#1CC0F3' : '#949594', color: (item.progress == 'pending' ? '#0BADD4' : item.progress == 'going' ? '#1CC0F3' : '#949594')}">
                                        {{ item.progress == 'pending' ? $t('learnActivity.mgtScEv.pending') : item.progress == 'going' ? $t('learnActivity.mgtScEv.going') : $t('learnActivity.mgtScEv.finish') }}
                                    </span>
                                </p>
                                <!-- 立即结束 -->
                                <p class="evaluation-type">
                                    <span v-if="item.progress == 'going'" class="handle-end-tag" @click="handleEnd(index)">
                                        {{$t('learnActivity.mgtScEv.stop')}}
                                    </span>
                                </p>
                            </div>
                        </div>
                        <EmptyData v-if="evaListShow.length == 0" style="margin-top:180px;" :textContent="$t('learnActivity.mgtScEv.nodata')"></EmptyData>
                    </vuescroll>
                </div>
            </div>
            <div slot="right" class="evaluation-detail-wrap">
                <!--顶部菜单-->
                <div class="evaluation-detail-bar">
                    <span :class="curBarIndex == 0 ? 'evalustion-bar-item line-bottom-active line-bottom':'evalustion-bar-item line-bottom'" @click="selectBar(0)">
                        {{$t('learnActivity.mgtScEv.tab1')}}
                    </span>
                    <span :class="curBarIndex == 1 ? 'evalustion-bar-item line-bottom-active line-bottom':'evalustion-bar-item line-bottom'" @click="selectBar(1)">
                        {{$t('learnActivity.mgtScEv.tab2')}}
                    </span>
                </div>
                <!--试卷信息-->
                <div :class="curBarIndex == 1 ? 'animated fadeIn evaluation-base-info':'evaluation-base-info animated fadeOutRight'" v-show="curBarIndex == 1">
                    <div class="test-paper-detail" style="margin-top:5px;">
                        <vuescroll ref="test-paper-detail" @handle-scroll="checkBackTop">
                            <!--试卷题目信息-->
                            <TestPaper v-if="evaListShow[curEvaIndex] && evaListShow[curEvaIndex].papers && evaListShow[curEvaIndex].papers[curSubIndex] && evaListShow[curEvaIndex].papers[curSubIndex].item" :paper="evaListShow[curEvaIndex].papers[curSubIndex]" style="color:#515a6e;margin-top:-30px;" :isShowTools="false" isExamPaper></TestPaper>
                            <EmptyData v-else style="margin-top:60px;"></EmptyData>
                            <!--返回顶部-->
                            <div class="back-to-top fl-col-center" :title="$t('learnActivity.mgtScEv.returnTop')" v-if="showBack" @click="handleBackToTop">
                                <Icon type="ios-arrow-up" />
                            </div>
                        </vuescroll>
                    </div>
                </div>
                <!-- 试卷评测打分 -->
                <div :class="curBarIndex == 0 ? 'animated fadeIn evaluation-base-info':'evaluation-base-info animated fadeOutRight'" v-show="curBarIndex == 0">
                    <Scoring :examInfo="examDetaiInfo" ref="score-box"></Scoring>
                </div>
            </div>
        </Split>
    </div>
</template>
<script>
import TestPaper from '@/view/evaluation/index/TestPaper.vue'
// import PrivScoring from './PrivScoring.vue'
import Scoring from './Scoring.vue'
export default {
    components: {
        TestPaper,
        Scoring
    },
    inject: ['reload'],
    data() {
        return {
            curEvValue:0,
            split1: 0.2,
            scope: '',//school 校本 private 个人
            showBack: false,
            curSubIndex: 0,
            curBarIndex: 0,
            curEvaIndex: 0,
            evaluationList: [],
            evaListShow: [],
            examDetaiInfo: {},
            targetList: [],
            isLoading: false,
            schoolBase: {
                period: []
            },
            evFilter:[
                {
                    label:this.$t('learnActivity.mgtScEv.myEv'),
                    value:0
                },
                {
                    label:this.$t('learnActivity.mgtScEv.teaEv'),
                    value:1
                }
            ],
            scoreLoading: false,
            answerLoading: false
        }
    },
    methods: {
        /**获取mode对应的label */
        getModeLabel(code) {
            for (let item of this.$GLOBAL.EV_MODE()) {
                if (item.value == code) {
                    return item.label
                }
            }
        },
        dropdownStates(flag) {
            if (!flag) this.filterByTag()
        },
        filterByTag() {
            this.curEvaIndex = 0
        },
        // 模拟教师评分数据
        mockScoring() {
            this.scoreLoading = true
            this.$api.learnActivity.mockScoring({
                id: this.evaListShow[this.curEvaIndex].id,
                code: this.evaListShow[this.curEvaIndex].code.replace('Exam-', '')
            }).then(
                res => {
                    setTimeout(() => {
                        this.$Message.success(this.$t('learnActivity.mgtScEv.mockOk'))
                    }, 500)
                },
                err => {
                    this.$Message.error(this.$t('learnActivity.mgtScEv.mockErr'))
                }
            ).finally(() => {
                setTimeout(() => {
                    this.scoreLoading = false
                    this.reload()
                }, 500)
            })
        },
        // 模拟学生作答数据
        mockAnswer() {
            this.answerLoading = true
            this.$api.learnActivity.mockAnswer({
                id: this.evaListShow[this.curEvaIndex].id,
                code: this.evaListShow[this.curEvaIndex].code.replace('Exam-', '')
            }).then(
                res => {
                    setTimeout(() => {
                        this.$Message.success(this.$t('learnActivity.mgtScEv.mockOk'))
                    }, 500)
                },
                err => {
                    this.$Message.error(this.$t('learnActivity.mgtScEv.mockErr'))
                }
            ).finally(() => {
                setTimeout(() => {
                    this.answerLoading = false
                    this.reload()
                }, 500)
            })
        },
        handleEnd(index) {
            this.$Modal.confirm({
                title: this.$t('learnActivity.mgtScEv.stopTitle'),
                content: `${this.$t('learnActivity.mgtScEv.stopContent')}${this.evaListShow[index].name}?`,
                onOk: () => {
                    this.$api.learnActivity.FinishEva({
                        id: this.evaListShow[index].id,
                        code: this.evaListShow[index].code.replace('Exam-', '')
                    }).then(
                        res => {
                            if (!res.error) {
                                this.$Message.success(this.$t('learnActivity.mgtScEv.stopOk'))
                                this.evaListShow[index].progress = 'finish'
                            } else {
                                this.$Message.error('API ERROR！')
                            }
                        },
                        err => {
                            this.$Message.error('API ERROR！')
                        }
                    )
                }
            })
        },
        /**获取type对应的label */
        getTypeLabel(code) {
            for (let item of this.$GLOBAL.EV_TYPE()) {
                if (item.value == code) {
                    return item.label
                }
            }
        },
        /**
         * 查找班级课程下的班级
         * */
        findClassroom() {
            if (this.targetList.length == 0) {
                let requestData = this.$store.state.userInfo.TEAMModelId
                this.$api.learnActivity.FindClassroomByTeacherId({
                    code: requestData
                }).then(
                    res => {
                        if (res.error == null) {
                            this.targetList = res.result.data
                        } else {
                            this.$Message.error('API ERROR!')
                        }
                    },
                    err => {

                    }
                )
            }
        },
        /**
         * 判断是否显示回到顶部按钮
         * @param vertical
         * @param horizontal
         * @param nativeEvent
         */
        checkBackTop(vertical, horizontal, nativeEvent) {
            if (vertical.scrollTop > 100) {
                this.showBack = true
            } else {
                this.showBack = false
            }
        },
        /**vuescroll回到顶部 */
        handleBackToTop() {
            this.$refs['test-paper-detail'].scrollTo(
                { y: '0' }, 300
            )
        },
        /**删除评测信息 */
        deleteEvaluation() {
            this.$Modal.confirm({
                title: this.$t('learnActivity.mgtScEv.deleteTitle'),
                content: `${this.$t('learnActivity.mgtScEv.deleteContent')}${this.evaListShow[this.curEvaIndex].name}?`,
                onOk: () => {
                    let params = {
                        id: this.evaListShow[this.curEvaIndex].id,
                        code: this.evaListShow[this.curEvaIndex].code.replace('Exam-', ''),
                        scope: this.evaListShow[this.curEvaIndex].scope
                    }
                    this.isLoading = true
                    this.$api.learnActivity.DeleteExamInfo(params).then(
                        res => {
                            if (res.error == null) {
                                let index = this.curEvaIndex
                                this.selectEvaluation(0)
                                this.evaListShow.splice(index, 1)
                                this.$Message.success(this.$t('learnActivity.mgtScEv.deleteOk'))
                            } else {
                                this.$Message.error(this.$t('learnActivity.mgtScEv.deleteErr'))
                            }
                        },
                        err => {
                            this.$Message.error(this.$t('learnActivity.mgtScEv.deleteErr'))
                        }
                    ).finally(() => {
                        setTimeout(() => {
                            this.isLoading = false
                        }, 500)
                    })
                }
            })
        },
        goToCreate() {
            // if (this.$store.state.user.schoolProfile.school_base) { //这里判断必须要加入学校才能创建评测
                if (this.scope == 'school') {
                    this.$router.push({
                        name: 'createSchoolEva'
                    })
                } else if (this.scope == 'private') {
                    this.$router.push({
                        name: 'createPrivEva'
                    })
                }
            // } else {
            //     this.$Message.warning(this.$t('learnActivity.mgtScEv.noJoin'))
            // }
        },
        editEvaluation() {
            this.$router.push({
                name: 'createPrivEva',
                params: {
                    evaluationInfo: this.examDetaiInfo
                }
            })
        },
        selectSubject(index) {
            this.curSubIndex = index
        },
        selectBar(index) {
            this.curBarIndex = index
        },
        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;
        },
        //查询评测列表
        findEvaluation() {
            let requestData = {
                code: this.scope == 'school' ? this.$store.state.userInfo.schoolCode : this.$store.state.userInfo.TEAMModelId
            }
            this.$api.learnActivity.FindExamInfo(requestData).then(
                res => {
                    if (!res.error) {
                        res.examInfo = res.examInfo.sort((a, b) => {
                            return a.createTime - b.createTime > 0 ? -1 : 1
                        })
                        this.evaluationList = res.examInfo
                        this.evaListShow = res.examInfo
                        if (res.examInfo.length) this.selectEvaluation(0)

                    } else {
                        this$Message.error('API ERROR!')
                    }
                }
            )
        },
        selectEvaluation(index) {
            this.curSubIndex = 0
            this.curEvaIndex = index
            this.$refs['score-box'].showTest = false
            if (this.evaListShow[this.curEvaIndex] && this.evaListShow[this.curEvaIndex].papers.length == 0) {
                this.findExamPaper()
            } else {
                this.examDetaiInfo = this.evaListShow[this.curEvaIndex]
            }
        },
        //查询当前评测的试卷信息
        findExamPaper() {
            let requestData = {
                id: this.evaListShow[this.curEvaIndex].id,
                code: this.evaListShow[this.curEvaIndex].code
            }
            this.isLoading = true
            this.$api.learnActivity.FindExamInfos(requestData).then(
                async res => {
                    if (!res.error) {
                        let resData = res.examInfo[0]
                        resData.score = 0
                        for (let index in resData.papers) {
                            resData.score += resData.papers[index].point.reduce((total, item) => {
                                return total + parseInt(item)
                            }, 0)
                            if (resData.papers[index].blob) {
                                let blob = resData.papers[index].blob
                                resData.papers[index].examScope = resData.scope
                                resData.papers[index].examId = resData.id
                                resData.papers[index] = await this.$evTools.getFullPaper(resData.papers[index])
                                resData.papers[index].blob = blob
                                resData.score += resData.papers[index].score
                            }
                        }
                        this.evaListShow.splice(this.curEvaIndex, 1, resData)
                        this.examDetaiInfo = resData
                    } else {
                        this.$Message.error('API ERROR!')
                    }
                },
                err => {
                    this.$Message.error('API ERROR!')
                }
            ).finally(() => {
                this.isLoading = false;
            })
        }
    },
    created() {
        if (this.$route.name == 'privateEvaluation') {
            this.scope = 'private'
        } else if (this.$route.name == 'schoolEvaluation') {
            this.scope = 'school'
        }
        this.$store.dispatch('user/getSchoolProfile').then(
            (res) => {
                if (res) {
                    this.schoolBase = res.school_base
                }
            }
        ).finally(() => {
            this.findEvaluation()
        })
    },
    watch: {
        $route: {
            handler: function (to, from) {
                if (this.$route.name == 'privateEvaluation') {
                    this.scope = 'private'
                } else if (this.$route.name == 'schoolEvaluation') {
                    this.scope = 'school'
                }
            },
            immediate: true
        }
    },
    computed: {
        curEvLabel: function () {
            let value = this.curEvValue
            console.log(this.curEvValue)
            let curObj = this.evFilter.find(item=>{
                return item.value == value
            })
            return curObj.label
        },
    }
}
</script>
<style lang="less" scoped>
@import "./MgtPrivEva.less";
</style>
<style lang="less">
.evalustion-base-attr .ivu-form .ivu-form-item-label {
    color: #a5a5a5;
}
.evaluation-attr-form .ivu-select-disabled .ivu-select-selection {
    background: none;
}
.sort-dropdown {
    .title {
        color: white;
        font-size: 14px;
    }
    .ivu-select-dropdown {
        background-color: #2d2d2d;
        border-radius: 2px;
        border: 1px #464646 solid;
        .ivu-dropdown-menu {
            li {
                color: #ccc;
                font-size: 12px !important;
                &:hover {
                    color: #2d2d2d;
                }
            }
        }
    }
}
// .test-paper-detail .paper-container{
//     padding-bottom: 30px;
// }
</style>
