<template>
    <div class="create-priv-container">
        <div class="create-header">
            <p class="create-header-title" @click="consData">{{$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.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.courseType')" prop="course">
                                <Select v-model="evaluationInfo.scope" @on-change="resetCourse">
                                    <Option value="school">{{$t('learnActivity.createEv.cusLabel1')}}</Option>
                                    <Option value="private">{{$t('learnActivity.createEv.cusLabel2')}}</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" @visible-change="visibleChange" :props="props" @change="treeChange" style="width:100%;" :options="curCusList">
                                </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="evaluation-question-main">
                    <Tabs v-model="activeTab" type="card" class="question-main-tabs" name="createTest">
                        <TabPane :label="$t('learnActivity.createEv.papersLabel')" name="manualPaper" v-if="createType == 'manualPaper'" :index="1" tab="createTest">
                            <ManualPaper @selectPaper="selectPaper" :selectedId="evaluationInfo.paperInfo[0] ? evaluationInfo.paperInfo[0].id : ''"></ManualPaper>
                        </TabPane>
                        <TabPane :label="$t('learnActivity.createEv.perviewLabel')" name="preview" :index="2" tab="createTest">
                            <TeacherPreview :testPaper="evaluationInfo.paperInfo[0]"></TeacherPreview>
                        </TabPane>
                        <TabPane :label="$t('learnActivity.createEv.answerPreview')" name="student" :index="6" tab="createTest">
                            <StudentPreview></StudentPreview>
                        </TabPane>
                    </Tabs>
                </div>
            </div>
        </div>

    </div>
</template>
<script>
import BlobTool from '@/utils/blobTool.js'
import ManualPaper from './ManualPaper.vue'
import TeacherPreview from './TeacherPreview.vue'
import StudentPreview from './StudentPreview.vue'

export default {
    components: {
        TeacherPreview,
        StudentPreview,
        ManualPaper
    },
    data() {
        const _this = this
        return {
            isEdit: false,
            props: {
                multiple: true,
                lazy: true,
                lazyLoad(node, resolve) {
                    const { level } = node
                    let scope = _this.evaluationInfo.scope
                    // 一级菜单首次加载
                    if (level == 0 && _this.courseList.length == 0) {
                        let requestData = {
                            'code': _this.$store.state.userInfo.TEAMModelId,
                            'schoolId': _this.$store.state.userInfo.schoolCode,
                            'scope': 'private'
                        }
                        _this.$api.courseMgmt.findCourse(requestData).then(
                            (res) => {
                                if (res.error) {
                                    _this.$Message.error('API ERROR!')
                                    return
                                }
                                _this.courseList = res.courses
                                let scope = _this.evaluationInfo.scope
                                let curCus = _this.courseList.filter(item => {
                                    return item.scope == scope
                                })
                                let nodes = curCus.map(item => {
                                    return {
                                        value: item.id,
                                        label: item.name,
                                        leaf: level >= 1
                                    }
                                })
                                resolve(nodes)
                            },
                            (err) => {
                                _this.$Message.error('API ERROR!')
                            }
                        )
                    }
                    // 一级菜单非首次加载
                    else if (level == 0 && _this.courseList.length > 0) {
                        let curCus = _this.courseList.filter(item => {
                            return item.scope == scope
                        })
                        let nodes = curCus.map(item => {
                            return {
                                value: item.id,
                                label: item.name,
                                leaf: true
                            }
                        })
                        resolve(nodes)
                    }
                    // 加载二级菜单
                    else if (level == 1) {
                        console.log(node)
                        let course = node.data
                        let requestData = {
                            'code': scope == 'school' ? _this.$store.state.userInfo.schoolCode : _this.$store.state.userInfo.TEAMModelId,
                            'scope': scope,
                            'id': course.value
                        }
                        _this.$api.courseMgmt.findCusInfo(requestData).then(
                            async (res) => {
                                if (res.error) {
                                    resolve([])
                                    return
                                }
                                // 获取自定义名单信息
                                let ids = res.courses[0].schedule.map(item => {
                                    return item.stulist
                                })
                                for (let i = 0; i < ids.length; i++) {
                                    if (!ids[i]) {
                                        ids.splice(i, 1)
                                        i--
                                    }
                                }
                                if (ids.length) {
                                    try {
                                        let listRes = await _this.getListInfo([...ids])
                                        if (listRes) _this.stuList.push(...listRes.stuList)
                                    } catch (e) {
                                        _this.$Message.error('API error')
                                    }
                                }

                                if (res.courses && res.courses.length > 0) {
                                    res.courses[0].schedule = res.courses[0].schedule ? res.courses[0].schedule : []
                                    res.courses[0].schedule.forEach(item => {
                                        // 补充教室信息
                                        if (item.classId) {
                                            let classInfo = _this.schoolClassList.find(classItem => {
                                                return classItem.id == item.classId
                                            })
                                            item.classInfo = {
                                                id: item.classId,
                                                name: classInfo ? `${classInfo.name}` : ' - -'
                                            }
                                        }
                                        // 补充名单信息
                                        if (item.stulist) {
                                            let listInfo = _this.stuList.find(listItem => {
                                                return listItem.id == item.stulist
                                            })
                                            item.listName = listInfo ? `${listInfo.name}` : ' - -'
                                        }
                                    })
                                }
                                let schedule = res.courses[0].schedule.filter(item => {
                                    return item.teacherId == _this.$store.state.userInfo.TEAMModelId && (item.stulist || item.classId)
                                })
                                let nodes = schedule.map(item => {
                                    return {
                                        value: item.stulist || item.classId,
                                        label: item.listName || item.classInfo.name,
                                        leaf: level >= 1
                                    }
                                })
                                resolve(nodes)
                            }
                        )
                    } else {
                        resolve([])
                    }
                }
            },
            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
                }
            },
            courseList: [],
            schoolTree: [],
            privateTree: [],
            schoolClassList: [],
            createType: 'manualPaper',
            startTime: '',
            endTime: '',
            isLoading: false,
            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' }
                ],
                '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' }
                ],
                classes: [
                    { 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',
            evaluationInfo: {
                name: '',
                targets: [],
                classes: [],
                scope: 'school',
                type: '',  //测试类别
                source: '',
                publish: '0',
                examType: {}, //测试类型
                startTime: undefined,
                endTime: undefined,
                paperInfo: [],
                papers: []
            },
            mode: '',
            selectBefore: [],
            stuList: []
        }
    },
    methods: {
        publishChange(data) {
            if (data == 0) {
                this.startTime = new Date()
                this.evaluationInfo.startTime = Date.now()
            }
        },
        //根据id获取stulist信息
        getListInfo(ids) {
            let requestData = {
                'code': this.evaluationInfo.scope == 'school' ? this.$store.state.userInfo.schoolCode : this.$store.state.userInfo.TEAMModelId,
                'scope': this.evaluationInfo.scope,
                'ids': ids
            }
            return this.$api.courseMgmt.findListSummary(requestData)
        },
        //重置课程类型
        resetCourse() {
            this.evaluationInfo.targets = []
            this.evaluationInfo.classes = []
        },
        //新结构 校本和个人课程一个API返回
        getCourseList() {
            let requestData = {
                'code': this.$store.state.userInfo.TEAMModelId,
                'schoolId': this.$store.state.userInfo.schoolCode,
                'scope': 'private'
            }
            this.$api.courseMgmt.findCourse(requestData).then(
                (res) => {
                    if (res.error == null) {
                        this.courseList = res.courses
                    } else {
                        this.$Message.error('API ERROR!')
                    }
                },
                (err) => {
                    this.$Message.error('API ERROR!')
                }
            )
        },
        //获取课程完整信息
        getCusInfo(id) {
            if (this.courseListShow[this.curCusIndex]) {
                let requestData = {
                    'code': this.$store.state.userInfo.schoolCode,
                    'scope': 'school',
                    'id': id
                }
                this.$api.courseMgmt.findCusInfo(requestData).then(
                    (res) => {
                        if (!res.error) {
                            if (res.courses && res.courses.length > 0) {
                                res.courses[0].schedule = res.courses[0].schedule ? res.courses[0].schedule : []
                                res.courses[0].schedule.forEach(item => {
                                    if (item.classId) {
                                        let classInfo = this.classList.find(classItem => {
                                            return classItem.id == item.classId
                                        })
                                        if (classInfo) {
                                            item.classInfo = {
                                                id: item.classId,
                                                name: classInfo.name
                                            }
                                        } else {
                                            item.classInfo = {
                                                id: item.classId,
                                                name: '--'
                                            }
                                        }
                                    }
                                    if (item.stulist) {
                                        let listInfo = this.stuList.find(listItem => {
                                            return listItem.id == item.stulist
                                        })
                                        if (listInfo) {
                                            item.listName = listInfo.name
                                        } else {
                                            item.listName = '--'
                                        }
                                    }

                                })
                            }
                            this.$set(this.courseListShow, this.curCusIndex, res.courses[0])
                            this.selectTea(0)
                        }
                    }
                ).finally(() => {
                    setTimeout(() => {
                        this.tableLoading = false
                    }, 500)
                })
            }
        },
        //获取个人课程列表 （废弃）
        getPrivateCus() {
            let requestData = {
                id: this.$store.state.userInfo.TEAMModelId
            }
            this.$api.courseMgmt.getPrivateCusMgt(requestData).then(
                (res) => {
                    if (!res.error) {
                        let resData = res.courses
                        resData.forEach(curItem => {
                            let treeItem = {
                                label: curItem.name,
                                value: curItem.id,
                                children: []
                            }
                            curItem.classes.forEach(claItem => {
                                treeItem.children.push({
                                    label: claItem.name,
                                    value: claItem.id
                                })
                            })
                            this.privateTree.push(treeItem)
                        })
                        console.log('privateTree', this.privateTree)
                        //编辑评测需要回显已选对象
                        if (this.isEdit) {

                        }
                    } else {
                        this.$Message.error('API error!')
                    }
                },
                (err) => {
                    this.$Message.error('API error!')
                }
            )
        },
        //获取标准课程列表 （废弃）
        getSchoolCourse() {
            let requestData = {
                'code': this.$store.state.userInfo.schoolCode,
                'id': this.$store.state.userInfo.TEAMModelId
            }
            this.$api.courseMgmt.getSchoolCusMgt(requestData).then(
                (res) => {
                    if (!res.error) {
                        res.courses.forEach((item, index) => {
                            let c = this.schoolClassList.find((classItem) => {
                                return item.id == classItem.id
                            })
                            if (c) {
                                item.no = c.no
                                item.openType = c.openType
                            }
                        })
                        let courseListS = this.$jsFn.groupBy(res.courses, 'courseId')
                        courseListS.forEach(item => {
                            let treeItem = {
                                label: item[0].courseName,
                                value: item[0].courseId,
                                children: []
                            }
                            item.forEach(classItem => {
                                treeItem.children.push({
                                    label: classItem.name,
                                    value: classItem.id
                                })
                            })
                            this.schoolTree.push(treeItem)
                        })
                        console.log('schoolTree', this.schoolTree)
                        //编辑评测需要回显已选对象
                        if (this.isEdit) {
                            this.$set(this.evaluationInfo, 'targets', [])
                            let defCus = this.schoolTree.find(item => {
                                if (this.evaluationInfo.subjects.length) {
                                    return item.value == this.evaluationInfo.subjects[0].id
                                }
                            })
                            if (defCus) {
                                defCus.children.forEach(item => {
                                    if (this.evaluationInfo.classes.indexOf(item.value) > -1) {
                                        let arr = [defCus.value, item.value]
                                        this.evaluationInfo.targets.push(arr)
                                    }
                                })
                                this.selectBefore = this._.cloneDeep(this.evaluationInfo.targets)
                            }
                        }
                    } else {
                        this.$Message.error('API ERROR!')
                    }
                },
                (err) => {
                    this.$Message.error('API ERROR!')
                }
            )
        },
        //设置考试类型名称
        setExamTypeName(data) {
            this.evaluationInfo.examType.name = data.label
        },
        visibleChange(status) {
            if (status) {
                this.selectBefore = this._.cloneDeep(this.evaluationInfo.targets)
            }
        },
        treeChange(data) {
            //实现一级（课程）单选效果
            if (this.selectBefore.length) {
                let curCus = new Set()
                data.forEach(item => {
                    curCus.add(item[0])
                })
                if (curCus.size > 1) {
                    let originCus = this.selectBefore[0][0]
                    let newData = data.filter(item => {
                        return item[0] != originCus
                    })
                    this.selectBefore = newData
                    this.evaluationInfo.targets = newData
                }
            } else {
                this.selectBefore = data
            }

            //获取施测对象id 
            this.evaluationInfo.classes = []
            this.evaluationInfo.classes = this.evaluationInfo.targets.map(item => {
                return item[1]
            })
            //设置评测“学科”
            this.evaluationInfo.subjects = []
            if (this.evaluationInfo.targets.length) {
                if (this.evaluationInfo.scope == 'school') {
                    let cus = this.courseList.find(item => {
                        return item.id == data[0][0]
                    })
                    if (cus) {
                        this.evaluationInfo.subjects = [cus.subject]
                    } else {
                        this.evaluationInfo.subjects = []
                    }
                    console.log('subject', cus)
                } else {
                    let cus = this.courseList.find(item => {
                        return item.id == data[0][0]
                    })
                    if (cus) {
                        this.evaluationInfo.subjects = []
                        this.evaluationInfo.subjects.push({
                            id: cus.id,
                            name: cus.name
                        })
                    } else {
                        this.evaluationInfo.subjects = []
                    }
                }
            }
        },
        /*
         * 返回上一级
         */
        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) {
            this.evaluationInfo.paperInfo[0] = fullPaper
            this.evaluationInfo.papers[0] = simplePaper
            this.goToPreview()
        },

        /**
         * 将日期控件时间格式转成时间戳
         * @param value
         * @param date
         */
        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'
        },
        inDevelopment() {
            this.$Message.info(this.$t('learnActivity.createEv.inDev'))
        },
        setActiveTab(data) {
            this.activeTab = data
        },
        consData() {
            console.log('evaluationInfo', this.evaluationInfo)
        },
        async saveEvaluation() {
            //表单验证
            let flag = true
            this.$refs['evaForm'].validate((valid) => {
                if (!valid) {
                    this.$Message.warning(this.$t('learnActivity.createEv.formWarning'))
                    flag = false
                }
            })
            if (!flag) {
                return
            }
            //检查试卷是否添加
            if (this.evaluationInfo.papers.length < 1) {
                this.$Message.warning({
                    content: this.$t('learnActivity.createEv.paperWarning'),
                    duration: 2
                })
                flag = false
            }
            if (!flag) {
                return
            }
            //通过验证，保存评测
            this.isLoading = true
            let requestData = {
                pk: 'Exam',
                id: this.evaluationInfo.id || null,
                code: this.$store.state.userInfo.TEAMModelId,
                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.evaluationInfo.scope,
                createDate: Math.round(new Date()),
                // blobcntr: this.evaluationInfo.scope == 'school' ? this.$store.state.userInfo.schoolCode : this.$store.state.userInfo.TEAMModelId //后面新增字段 (废弃)
                owner: 'teacher' //后面新增字段
            }

            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 = {}
                        if (this.$store.state.userInfo.hasSchool) {
                            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 targetBlob = undefined
                        if (this.evaluationInfo.scope == 'school') {
                            targetBlob = new BlobTool(schoolSas.url, schoolSas.name, schoolSas.sas, 'school')
                        } else {
                            targetBlob = new BlobTool(privateSas.url, privateSas.name, privateSas.sas, 'private')
                        }
                        let privateBlob = new BlobTool(privateSas.url, privateSas.name, privateSas.sas, 'private')
                        let schoolBlob = 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
                                        })
                                    }, 1000)
                                }
                                return
                            }
                            // 挑选的是校本试卷
                            if (item.scope == 'school') {
                                if (!schoolBlob) schoolBlob = new BlobTool(schoolSas.url, schoolSas.name, schoolSas.sas, 'school')
                                targetBlob.copyFolder(targetFolder + this.evaluationInfo.subjects[index].id + '/', item.blob.substring(1), schoolBlob).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
                                                })
                                            }, 1000)
                                        }
                                    }
                                )
                            }
                            //挑选的是个人试卷
                            else if (item.scope == 'private') {
                                if (!privateBlob) privateBlob = new BlobTool(privateSas.url, privateSas.name, privateSas.sas, 'private')
                                targetBlob.copyFolder(targetFolder + this.evaluationInfo.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
                                                })
                                            }, 1000)
                                        }
                                    }
                                )
                            }
                        })

                    } 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++) {
                    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.schoolClassList = res.school_classes
            }
        )
        //判断创建个人还是校本评测
        if (this.$route.name == 'createSchoolEva') {
            this.mode = 'school'
        } else {
            this.mode = 'private'
        }

        //编辑评测逻辑
        let routerData = this.$route.params.evaluationInfo
        if (routerData !== undefined) {
            this.isEdit = true
            this.startTime = new Date(routerData.startTime)
            this.endTime = new Date(routerData.endTime)
            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].subjectId = routerData.subjects[i].id
                routerData.paperInfo[i].subjectName = routerData.subjects[i].name
            }
            this.evaluationInfo = routerData
            this.activeTab = 'preview'
        }

        // this.getSchoolCourse()
        // this.getPrivateCus()
        this.getCourseList()

    },
    computed: {
        curCusList() {
            let cus = this.courseList.filter(item => {
                return item.scope == this.evaluationInfo.scope
            })
            let nodes = cus.map(item => {
                return {
                    value: item.id,
                    label: item.name,
                    leaf: false
                }
            })
            return nodes
        },
        //评测学科信息 校本课程为课程关联的学科 个人课程就为课程名单
        subjectInfo() {
            if (this.evaluationInfo.scope == 'school') {
                // let cur = this.
            }
        }
    }
}
</script>
<style scoped lang="less">
@import "./CreatePrivEva.less";
</style>
<style>
.evaluation-attr-wrap .ivu-form .ivu-form-item-label {
    color: #a5a5a5;
}

.evaluation-question-main .ivu-tabs-tab-active {
    background-color: #404040 !important;
    font-weight: 600;
}

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

.evaluation-question-main .ivu-tabs-bar {
    border-color: #404040;
    margin-bottom: 0px;
    border-bottom: none;
}
.evaluation-question-main .ivu-tabs.ivu-tabs-card .ivu-tabs-bar .ivu-tabs-tab {
    border: none;
    background-color: #303030;
    color: white;
    margin-right: 2px;
}
</style> 