<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="evaType">
                                <Select v-model="evaluationInfo.evaType">
                                    <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="teacher">{{$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" :options="evaluationInfo.scope == 'teacher' ? schoolTree : privateTree" :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>
                            </FormItem>
                            <FormItem :label="$t('learnActivity.createEv.startTime')" v-if="evaluationInfo.publish == 1" prop="startTime">
                                <DatePicker 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 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.importLabel')" name="import" v-if="createType == 'import'" :index="4" tab="createTest">
                            <ImportCreate></ImportCreate>
                        </TabPane>
                        <TabPane :label="$t('learnActivity.createEv.answerPreview')" name="student" :index="6" tab="createTest">
                            <StudentPreview></StudentPreview>
                        </TabPane>
                        <!-- 暂时注解，创建评测这里只能挑选试卷，如果没有试卷提示前往试卷库创建试卷 -->
                        <!-- <div slot="extra" class="create-type-wrap" v-show="activeTab == 'manualPaper' || activeTab == 'import'">
                            <RadioGroup v-model="createType" style="margin-left:25px;" @on-change="setActiveTab" size="small">
                                <Radio label="manualPaper">挑选试卷</Radio>
                                <Radio label="import">导入试卷</Radio>
                            </RadioGroup>
                        </div> -->
                    </Tabs>
                </div>
            </div>
        </div>

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

export default {
    components: {
        TeacherPreview,
        StudentPreview,
        ImportCreate,
        ManualPaper
    },
    data() {
        return {

            props: {
                multiple: true,
            },
            schoolBase: {
                period: []
            },
            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' }
                ],
                evaType: [
                    { 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' }
                ],
                targetClassIds: [
                    { 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: [],
                targetClassIds: [],
                scope: 'teacher',
                type: '',  //测试类别
                evaType: '',
                publish: '0',
                examType: {}, //测试类型
                startTime: undefined,
                endTime: undefined,
                paperInfo: [],
                papers: []
            },
            mode: '',
            selectBefore: []
        }
    },
    methods: {

        //重置课程类型
        resetCourse() {
            this.evaluationInfo.targets = []
            this.evaluationInfo.targetClassIds = []
        },
        //获取个人课程列表
        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)
                    } else {
                        this.$Message.error('API error!')
                    }
                },
                (err) => {
                    this.$Message.error('API error!')
                }
            )
        },
        //获取标准课程列表
        getCourseList() {
            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.no
                                })
                            })
                            this.schoolTree.push(treeItem)
                        })
                        console.log('schoolTree', this.schoolTree)
                    } 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)
                console.log('before', this.selectBefore)
            }
        },
        treeChange(data) {
            console.log('data', 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.targetClassIds = []
            this.evaluationInfo.targetClassIds = this.evaluationInfo.targets.map(item => {
                return item[1]
            })
            //设置测试“学科”
            this.evaluationInfo.subjects = []
            if (this.evaluationInfo.targets.length) {
                if (this.evaluationInfo.scope == 'teacher') {
                    let res = this.schoolTree.filter(item => {
                        return item.value == this.evaluationInfo.targets[0][0]
                    })
                    if (res.length) {
                        this.evaluationInfo.subjects.push({
                            id: res[0].value,
                            name: res[0].label
                        })
                    }
                } else {
                    let res = this.privateTree.filter(item => {
                        return item.value == this.evaluationInfo.targets[0][0]
                    })
                    if (res.length) {
                        this.evaluationInfo.subjects.push({
                            id: res[0].value,
                            name: res[0].label
                        })
                    }
                }
            }
        },
        /*
         * 返回上一级
         */
        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()
            } 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',
                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.evaType,
                targetClassIds: this.evaluationInfo.targetClassIds,
                publish: this.evaluationInfo.publish,
                startTime: this.evaluationInfo.publish == 0 ? Math.round(new Date()) : this.evaluationInfo.startTime,
                endTime: this.evaluationInfo.endTime,
                scope: this.evaluationInfo.scope,
                createDate: Math.round(new Date())
            }

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

                        //发布成功需要备份试卷数据
                        let examId = res.exam.id
                        let privateSas = this.$store.state.privateSas
                        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 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 => {
                            if (item.scope == 'school') {
                                if (!schoolBlob) schoolBlob = new BlobTool(schoolSas.url, schoolSas.name, schoolSas.sas, 'school')
                                privateBlob.copyFolder(targetFolder + item.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
                                                })
                                            }, 2000)
                                        }
                                    }
                                )
                            } else if (item.scope == 'private') {
                                if (!privateBlob) privateBlob = new BlobTool(privateSas.url, privateSas.name, privateSas.sas, 'private')
                                privateBlob.copyFolder(targetFolder + item.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 {
                        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++) {
                    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 = []
                    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)
                            paper.point.push(rule[i].slides[k].scoring.score)
                            paper.knowledge.push(rule[i].slides[k].scoring.knowledge ? rule[i].slides[k].scoring.knowledge : [])
                            if (rule[i].slides[k].scoring.field) paper.field.push(rule[i].slides[k].scoring.field)
                        }
                    }
                    paperDto.push(paper)
                }
                return paperDto
            } else {
                return []
            }
        }
    },
    created() {
        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'
        }
        this.getCourseList()
        this.getPrivateCus()

    },
    mounted() {
        this.startTime = new Date()
        this.evaluationInfo.startTime = new Date()
        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
    }
}
</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> 