<template>
    <div class="create-school-container">
        <div class="create-header">
            <p class="create-header-title" @click="test">{{$t('learnActivity.createEv.createLabel')}}</p>
            <Button class="btn-save" type="text" :loading="isLoading" ghost icon="ios-albums-outline" @click="saveEvaluation" style="margin-right:30px;">
                {{$t('learnActivity.createEv.publishEv')}}
            </Button>
            <Button class="btn-save" type="text" ghost icon="md-arrow-back" @click="confirmToManage">
                {{$t('learnActivity.createEv.return')}}
            </Button>
        </div>
        <div class="create-body">
            <div class="evaluation-attr-wrap">
                <p class="wrap-label">{{$t('learnActivity.createEv.baseInfo')}}</p>
                <div style="width:100%; height:calc(100% - 45px);padding-top:30px;" class="dark-iview-form ivu-select-nochoose dark-el-cascader">
                    <vuescroll>
                        <Form ref="evaForm" :model="evaluationInfo" label-position="top" class="evaluation-attr-form " label-colon :rules="ruleValidate">
                            <FormItem :label="$t('learnActivity.createEv.evName')" prop="name">
                                <Input v-model="evaluationInfo.name" :placeholder="$t('learnActivity.createEv.evName')"></Input>
                            </FormItem>
                            <FormItem :label="$t('learnActivity.createEv.evPeriod')" prop="period.id" v-if="mode == 'school'">
                                <Select v-model="evaluationInfo.period.id" @on-change="setPeriodName" @on-open-change="checkChangePeriod" label-in-value>
                                    <Option v-for="(item,index) in $store.state.user.schoolProfile.periods" :value="item.id" :key="index">{{ item.name }}</Option>
                                </Select>
                            </FormItem>
                            <FormItem :label="$t('learnActivity.createEv.evMode')" prop="source">
                                <Select v-model="evaluationInfo.source">
                                    <Option v-for="(item,index) in $GLOBAL.EV_MODE()" :value="item.value" :key="index">{{ item.label }}</Option>
                                </Select>
                            </FormItem>
                            <FormItem :label="$t('learnActivity.createEv.evType')" prop="type">
                                <Select v-model="evaluationInfo.type">
                                    <Option v-for="(item,index) in $GLOBAL.EV_TYPE()" :value="item.value" :key="index">{{ item.label }}</Option>
                                </Select>
                            </FormItem>
                            <FormItem :label="$t('learnActivity.createEv.examType')" prop="examType.id">
                                <Select v-model="evaluationInfo.examType.id" @on-change="setExamTypeName" label-in-value>
                                    <Option v-for="(item,index) in testType" :value="item.id" :key="index">{{ item.name }}</Option>
                                </Select>
                            </FormItem>
                            <!-- 校园评测施测对象为系统班级 -->
                            <FormItem :label="$t('learnActivity.createEv.evTarget')" prop="targets">
                                <el-cascader size="small" :show-all-levels="false" clearable filterable v-model="evaluationInfo.targets" :options="csOptions" :props="props" @change="treeChange" style="width:100%;">
                                </el-cascader>
                            </FormItem>
                            <FormItem :label="$t('learnActivity.createEv.publishType')" prop="publish">
                                <!-- <RadioGroup v-model="evaluationInfo.publish" style="color:white;">
                                    <Radio :label="item.value" :key="index" v-for="(item,index) in $GLOBAL.PUBLISH_TYPE()" style="width:120px;">
                                        <span>{{ item.label }}</span>
                                    </Radio>
                                </RadioGroup> -->
                                <Checkbox v-model="evaluationInfo.publish" :true-value="$GLOBAL.PUBLISH_TYPE()[0].value" :false-value="$GLOBAL.PUBLISH_TYPE()[1].value" @on-change="publishChange">
                                    <span style="color:white;margin-left:5px;user-select: none;">{{$GLOBAL.PUBLISH_TYPE()[0].label}}</span>
                                </Checkbox>
                            </FormItem>
                            <FormItem :label="$t('learnActivity.createEv.startTime')" v-if="evaluationInfo.publish == 1" prop="startTime">
                                <DatePicker :options="dateOpt" type="datetime" format="yyyy/MM/dd HH:mm" v-model="startTime" split-panels :placeholder="$t('learnActivity.createEv.sTimeHolder')" style="width:100%" @on-change="getDate($event,0)"></DatePicker>
                            </FormItem>
                            <FormItem :label="$t('learnActivity.createEv.endTime')" prop="endTime">
                                <DatePicker :options="dateOpt1" type="datetime" format="yyyy/MM/dd HH:mm" v-model="endTime" split-panels :placeholder="$t('learnActivity.createEv.eTimeHolder')" style="width:100%" @on-change="getDate($event,1)"></DatePicker>
                            </FormItem>
                        </Form>
                    </vuescroll>
                </div>
            </div>
            <div class="evaluation-question-wrap">
                <div class="wrap-label" v-if="mode == 'school'">
                    <p>{{$t('learnActivity.mgtScEv.evSubject')}}</p>
                    <span v-for="(item,index) in evaluationInfo.paperInfo" :key="index" :class="index == curSubIndex ? 'subject-item subject-item-active':'subject-item'" @click="selectSubject(index)">
                        {{item.subjectName}}
                        <Icon type="ios-close" size="18" class="delete-subject-btn" @click="deleteSubject(index)" />
                    </span>
                    <Icon @click="addSubject" type="md-add" :title="$t('learnActivity.createEv.addSubject')" class="add-subject-icon" />
                </div>
                <div class="evaluation-question-main">
                    <EmptyData :top="0" style="padding-top:100px;" v-if="evaluationInfo.paperInfo.length == 0" :textContent="$t('learnActivity.createEv.noSubject')"></EmptyData>
                    <Tabs v-model="activeTab" type="card" class="question-main-tabs" v-if="evaluationInfo.paperInfo.length > 0 || mode == 'class' " name="createTest">
                        <TabPane :label="$t('learnActivity.createEv.papersLabel')" name="manualPaper" v-if="evaluationInfo.paperInfo[curSubIndex].createType == 'manualPaper'" :index="1" tab="createTest">
                            <ManualPaper :periodId="evaluationInfo.period.id" :gradesObj="evaluationInfo.grades" :subjectId="evaluationInfo.paperInfo[curSubIndex].subjectId" @selectPaper="selectPaper" :selectedId="evaluationInfo.paperInfo[curSubIndex].id" :source="$store.state.userInfo.schoolCode"></ManualPaper>
                        </TabPane>
                        <TabPane :label="$t('learnActivity.createEv.perviewLabel')" name="preview" :index="2" tab="createTest">
                            <TeacherPreview :testPaper="evaluationInfo.paperInfo[curSubIndex]" :examAnalysisStatus="examAnalysisStatus"></TeacherPreview>
                        </TabPane>
                        <TabPane :label="$t('learnActivity.createEv.importLabel')" name="import" v-if="evaluationInfo.paperInfo[curSubIndex].createType == 'import'" :index="4" tab="createTest">
                            <BaseImport @importedQuestions="getImportQuestions" @goToPreview="goToPreview"></BaseImport>
                        </TabPane>
                        <TabPane :label="$t('learnActivity.createEv.answerPreview')" name="student" :index="6" tab="createTest">
                            <StudentPreview></StudentPreview>
                        </TabPane>
                    </Tabs>
                </div>
            </div>
        </div>
        <Modal v-model="addSubjectStatus" :title="$t('learnActivity.createEv.addSubject')" class-name="dark-iview-modal" @on-ok="confirmAddSubject">
            <div style="padding:20px 0px;">
                <CheckboxGroup v-model="evaluationInfo.subjectIds" style="color:white;">
                    <Checkbox v-for="(subjectItem,index) in curSubjects" :key="index" :label="subjectItem.id">
                        <span>{{subjectItem.name}}</span>
                    </Checkbox>
                </CheckboxGroup>
                <p v-if="!evaluationInfo.period.id" style="color:white; text-align:center;">{{$t('learnActivity.createEv.noSubject1')}}</p>
            </div>
        </Modal>
    </div>
</template>
<script>
import BlobTool from '@/utils/blobTool.js'
import ManualPaper from './ManualPaper.vue'
import BaseImport from '@/view/evaluation/components/BaseImport.vue'
import TeacherPreview from './TeacherPreview.vue'
import StudentPreview from './StudentPreview.vue'
export default {
    components: {
        TeacherPreview,
        StudentPreview,
        BaseImport,
        ManualPaper,
    },
    data() {
        let _this = this
        return {
            schoolClasses: [],
            props: {
                multiple: true,
                value: 'id',
                label: 'name'
            },
            schoolBase: {
                period: []
            },
            dateOpt: {
                disabledDate(date) {
                    return date && date.valueOf() < Date.now() - 86400000
                }
            },
            dateOpt1: {
                disabledDate(date) {
                    let d = _this.evaluationInfo.startTime ? _this.evaluationInfo.startTime : Date.now()
                    return d && d > date.valueOf() + 86400000
                }
            },
            startTime: '',
            endTime: '',
            privClassList: [],
            examAnalysisStatus: false,
            comfirmPreviewStatus: false,
            addSubjectStatus: false,
            isLoading: false,
            examInfo: {},
            ruleValidate: {
                name: [
                    { required: true, message: this.$t('learnActivity.createEv.errTips1'), trigger: 'change' }
                ],
                'type.id': [
                    { required: true, message: this.$t('learnActivity.createEv.errTips2'), trigger: 'change' }
                ],
                source: [
                    { required: true, message: this.$t('learnActivity.createEv.errTips3'), trigger: 'change' }
                ],
                'period.id': [
                    { required: true, message: this.$t('learnActivity.createEv.errTips10'), trigger: 'change' }
                ],
                'type': [
                    { required: true, message: this.$t('learnActivity.createEv.errTips4'), trigger: 'change' }
                ],
                'examType.id': [
                    { required: true, message: this.$t('learnActivity.createEv.errTips5'), trigger: 'change' }
                ],
                targets: [
                    { required: true, message: this.$t('learnActivity.createEv.errTips6'), type: 'array', trigger: 'change' }
                ],
                publish: [
                    { required: true, message: this.$t('learnActivity.createEv.errTips7'), trigger: 'change' }
                ],
                startTime: [
                    { required: true, type: 'number', message: this.$t('learnActivity.createEv.errTips8'), trigger: 'change' }
                ],
                endTime: [
                    { required: true, type: 'number', message: this.$t('learnActivity.createEv.errTips9'), trigger: 'change' }
                ]
            },
            activeTab: 'manualPaper', //默认到试卷库
            curSubIndex: 0,
            evaluationInfo: {
                name: '',
                targets: [],
                classes: [],
                grades: [],
                type: '',  //测试类别
                source: '',
                publish: '0',
                subjects: [],
                subjectIds: [],
                period: {}, //学段
                examType: {}, //测试类型
                startTime: undefined,
                endTime: undefined,
                paperInfo: [],
                papers: []
            },
            mode: '',
            befPeriod: {
                id: '',
                name: ''
            }
        }
    },
    methods: {
        test() {
            console.log(this.evaluationInfo)
        },
        publishChange(data) {
            if (data == 0) {
                this.startTime = new Date()
                this.evaluationInfo.startTime = Date.now()
            }
        },
        //设置学科名称
        setSubjectName() {
            this.evaluationInfo.subjects = this.curSubjects.filter(item => {
                return this.evaluationInfo.subjectIds.indexOf(item.id) >= 0
            })
        },
        //设置考试类型名称
        setExamTypeName(data) {
            this.evaluationInfo.examType.name = data.label
        },
        //设置学段名称
        setPeriodName(data) {
            if (this.befPeriod.id && this.befPeriod.id != this.evaluationInfo.period.id && this.evaluationInfo.paperInfo.length > 0) {
                this.$Modal.confirm({
                    title: this.$t('learnActivity.createEv.togglePeriod'),
                    content: `${this.$t('learnActivity.createEv.togglePdTip1')}${this.befPeriod.name}${this.$t('learnActivity.createEv.togglePdTip2')}`,
                    okText: this.$t('learnActivity.createEv.toggleOkText'),
                    onOk: () => {
                        this.evaluationInfo.period.name = data.label
                        this.evaluationInfo.paperInfo = []
                        this.evaluationInfo.papers = []
                        this.evaluationInfo.subjectIds = []
                        this.evaluationInfo.subjects = []
                    },
                    onCancel: () => {
                        this.evaluationInfo.period = this._.cloneDeep(this.befPeriod)
                    }
                })
            }
            this.evaluationInfo.period.name = data.label
        },
        //学段选择展开时
        checkChangePeriod(status) {
            if (status) {
                this.befPeriod = this._.cloneDeep(this.evaluationInfo.period)
            }
        },

        treeChange(data) {
            //获取classIds
            this.evaluationInfo.classes = data.map(item => {
                return item[1]
            })
            //获取年级对象
            let graIds = new Set(data.map(item => {
                return item[0]
            }))
            graIds = Array.from(graIds)

            this.evaluationInfo.grades = graIds.map(item => {
                return {
                    id: item + '',
                    name: this.curGrades[item]
                }
            })
            // this.evaluationInfo.grades = this.curGrades.filter(item => {
            //     return graIds.indexOf(item.id) >= 0
            // })
        },
        /*
         * 返回上一级
         */
        confirmToManage() {
            if (this.mode == 'private') {
                this.$router.push({
                    name: 'privateEvaluation'
                })
            } else {
                this.$router.push({
                    name: 'schoolEvaluation'
                })
            }
        },
        /**
         * 处理挑选试卷事件
         * @param data
         */
        selectPaper(data) {
            let simplePaper = data
            this.$Modal.confirm({
                title: this.$t('learnActivity.createEv.stPaperTitle'),
                content: `${this.$t('learnActivity.createEv.stPaperContent')}${data.name}?`,
                onOk: async () => {
                    let fullPaper = await this.$evTools.getFullPaper(simplePaper)
                    this.comfirmSelectPaper(simplePaper, fullPaper)
                }
            })
        },
        comfirmSelectPaper(simplePaper, fullPaper) {
            let curSubName = this.evaluationInfo.paperInfo[this.curSubIndex].subjectName
            let curSubId = this.evaluationInfo.paperInfo[this.curSubIndex].subjectId
            this.evaluationInfo.paperInfo[this.curSubIndex] = fullPaper
            this.evaluationInfo.papers[this.curSubIndex] = simplePaper
            //解决学科被覆盖
            this.evaluationInfo.paperInfo[this.curSubIndex].subjectId = curSubId
            this.evaluationInfo.paperInfo[this.curSubIndex].subjectName = curSubName
            this.evaluationInfo.papers[this.curSubIndex].subjectId = curSubId
            this.evaluationInfo.papers[this.curSubIndex].subjectName = curSubName
            this.evaluationInfo.papers[this.curSubIndex].periodId = this.evaluationInfo.period.id
            this.evaluationInfo.paperInfo[this.curSubIndex].periodId = this.evaluationInfo.period.id

            this.goToPreview()
        },

        /**
         * 将日期控件时间格式转成时间戳
         * @param value
         * @param flag 0 开始时间 1 结束时间
         */
        getDate(value, flag) {
            if (value.indexOf('00:00') > 0) {
                value = value.replace('00:00', '23:59:59')
            }
            if (flag == 0) {
                this.startTime = value
                this.evaluationInfo.startTime = new Date(value).getTime()
                if (this.evaluationInfo.startTime > this.evaluationInfo.endTime) {
                    this.endTime = undefined
                    this.evaluationInfo.endTime = undefined
                }
            } else if (flag == 1) {
                this.endTime = value
                this.evaluationInfo.endTime = new Date(value).getTime()
            }
        },
        /**
         * 获取导入试卷题目
         * @param questions
         */
        getImportQuestions(questions) {
            if (this.evaluationInfo.paperInfo[this.curSubIndex].item != undefined) {
                this.evaluationInfo.paperInfo[this.curSubIndex].item = [...questions, ...this.evaluationInfo.paperInfo[this.curSubIndex].item]
            } else {
                this.evaluationInfo.paperInfo[this.curSubIndex].item = [...questions]
            }
        },
        goToPreview() {
            this.activeTab = 'preview'
            this.evaluationInfo.paperInfo[this.curSubIndex].createType = 'manualPaper'
        },
        inDevelopment() {
            this.$Message.info(this.$t('learnActivity.createEv.inDev'))
        },
        setActiveTab(data) {
            this.activeTab = data
        },
        deleteSubject(index) {
            this.$Modal.confirm({
                title: this.$t('learnActivity.createEv.delPdTitle'),
                content: this.$t('learnActivity.createEv.delPdContent') + this.evaluationInfo.paperInfo[index].subjectName + '?',
                onOk: () => {
                    for (let i in this.evaluationInfo.subjects) {
                        if (this.evaluationInfo.subjects[i].id == this.evaluationInfo.paperInfo[index].subjectId) {
                            this.evaluationInfo.subjects.splice(i, 1)
                            break
                        }
                    }
                    for (let i in this.evaluationInfo.subjectIds) {
                        if (this.evaluationInfo.subjectIds[i] == this.evaluationInfo.paperInfo[index].subjectId) {
                            this.evaluationInfo.subjectIds.splice(i, 1)
                            break
                        }
                    }
                    this.evaluationInfo.paperInfo.splice(index, 1)
                    this.evaluationInfo.papers.splice(index, 1)
                    this.curSubIndex = 0
                    this.$Message.success(this.$t('learnActivity.createEv.delOk'))
                },
                onCancel: () => {
                },
            })
        },
        addSubject() {
            if (this.evaluationInfo.period !== '') {
                this.addSubjectStatus = true
            } else {
                this.$Message.warning(this.$t('learnActivity.createEv.pdTips'))
            }
        },
        confirmAddSubject() {
            this.setSubjectName()
            console.log(this.evaluationInfo)
            //查看是否已有对应学科试卷
            for (let item of this.evaluationInfo.subjects) {
                let f = this.evaluationInfo.paperInfo.find(paper => {
                    return paper.subjectId == item.id
                })
                if (!f) {
                    this.evaluationInfo.paperInfo.push({
                        periodName: this.evaluationInfo.name,
                        periodId: this.evaluationInfo.id,
                        subjectName: item.name,
                        subjectId: item.id,
                        createType: 'manualPaper',
                        score: 100,
                        item: [],
                        filter: {},
                        name: this.$t('learnActivity.createEv.defaultPaper')
                    })
                }
            }
            //处理取消选择学科逻辑
            for (let i = 0; i < this.evaluationInfo.paperInfo.length; i++) {
                let subId = this.evaluationInfo.paperInfo[i].subjectId
                if (this.evaluationInfo.subjectIds.indexOf(subId) < 0) {
                    this.evaluationInfo.paperInfo.splice(i, 1)
                    i--
                }
            }
        },
        selectSubject(index) {
            this.curSubIndex = index
            this.activeTab = 'preview'
        },
        /**
         * 检查试卷数据完整性
         * @param paperInfo
         */
        checkPaper(paperInfo) {
            if (!paperInfo.code) {
                paperInfo.code = this.examInfo.id
            }
            if (!paperInfo.markConfig) {
                paperInfo.markConfig = {
                    "auto": false,
                    "type": 0,
                    "score": 0
                }
            }
        },
        /**
         * 保存试卷
         * @param paperInfo
         * @param index
         */
        saveTestPaper(paperInfo, index) {
            if (this.examInfo.id == undefined) {
                this.isLoading = true
                this.saveEvaluation()
            } else {
                this.checkPaper(paperInfo)
                this.$api.learnActivity.SaveExamPaper(paperInfo).then(
                    res => {
                        if (res.error == null) {
                            this.evaluationInfo.paperInfo[index].id = res.result.data.id
                        } else {
                            this.$Message.error('API ERROR!')
                        }
                    },
                    err => {
                        this.$Message.error('API ERROR!')
                    }
                )
            }
        },
        async saveEvaluation() {
            //表单验证
            let flag = true
            console.log(this.evaluationInfo)
            this.$refs['evaForm'].validate((valid) => {
                if (!valid) {
                    this.$Message.warning(this.$t('learnActivity.createEv.formWarning'))
                    flag = false
                }
            })
            if (!flag) {
                return
            }
            //检查试卷是否添加
            if (this.evaluationInfo.subjects == 0) {
                this.$Message.warning(this.$t('learnActivity.createEv.pdWarning'))
                flag = false
            }
            if (this.evaluationInfo.subjects.length != this.evaluationInfo.papers.length) {
                for (let subjectItem of this.evaluationInfo.subjects) {
                    let res = this.evaluationInfo.papers.find(paper => {
                        return paper.subjectId == subjectItem.id
                    })
                    if (!res) {
                        this.$Message.warning({
                            content: `${subjectItem.name}${this.$t('learnActivity.createEv.paperWarning1')}`,
                            duration: 2
                        })
                        break
                    }
                }
                flag = false
            }
            if (!flag) {
                return
            }
            //通过验证，保存评测
            this.isLoading = true
            let requestData = {
                pk: 'Exam',
                id: this.evaluationInfo.id || null,
                code: this.$store.state.userInfo.schoolCode,
                school: this.$store.state.userInfo.schoolCode,
                name: this.evaluationInfo.name,
                creatorId: this.$store.state.userInfo.TEAMModelId,
                type: this.evaluationInfo.type,
                period: this.evaluationInfo.period,
                grades: this.evaluationInfo.grades,
                subjects: this.evaluationInfo.subjects,
                papers: this.getPaperInfo(),
                examType: this.evaluationInfo.examType,
                year: new Date().getFullYear(),
                range: this.mode,
                source: this.evaluationInfo.source,
                classes: this.evaluationInfo.classes,
                // publish: this.evaluationInfo.publish,//后端去掉此字段，立即发布由后端获取时间
                startTime: this.evaluationInfo.publish == 0 ? -1 : this.evaluationInfo.startTime,//立即发布由后端获取时间
                endTime: this.evaluationInfo.endTime,
                scope: this.mode,
                createDate: Math.round(new Date()),
                // blobcntr: this.$store.state.userInfo.schoolCode //后面新增字段 (废弃)
                owner: 'school' //后面新增字段
            }

            this.$api.learnActivity.SaveExamInfo(requestData).then(
                res => {
                    if (res.error == null) {

                        //发布成功需要备份试卷数据
                        let examId = res.exam.id
                        // let privateSas = this.$store.state.privateSas
                        let privateSas = {}
                        if(this.$store.state.user.userProfile){
                            let blobInfo = this.$store.state.user.userProfile
                            privateSas.sas = '?' + blobInfo.blob_sas
                            privateSas.url = blobInfo.blob_uri.slice(0, blobInfo.blob_uri.lastIndexOf(this.$store.state.userInfo.TEAMModelId) - 1)
                            privateSas.name = this.$store.state.userInfo.TEAMModelId
                        }

                        let schoolSas = {
                            sas: '?' + this.$store.state.user.schoolProfile.blob_sas,
                            url: this.$store.state.user.schoolProfile.blob_uri.slice(0, this.$store.state.user.schoolProfile.blob_uri.lastIndexOf(this.$store.state.userInfo.schoolCode) - 1),
                            name: this.$store.state.userInfo.schoolCode
                        }
                        let schoolBlob = new BlobTool(schoolSas.url, schoolSas.name, schoolSas.sas, 'school')
                        let privateBlob = undefined
                        let targetFolder = 'exam/' + examId + '/paper/'
                        let count = 0
                        requestData.papers.forEach(async (item, index) => {
                            if (item.blob.indexOf('/exam/') == 0) {
                                if (++count == (requestData.papers.length)) {
                                    setTimeout(() => {
                                        this.$Message.success(this.$t('learnActivity.createEv.publishOk'))
                                        this.isLoading = false
                                        let route = this.mode + 'Evaluation'
                                        this.$router.push({
                                            name: route
                                        })
                                    }, 2000)
                                }
                                return
                            }
                            if (item.scope == 'school') {
                                schoolBlob.copyFolder(targetFolder + requestData.subjects[index].id + '/', item.blob.substring(1)).then().finally(
                                    () => {
                                        if (++count == (requestData.papers.length)) {
                                            setTimeout(() => {
                                                this.$Message.success(this.$t('learnActivity.createEv.publishOk'))
                                                this.isLoading = false
                                                let route = this.mode + 'Evaluation'
                                                this.$router.push({
                                                    name: route
                                                })
                                            }, 2000)
                                        }
                                    }
                                )
                            } else if (item.scope == 'private') {
                                if (!privateBlob) privateBlob = new BlobTool(privateSas.url, privateSas.name, privateSas.sas, 'private')
                                schoolBlob.copyFolder(targetFolder + requestData.subjects[index].id + '/', item.blob.substring(1), privateBlob).then().finally(
                                    () => {
                                        if (++count == (requestData.papers.length)) {
                                            setTimeout(() => {
                                                this.$Message.success(this.$t('learnActivity.createEv.publishOk'))
                                                this.isLoading = false
                                                let route = this.mode + 'Evaluation'
                                                this.$router.push({
                                                    name: route
                                                })
                                            }, 2000)
                                        }
                                    }
                                )
                            }
                        })
                    } else {
                        this.$Message.error('API ERROR!')
                        this.isLoading = false
                    }
                },
                err => {
                    this.isLoading = false
                    this.$Message.error('API ERROR!')
                }
            )
        },
        //拼接API需要的paper数据
        getPaperInfo() {
            let data = this.evaluationInfo.papers
            let rule = this.evaluationInfo.paperInfo
            if (data) {
                let paperDto = []
                for (let i = 0; i < data.length; i++) {
                    console.log(data[i])
                    if (data[i].blob.indexOf('/exam/') == 0) {
                        paperDto.push(data[i])
                    } else {
                        let paper = {}
                        paper.id = data[i].id
                        paper.code = data[i].code
                        paper.name = data[i].name
                        paper.blob = data[i].blob
                        paper.scope = data[i].scope
                        paper.multipleRule = rule[i].multipleRule
                        paper.answers = []
                        paper.point = []
                        paper.knowledge = []
                        paper.field = []
                        paper.type = []//后面新增字段， 保存每个题目类型
                        for (let k = 0; k < rule[i].slides.length; k++) {
                            if (rule[i].slides[k].type !== 'compose') {
                                paper.answers.push(rule[i].slides[k].scoring.ans ? rule[i].slides[k].scoring.ans : [])
                                paper.point.push(rule[i].slides[k].scoring.score)
                                paper.knowledge.push(rule[i].slides[k].scoring.knowledge ? rule[i].slides[k].scoring.knowledge : [])
                                paper.field.push(rule[i].slides[k].scoring.field ? rule[i].slides[k].scoring.field : [])
                                paper.type.push(rule[i].slides[k].type) //后面新增字段， 保存每个题目类型
                            }
                        }
                        paperDto.push(paper)
                    }
                }
                return paperDto
            } else {
                return []
            }
        }
    },
    created() {
        // 处理默认时间
        this.startTime = new Date()
        this.evaluationInfo.startTime = new Date().getTime()
        this.endTime = new Date(new Date(new Date().toLocaleDateString()).getTime() + 2 * 24 * 60 * 60 * 1000 - 1)
        this.evaluationInfo.endTime = new Date(new Date().toLocaleDateString()).getTime() + 2 * 24 * 60 * 60 * 1000 - 1

        this.$store.dispatch('user/getSchoolProfile').then(
            res => {
                this.schoolBase = res.school_base
                this.schoolClasses = res.school_classes
            }
        )
        //判断创建个人还是校本评测
        if (this.$route.name == 'createSchoolEva') {
            this.mode = 'school'
        }

        //编辑评测逻辑
        let routerData = this.$route.params.evaluationInfo
        if (routerData !== undefined) {
            this.startTime = new Date(routerData.startTime)
            this.endTime = new Date(routerData.endTime)
            routerData.subjectIds = routerData.subjects.map(item => {
                return item.id
            })
            routerData.paperInfo = []
            for (let i = 0; i < routerData.papers.length; i++) {
                let paper = this._.cloneDeep(routerData.papers[i])
                routerData.paperInfo.push(paper)
                routerData.paperInfo[i].createType = 'manualPaper'
                routerData.paperInfo[i].subjectId = routerData.subjects[i].id
                routerData.paperInfo[i].subjectName = routerData.subjects[i].name
            }
            this.evaluationInfo = routerData
            this.$store.dispatch('user/getSchoolProfile').then(
                res => {
                    let f = res.school_classes.filter((item) => {
                        return routerData.classes.indexOf(item.id) > -1
                    })
                    this.evaluationInfo.targets = []
                    f.forEach((item, index) => {
                        let arr = [
                            item.gradeId,
                            item.id
                        ]
                        this.evaluationInfo.targets.push(arr)
                    })
                }
            )
            this.activeTab = 'preview'
        }
    },
    computed: {
        //级联选择年级班级
        csOptions() {
            let data = []
            if (this.evaluationInfo.period.id && this.schoolBase.period.length && this.schoolClasses.length) {
                let curPd = this.schoolBase.period.find((item) => {
                    return item.id == this.evaluationInfo.period.id
                })
                if (curPd) {
                    //计算学级逻辑
                    let date = new Date()
                    let curYear = date.getFullYear()
                    let month = date.getMonth() + 1
                    let start = curPd.semesters.find(item => {
                        return item.start == 1
                    })
                    // 根据入学月份确定当前年级和学级的关系
                    if (start && month < start.month) {
                        curYear--
                    }
                    curPd.grades.forEach((item, index) => {
                        let dataItem = {
                            id: index,  //年级使用index
                            name: `${item}(${curYear - index}级)`,
                            year: curYear - index,
                            children: []
                        }
                        let child = this.schoolClasses.filter(classItem => {
                            return (classItem.year == curYear - index) && classItem.periodId == this.evaluationInfo.period.id
                        })
                        dataItem.children = child
                        data.push(dataItem)
                    })
                }
            }
            return data
        },
        //计算当前学段下面的年级信息
        curGrades() {
            if (this.evaluationInfo.period) {
                let res = this.schoolBase.period.filter((item) => {
                    return item.id == this.evaluationInfo.period.id
                })
                if (res.length > 0) {
                    return res[0].grades
                } else {
                    return []
                }
            } else {
                return []
            }
        },
        //计算当前学段下面的学科信息
        curSubjects() {
            if (this.evaluationInfo.period) {
                let res = this.schoolBase.period.filter((item) => {
                    return item.id == this.evaluationInfo.period.id
                })
                if (res.length > 0) {
                    return res[0].subjects
                } else {
                    return []
                }
            } else {
                return []
            }
        },
        //学校定义的考试类型
        testType() {
            let curPeriod = this.schoolBase.period.filter(item => {
                return item.id == this.evaluationInfo.period.id
            })
            if (curPeriod.length > 0) {
                return curPeriod[0].analysis.type
            } else {
                return []
            }
        }
    }
}
</script>
<style scoped lang="less">
@import "./CreateSchoolEva.less";
</style>
<style scoped>
.evaluation-attr-wrap .ivu-form .ivu-form-item-label {
    color: #a5a5a5;
}

.evaluation-question-main
    .ivu-tabs.ivu-tabs-card
    /deep/
    .ivu-tabs-bar
    .ivu-tabs-tab-active {
    background-color: #404040;
    font-weight: 600;
}

.evaluation-question-main .ivu-tabs .ivu-tabs-content-animated {
    height: 100%;
    margin-bottom: 10px;
}

.evaluation-question-main .ivu-tabs-bar {
    margin-bottom: 0px;
}
</style> 