<template>
  <div>
    <!--<div class="back_box">-->
    <!--<el-button type="text" @click="goBack">返回</el-button>-->
    <!--</div>-->
    <div class="title_content">{{ $store.state.user.companyName + '教学管理' }}</div>
    <div style="width: 90%;margin: 0 auto;overflow: hidden;">
      <el-menu
        :default-active="defaultActive"
        style="width: 200px;float: left;"
        active-text-color="#00BFFF"
        @open="handleOpen"
        @close="handleClose"
      >
        <el-menu-item index="1" @click="clickMenu">
          <img :src="classIcon" style="width: 18px;height: 18px;margin-right: 8px;">
          <span style="font-size: 18px;">班级管理</span>
        </el-menu-item>
        <el-submenu index="2">
          <template slot="title">
            <img :src="lessonIcon" style="width: 18px;height: 18px;margin-right: 8px;">
            <span style="font-size: 18px;">课程管理</span>
          </template>
          <el-menu-item-group>
            <el-menu-item index="2-1" style="font-size: 16px;" @click="clickMenu">发布课程管理</el-menu-item>
            <el-menu-item index="2-2" style="font-size: 16px;" @click="clickMenu">草稿课程管理</el-menu-item>
          </el-menu-item-group>
        </el-submenu>
        <el-menu-item index="3" @click="clickMenu">
          <img :src="examIcon" style="width: 18px;height: 18px;margin-right: 8px;">
          <span slot="title" style="font-size: 18px;">考试管理</span>
        </el-menu-item>
        <el-menu-item index="4" @click="clickMenu">
          <img :src="ruleIcon" style="width: 18px;height: 18px;margin-right: 8px;">
          <span slot="title" style="font-size: 18px;">评价管理</span>
        </el-menu-item>
      </el-menu>
      <div style="width: calc(100% - 200px);margin-left: 200px;">
        <div v-show="defaultActive === '1'" v-loading="loadingStudentInfo">
          <QueryListPage
            ref="classQueryListPage"
            :query-form="classQueryForm"
            :pager-config="pagerConfig"
            :query-list="classQueryList"
            style="width:90%;margin: 0 auto;"
          />
        </div>
        <div v-show="defaultActive === '2-1'">
          <QueryListPage
            ref="lessonQueryListPage"
            :query-form="lessonQueryForm"
            :pager-config="pagerConfig"
            :query-list="lessonQueryList"
            style="width:90%;margin: 0 auto;"
          />
        </div>
        <div v-show="defaultActive === '2-2'">
          <QueryListPage
            ref="draftLessonQueryListPage"
            :query-form="draftLessonQueryForm"
            :pager-config="pagerConfig"
            :query-list="draftLessonQueryList"
            style="width:90%;margin: 0 auto;"
          />
        </div>
        <div v-show="defaultActive === '3'">
          <QueryListPage
            ref="examQueryListPage"
            :query-form="examQueryForm"
            :pager-config="pagerConfig"
            :query-list="examQueryList"
            style="width:90%;margin: 0 auto;"
          />
        </div>
        <div v-show="defaultActive === '4'">
          <div style="display: flex; justify-content: space-between;width: 80%;margin: 0 auto;">
            <el-form :inline="true" :model="ruleFormModel" size="small">
              <el-form-item label="学年：">
                <el-select v-model="ruleFormModel.academicYear" placeholder="请选择" :clearable="true">
                  <el-option
                    v-for="item in academicYearList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="学期：">
                <el-select v-model="ruleFormModel.semester" placeholder="请选择" :clearable="true">
                  <el-option
                    v-for="item in semesterList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button @click="ruleQuery">规则查询</el-button>
              </el-form-item>
            </el-form>
            <el-button type="primary" size="small" style="width: 100px;height: 32px;" @click="ruleCreate">新建评价规则</el-button>
          </div>
          <el-table :data="ruleData" border style="width: 80%;margin: 0 auto;">
            <el-table-column type="index" width="50" />
            <el-table-column prop="content" label="规则内容" />
            <el-table-column prop="createDate" label="创建日期" />
            <el-table-column prop="className" label="适用班级" />
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="text" size="small">删除</el-button>
                <el-button type="text" size="small">修改</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <create-by-published ref="createByPublished" @refresh="draftLessonRefresh" />
    <edit-lesson-info ref="editLessonInfo" @refresh="lessonRefresh" />
    <publish-lesson ref="publishLesson" @refresh="draftLessonRefresh" />
    <create-class ref="createClass" @refresh="classRefresh" />
    <bind-lessons ref="bindLessons" />
  </div>
</template>

<script>
import ClassIcon from '@/assets/teachManage/class.png';
import LessonIcon from '@/assets/teachManage/lesson.png';
import ExamIcon from '@/assets/teachManage/exam.png';
import RuleIcon from '@/assets/teachManage/rule.png';
import ConstConfig from '@/scripts/ConstConfig';
import { getLessonDraftListSelf } from '@/api/jmap/lessondraft';
import { getLessonListSelf, forceDeleteLesson, getLessonListsSelfNoPage } from '@/api/jmap/lesson';
import { getClassListPageSelf, importCompanyMember, deleteDeptInfo, getClassListUnPageSelf } from '@/api/company';
import { getExamListSelf, deleteExam } from '@/api/management/exam';
import CreateByPublished from './createByPublished';
import EditLessonInfo from './editLessonInfo';
import { getPublishMapListOnline, getPublishMapInfo } from '@/api/jmap/map';
import { delLesson } from '@/api/jmap/lessondraft';
import PublishLesson from './publishLesson';
import CreateClass from './createClass';
import BindLessons from './bindLessons';
import { getSessionStorage, setSessionStorage } from '@/utils/auth';
import { convertSheetToList } from '@/utils/runPlan';

export default {
    name: 'Organization',
    components: {
        CreateByPublished,
        EditLessonInfo,
        PublishLesson,
        CreateClass,
        BindLessons
    },
    data() {
        return {
            classIcon: ClassIcon,
            lessonIcon: LessonIcon,
            examIcon: ExamIcon,
            ruleIcon: RuleIcon,
            loadingStudentInfo: false,
            defaultActive: '1',
            examData: [{ name: '测试课程', className: '测试班级', createDate: '2021.03.11' }],
            ruleData: [{ content: '平时考勤30%，考试成绩70%', createDate: '2021.03.11', className: '测试班级' }],
            academicYearList: [],
            semesterList: [{ label: '上学期', value: 'top' }, { label: '下学期', value: 'down' }],
            mapIdList: [],
            lessonList: [],
            classList: [],
            lineCode: '',
            classFormModel: {
                className: ''
            },
            lessonFormModel: {
                academicYear: '',
                semester: ''
            },
            examFormModel: {
                academicYear: '',
                semester: ''
            },
            ruleFormModel: {
                academicYear: '',
                semester: ''
            },
            pagerConfig: {
                pageSize: 'pageSize',
                pageIndex: 'pageNum'
            },
            classQueryForm: {
                leftSpan: 14,
                labelWidth: '90px',
                textAlign: 'right',
                reset: true,
                queryObject: {
                    name: {
                        type: 'text',
                        label: '班级名称:'
                    }
                }
            },
            classQueryList: {
                query: getClassListPageSelf,
                selectCheckShow: false,
                indexShow: true,
                columns: [
                    {
                        title: '班级名称:',
                        prop: 'name',
                        width: '200'
                    },
                    {
                        title: '人数',
                        prop: 'numberOfPeople'
                    },
                    {
                        title: '创建日期',
                        prop: 'createTime'
                    },
                    {
                        type: 'button',
                        title: this.$t('global.operate'),
                        width: '550',
                        buttons: [
                            {
                                name: '编辑班级',
                                handleClick: this.handleUpdateClass,
                                type: 'primary'
                            },
                            {
                                name: '导入学生',
                                handleClick: this.importResults,
                                type: 'file'
                            },
                            {
                                name: '查看名册',
                                handleClick: this.handleStudentDetail,
                                type: 'primary'
                            },
                            {
                                name: '评价查询',
                                handleClick: this.handleGradeCheck,
                                type: 'primary'
                            },
                            {
                                name: '排课',
                                handleClick: this.handleBindLesson,
                                type: 'primary'
                            },
                            {
                                name: '删除',
                                handleClick: this.handleDeleteClass,
                                type: 'danger'
                            }
                        ]
                    }
                ],
                actions: [
                    { text: '新建班级', handler: this.classCreate },
                    { text: '导入模板下载', handler: this.exportTemplate },
                    { text: '返回', handler: this.goBack }
                ]
            },
            lessonQueryForm: {
                leftSpan: 16,
                labelWidth: '90px',
                textAlign: 'right',
                reset: true,
                queryObject: {
                    name: {
                        type: 'text',
                        label: '课程名称:'
                    }
                }
            },
            lessonQueryList: {
                query: getLessonListSelf,
                selectCheckShow: false,
                indexShow: true,
                columns: [
                    {
                        title: this.$t('lesson.courseName'),
                        prop: 'name',
                        width: '200'
                    },
                    {
                        title: '课程地图',
                        prop: 'mapId',
                        type: 'tag',
                        width: '250',
                        columnValue: (row) => {
                            return this.$convertField(row.mapId, this.mapIdList, ['id', 'name']);
                        },
                        tagType: (row) => { return 'success'; }
                    },
                    {
                        title: this.$t('lesson.courseDescription'),
                        prop: 'remarks'
                    },
                    {
                        type: 'button',
                        title: this.$t('global.operate'),
                        width: '200',
                        buttons: [
                            {
                                name: '修改课程',
                                handleClick: this.handleEditLessonInfo,
                                type: 'primary'
                            },
                            {
                                name: '删除',
                                handleClick: this.handleDeleteLesson,
                                type: 'danger'
                            }
                        ]
                    }
                ],
                actions: [
                    { text: '返回', handler: this.goBack }
                ]
            },
            draftLessonQueryForm: {
                leftSpan: 14,
                textAlign: 'right',
                labelWidth: '90px',
                reset: true,
                queryObject: {
                    name: {
                        type: 'text',
                        label: '课程名称:'
                    }
                }
            },
            draftLessonQueryList: {
                query: getLessonDraftListSelf,
                selectCheckShow: false,
                indexShow: true,
                columns: [
                    {
                        title: this.$t('lesson.courseName'),
                        prop: 'name'
                    },
                    {
                        title: this.$t('lesson.courseDescription'),
                        prop: 'remarks'
                    },
                    {
                        title: this.$t('global.status'),
                        prop: 'status',
                        type: 'tag',
                        columnValue: (row) => {
                            return this.$convertField(row.status, ConstConfig.ConstSelect.releaseReview, ['value', 'label']);
                        },
                        tagType: (row) => { return 'success'; }
                    },
                    {
                        type: 'button',
                        title: this.$t('global.operate'),
                        width: '400',
                        buttons: [
                            {
                                name: this.$t('lesson.courseDetails'),
                                handleClick: this.goLessonDetail,
                                type: 'primary',
                                showControl: (row) => {
                                    return row.status !== '1';
                                }
                            },
                            {
                                name: this.$t('lesson.contentSorting'),
                                handleClick: this.treeSortLesson,
                                type: 'primary',
                                showControl: (row) => {
                                    return row.status !== '1';
                                }
                            },
                            {
                                name: this.$t('global.release'),
                                handleClick: this.publishLesson,
                                type: 'primary',
                                showControl: (row) => {
                                    return row.status === '0';
                                }
                            },
                            {
                                name: this.$t('global.delete'),
                                handleClick: this.deleteLesson,
                                type: 'danger'
                            }
                        ]
                    }
                ],
                actions: [
                    { text: '从发布课程新建', handler: this.lessonCreateByOld },
                    { text: '新建课程', handler: this.lessonCreate },
                    { text: '返回', handler: this.goBack }
                ]
            },
            examQueryForm: {
                leftSpan: 14,
                textAlign: 'right',
                labelWidth: '90px',
                reset: true,
                queryObject: {
                    name: {
                        type: 'text',
                        label: '试卷名称:'
                    },
                    clsId: {
                        type: 'select',
                        label: '班级:',
                        config: {
                            data: []
                        }
                    }
                }
            },
            examQueryList: {
                query: getExamListSelf,
                selectCheckShow: false,
                indexShow: true,
                columns: [
                    {
                        title: '试卷名称',
                        prop: 'name'
                    },
                    {
                        title: '课程名称',
                        prop: 'lessonId',
                        type: 'tag',
                        columnValue: (row) => {
                            return this.$convertField(row.lessonId, this.lessonList, ['id', 'name']);
                        },
                        tagType: (row) => { }
                    },
                    {
                        title: '班级',
                        prop: 'clsIds',
                        type: 'tagMore',
                        columnValue: (row) => { return this.$convertField(row.clsIds, this.classList, ['id', 'name'], true); },
                        tagType: (row) => { return 'success'; }
                    },
                    {
                        title: '满分',
                        prop: 'fullPoint'
                    },
                    {
                        title: '及格分',
                        prop: 'passingPoint'
                    },
                    {
                        title: '时长',
                        prop: 'duration',
                        type: 'tag',
                        columnValue: (row) => {
                            return Math.floor(row.duration / 60);
                        },
                        tagType: (row) => { }
                    },
                    {
                        type: 'button',
                        title: this.$t('global.operate'),
                        width: '200',
                        buttons: [
                            {
                                name: '成绩查询',
                                handleClick: this.handleQueryGrade,
                                type: 'primary',
                                showControl: (row) => {
                                    return row.clsIds && row.clsIds.length;
                                }
                            },
                            {
                                name: '删除',
                                handleClick: this.handleDeleteExam,
                                type: 'danger'
                            }
                        ]
                    }
                ],
                actions: [
                    { text: '新建试卷', handler: this.examCreate },
                    { text: '返回', handler: this.goBack }
                ]
            }
        };
    },
    computed: {

    },
    created() {
        const index = getSessionStorage('organizationIndex');
        if (index) { this.defaultActive = index; }
    },
    mounted() {
        this.academicYearList = [];
        const nowYear = new Date().getFullYear();
        for (let i = 2020; i < nowYear + 1; i++) {
            this.academicYearList.push({ label: `${i}-${i + 1}学年`, value: i });
        }
        this.mapIdList = [];
        getPublishMapListOnline().then(response => {
            this.mapIdList = response.data;
        });
        getLessonListsSelfNoPage().then(response => {
            this.lessonList = response.data;
        });
        getClassListUnPageSelf().then(response => {
            this.classList = response.data;
            this.classList.forEach(item => {
                this.examQueryForm.queryObject.clsId.config.data.push({ value: item.id, label: item.name });
            });
        });
    },
    methods:{
        handleOpen(val) {
        },
        handleClose(val) {
        },
        clickMenu(val) {
            setSessionStorage('organizationIndex', val.index);
            this.defaultActive = val.index;
            if (val.index === '2-1') {
                this.lessonRefresh();
            } else if (val.index === '2-2') {
                this.draftLessonRefresh();
            } else if (val.index === '1') {
                this.classRefresh();
            } else if (val.index === '3') {
                this.examRefresh();
            }
        },
        publishLesson(index, row) {
            this.$refs.publishLesson.doShow(row);
        },
        goBack() {
            this.$router.go(-1);
        },
        classQuery() {

        },
        classCreate() {
            this.$refs.createClass.doShow();
        },
        lessonCreate() {
            this.$router.push({ path: `/info/createLesson` });
        },
        lessonCreateByOld() {
            this.$refs.createByPublished.doShow();
        },
        examQuery() {

        },
        examCreate() {
            this.$router.push({ path: `/info/examRule/draft/add/0/0`, query: { source: 'org' } });
        },
        ruleQuery() {

        },
        ruleCreate() {

        },
        goLessonDetail(index, row) {
            getPublishMapInfo(row.mapId).then(resp => {
                this.lineCode = resp.data.lineCode;
                this.$router.push({ path: '/info/editLesson', query: { lessonId: row.id, mapId: row.mapId, prdType: row.prdType, lineCode: this.lineCode } });
            });
        },
        treeSortLesson(index, row) {
            this.$router.push({ path: '/info/sortLesson', query: { lessonId: row.id } });
        },
        deleteLesson(index, row) {
            this.$confirm('此操作将删除草稿课程，且无法恢复，是否继续？', this.$t('global.tips'), {
                confirmButtonText: this.$t('global.confirm'),
                cancelButtonText: this.$t('global.cancel'),
                type: 'warning'
            }).then(() => {
                delLesson(row).then(response => {
                    this.$message.success(this.$t('tip.successfullyDelete'));
                    this.draftLessonRefresh();
                }).catch(() => {
                    this.$messageBox(this.$t('tip.failDelete'));
                });
            }).catch(() => { });
        },
        handleDeleteLesson(index, row) {
            this.$confirm('此操作将删除课程及所有对应的试卷，且无法恢复，是否继续？', this.$t('global.tips'), {
                confirmButtonText: this.$t('global.confirm'),
                cancelButtonText: this.$t('global.cancel'),
                type: 'warning'
            }).then(() => {
                forceDeleteLesson(row.id).then(response => {
                    this.$message.success(this.$t('publish.deleteSuccess'));
                    this.lessonRefresh();
                }).catch((error) => {
                    this.$messageBox(this.$t('error.deleteFailed') + ':' + error.message);
                    this.lessonRefresh();
                });
            }).catch(() => { });
        },
        handleEditLessonInfo(index, row) {
            this.$refs.editLessonInfo.doShow(row);
        },
        handleGradeCheck() {

        },
        lessonRefresh() {
            this.$nextTick(() => {
                this.$refs.lessonQueryListPage.refresh(true);
            });
        },
        draftLessonRefresh() {
            this.$nextTick(() => {
                this.$refs.draftLessonQueryListPage.refresh(true);
            });
        },
        classRefresh() {
            this.$nextTick(() => {
                this.$refs.classQueryListPage.refresh(true);
            });
        },
        examRefresh() {
            this.$nextTick(() => {
                this.$refs.examQueryListPage.refresh(true);
            });
        },
        handleBindLesson(index, row) {
            this.$refs.bindLessons.doShow(row);
        },
        handleDeleteClass(index, row) {
            this.$confirm('此操作将班级，且无法恢复，是否继续？', this.$t('global.tips'), {
                confirmButtonText: this.$t('global.confirm'),
                cancelButtonText: this.$t('global.cancel'),
                type: 'warning'
            }).then(() => {
                deleteDeptInfo(row.id).then(response => {
                    this.$message.success('删除班级成功！');
                    this.classRefresh();
                }).catch(() => {
                    this.$messageBox('删除班级失败！');
                    this.classRefresh();
                });
            }).catch(() => { });
        },
        handleStudentDetail( index, row ) {
            this.$router.push({ path: '/info/studentDetail', query: { classId: row.id, className: row.name} });
        },
        handleUpdateClass(index, row) {
            this.$refs.createClass.doShow(row);
        },
        handleQueryGrade(index, row) {
            this.$router.push({ path: '/info/gradeList', query: { examId: row.id, clsIds: row.clsIds.join('-'), name: row.name } });
        },
        handleDeleteExam(index, data) {
            this.$confirm(this.$t('publish.wellDelPaper'), this.$t('global.tips'), {
                confirmButtonText: this.$t('global.confirm'),
                cancelButtonText: this.$t('global.cancel'),
                type: 'warning'
            }).then(() => {
                deleteExam(data).then(res => {
                    this.examRefresh();
                    this.$message({
                        type: 'success',
                        message: '删除试卷成功！'
                    });
                }).catch(res => {
                    if (res.code == '10004') {
                        this.$message({ type: 'error', message: '删除失败:试卷已被使用，无法删除!' });
                    } else if (res.code == '10003') {
                        this.$message({ type: 'warning', message: '删除失败:无权限删除!'});
                    } else {
                        this.$message({ type: 'error', message: this.$t('error.deleteException') });
                    }
                });
            }).catch(() => { });
        },
        exportTemplate() {
            const wb = XLSX.utils.book_new();
            const data1 = [{A: '学号', B:'姓名'}];
            const data2 = [{A: '00001', B:'张三'}];
            const data3 = [{A: '00002', B:'李四'}];
            const data = [...data1, ...data2, ...data3];
            const ws = XLSX.utils.json_to_sheet(data, {skipHeader:true});
            ws['!cols'] = [
                {width: 15},
                {width: 15},
                {width: 15}
            ];
            XLSX.utils.book_append_sheet(wb, ws, 'file');
            XLSX.writeFile(wb, '学生信息模板' + '.xlsx');
        },
        importResults(index, row) {
            const obj = document.getElementById(`queryListPageFilesInput${index}`);
            if (!obj || !obj.files) return;
            const f = obj.files[0];
            this.handleImportResults(f, row);
        },
        handleImportResults(file, row) {
            if (file) {
                setTimeout(() => {
                    const that = this;
                    const reader = new FileReader();
                    if (reader) {
                        reader.onload = function (e) {
                            let wb;
                            const data = e.target.result;
                            if (that.rABS) {
                                wb = XLSX.read(btoa(that.fixdata(data)), { // 手动转化
                                    type: 'base64'
                                });
                            } else {
                                wb = XLSX.read(data, {
                                    type: 'binary'
                                });
                            }
                            if (wb) {
                                try {
                                    const students = [];
                                    for (const index in wb.Sheets) {
                                        const dataList = convertSheetToList(wb.Sheets[index], true);
                                        if (dataList.length) {
                                            for ( let i = 1; i <= dataList[0].length; i++) {
                                                const studentId = dataList[0][i];
                                                const name = dataList[1][i];
                                                const reg = new RegExp('[\\u4E00-\\u9FFF]+', 'g');
                                                const studentIdJudge = !!studentId && !reg.test(studentId);
                                                if (studentIdJudge && name) {
                                                    students.push({account:dataList[0][i], name: dataList[1][i]});
                                                } else {
                                                    if (!studentId && !name) {
                                                        break;
                                                    } else if (!name) {
                                                        throw new Error(`学号为：《${studentId}》的数据学生姓名为空！`);
                                                    } else if (!studentIdJudge) {
                                                        throw new Error(`学号为：《${studentId}》的数据学号格式不正确！`);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    that.loadingStudentInfo = true;
                                    importCompanyMember(row.id, students).then(resp => {
                                        that.$message.success('学生信息导入成功！');
                                        that.loadingStudentInfo = false;
                                    }).catch((error) => {
                                        that.$message.error('学生信息导入失败:' + error.message);
                                        that.loadingStudentInfo = false;
                                    });
                                } catch (error) {
                                    that.$message.warning(`解析学生信息表失败:${error}`);
                                }
                            }
                        };
                        if (that.rABS) {
                            reader.readAsArrayBuffer(file);
                        } else {
                            reader.readAsBinaryString(file);
                        }
                    }
                }, 200);
            }
        }
    }
};
</script>

<style scoped>
	.back_box {
		height: 20px;
		z-index: 36;
		width: 40px;
		text-align: center;
		position: absolute;
		right: 20px;
		top: -20px;
	}
	.title_content {
		width: 100%;
		margin: 20px 0 30px;
		text-align: center;
		font-size: 28px;
		font-weight: bold;
	}
</style>
