<template>
    <div class="course-plan-container dark-iview-split">
        <div class="course-table-header">
            <BasePdSelect @pd-change="filterByPeriod"></BasePdSelect>
            <div class="action-btn-wrap">
                <span v-if="$access.can('admin.*|course-upd')" @click="showImportCus()" class="action-btn">
                    <Icon custom="iconfont icon-upload" size="16" />
                    <span>{{$t('cusMgt.importLabel')}}</span>
                </span>
                <span v-if="$access.can('admin.*|course-upd')" @click="toggleView()" class="action-btn" style="margin-right:40px">
                    <Icon custom="iconfont icon-kecheng" size="16" />
                    <span>{{$t('cusMgt.cusMode')}}</span>
                </span>
            </div>
        </div>
        <Split v-model="split1">
            <div class="class-list-wrap" slot="left">
                <div class="class-list-header">
                    <div v-if="!isSearch">
                        <span>教室</span>
                        <Icon type="md-search" class="action-btn-icon" @click="toggleSearch" />
                    </div>
                    <div v-else class="dark-iview-input">
                        <Input icon="ios-close" v-model="classFilter.keyWord" :placeholder="$t('cusMgt.searchHolder')" autofocus style="width:calc(100% - 100px);float:right;margin-top:6px;margin-right:8px" @on-click="toggleSearch" @on-change="onSearchClass" @on-enter="onSearchClass" />
                    </div>
                </div>
                <div class="class-list-content">
                    <vuescroll>
                        <Loading v-show="isListLoading" bgColor="rgba(103, 103, 103, 0.27)"></Loading>
                        <div class="class-list-item" v-for="(item,index) in roomListShow" :key="index" @click="selectClass(index)" :class="curClassIndex == index ? 'block-bg block-bg-active':'block-bg'">
                            <div class="class-list-item-left">
                                <p class="class-name">{{item.name}}</p>
                                <p class="head-teacher">
                                    <span>教室类型：</span>
                                    <span class="primary-text-color">{{item.style}}</span>
                                </p>
                            </div>
                        </div>
                        <EmptyData v-if="roomListShow.length == 0" style="padding-top:120px;"></EmptyData>
                    </vuescroll>
                </div>
            </div>
            <div class="cus-table-wrap" slot="right">
                <!-- <div class="cus-table-header common-save-btn">
                    <span>{{$t('cusMgt.cusTable')}}</span>
                    
                </div> -->
                <div class="cus-table-content dark-iview-table">
                    <vuescroll>
                        <!-- 班级课程表 -->
                        <ClassTable v-if="this.roomListShow[this.curClassIndex]" :schedData="roomCus" :roomId="roomListShow[curClassIndex].id" :periodId="pdId" @selectCell="selectCell" @cancelCell="cancelCell"></ClassTable>
                        <Loading v-if="isLoading" bgColor="rgba(103, 103, 103, 0.27)"></Loading>
                    </vuescroll>
                </div>
            </div>
        </Split>

        <!--导入课表功能尚未开发-->
        <Modal v-model="importCusStatus" title="导入课表" width="1000" class-name="dark-iview-modal" @on-ok="confImpStatus = true" @on-cancel="cancelImport">
            <ImportExcel ref="impXls" :headerKeys="headerKeys" :headerTitles="headerTitles" @getTableData="getTableData"></ImportExcel>
            <div class="error-tips-wrap">
                <span style="color:#ed4014;" v-if="errorCourse.length > 0">
                    <span>错误课程：</span><span>{{errorCourse.join(',')}}</span>
                </span>
                <span style="color:#ff9900" v-if="errorClass.length > 0">
                    <span>错误班级：</span><span>{{errorClass.join(',')}}</span>
                </span>
                <span style="color:#2db7f5" v-if="errorTeacher.length > 0">
                    <span>错误授课老师：</span><span>{{errorTeacher.join(',')}}</span>
                </span>
                <span style="color:#ed4014" v-if="moreClass">
                    <span>只能以班级为单位导入！</span>
                </span>
            </div>
        </Modal>
        <Modal v-model="confImpStatus" title="确认导入" class-name="dark-iview-modal dark-iview-form" @on-ok="importCus">
            <p style="color:white;font-size:16px;">批量导入课程将覆盖班级原来的课表，确认批量导入并且覆盖原来的课表？</p>
        </Modal>
    </div>
</template>
<script>
import ClassTable from "./ClassTable.vue"
export default {
    components: {
        ClassTable
    },
    inject: ['reload'],
    data() {
        return {
            split1: 0.2,
            pdId: '',
            confImpStatus: false,
            classFilter: {
                keyWord: ''
            },
            isSearch: false,
            isLoading: false,
            courseList: [],
            delCusInfo: {},
            errorClass: [],
            errorCourse: [],
            errorTeacher: [],
            excelData: [],
            headerKeys: ['classroomCode', 'courseName', 'courseCode', 'teacher', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN'],
            headerTitles: ['班级', '课程名称', '课程编码', '授课老师', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'],
            importCusStatus: false,
            moreClass: false,
            schoolInfo: {},
            subIndex: 0,
            isListLoading: false,
            roomList: [],
            roomListShow: [],
            curClassIndex: 0,
            tableData: [],
            importData: [],
            allClassCus: {}
        }
    },
    methods: {
        filterByPeriod(pd) {
            console.log(pd)
            this.pdId = pd
            this.curClassIndex = 0
            if (pd) {
                this.roomListShow = this.roomList.filter(item => item.periodId == pd || !item.periodId)
            } else {
                this.roomListShow = [...this.roomList]
            }
            // 排序
            this.roomListShow = this.dataSort(this.roomListShow)
        },
        dataSort(data) {
            switch (this.orderBy) {
                case 'id': // ID 排序
                    data.sort(function (a, b) {
                        let nameA = a.id.toUpperCase(); // ignore upper and lowercase
                        let nameB = b.id.toUpperCase(); // ignore upper and lowercase
                        if (nameA < nameB) {
                            return -1;
                        }
                        if (nameA > nameB) {
                            return 1;
                        }

                        // names must be equal
                        return 0;
                    })
                    break;
                case 'state': // 智慧教室排序
                    data.sort(function (a, b) {
                        if (a.style == 'smart') {
                            return 1
                        } else {
                            return -1
                        }
                    })
                    break; // 學生總數排序
                case 'total':
                    data.sort(function (a, b) {
                        return b.studCount - a.studCount;
                    })
                    break;
            }
            return data
        },
        // 切换课表模式和课程模式
        toggleView() {
            this.$router.push({
                name: 'NewCusMgt'
            })
        },
        //关键字搜索班级
        onSearchClass() {
            this.roomListShow = this.roomList.filter((item) => {
                return item.name.indexOf(this.classFilter.keyWord) !== -1
            })
        },
        /**切换搜索状态 */
        toggleSearch() {
            this.isSearch = !this.isSearch
        },
        //处理表格导入的数据
        getTableData(data) {
            this.excelData = data
            let keys = ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN']
            let groupData = this.$jsFn.groupBy(data, 'classroomCode')
            if (groupData.length > 1) {
                this.$Message.warning('只能以班级为单位导入！')
                this.moreClass = true
                this.excelData.length = 0
            } else {
                for (let itemData of data) {
                    //验证班级code
                    let classroom = this.roomList.filter((item) => {
                        return item.classroomCode == itemData.classroomCode
                    })
                    if (classroom.length == 0) {
                        this.errorClass.push(itemData.classroomCode)
                        continue
                    }
                    //验证教师id
                    let teacher = this.$store.state.teachers.teacherList.filter((item) => {
                        return item.id == itemData.teacher
                    })
                    if (teacher.length == 0) {
                        this.errorTeacher.push(itemData.teacher)
                        continue
                    }
                    //验证课程编码
                    let courseId = ''
                    let course = this.courseList.filter((item) => {
                        return item.courseCode == itemData.courseCode
                    })
                    if (course.length > 0) {
                        courseId = course[0].id
                    } else {
                        this.errorCourse.push(itemData.courseCode)
                        continue
                    }


                    for (let key of keys) {
                        if (itemData[key]) {
                            let indexes = itemData[key].toString().split(',')
                            for (let index of indexes) {
                                let reqItem = {
                                    classroomCode: itemData.classroomCode,
                                    courseId: courseId,
                                    code: teacher[0].id,
                                    courseTime: {}
                                }
                                reqItem.courseTime.label = this.tableData[parseInt(index) - 1].label
                                reqItem.courseTime.time = this.tableData[parseInt(index) - 1].time
                                reqItem.courseTime.day = key
                                this.importData.push(reqItem)
                            }
                        }
                    }
                }
                if (this.errorClass.length > 0 || this.errorCourse.length > 0 || this.errorTeacher.length > 0) {
                    this.$Message.error({
                        content: '错误数据不能导入，请检查数据是否正确',
                        duration: 5,
                    })
                } else {
                    this.$Message.info('文件读取成功')
                }
            }
        },
        //显示导入课程
        showImportCus() {
            // this.importCusStatus = true
            // this.moreClass = false
            this.$Message.warning('功能正在开发中')
        },
        //确认导入课程
        importCus() {
            this.$refs['impXls'].file = undefined
            this.errorClass.length = 0
            this.errorCourse.length = 0
            this.errorTeacher.length = 0
            this.isLoading = true
            if (this.importData.length > 0) {
                this.$api.courseMgmt.importAllPlan({
                    classroomCode: this.importData[0].classroomCode,
                    coursePlans: this.importData
                }).then(
                    (res) => {
                        if (res.error == null) {
                            this.$Message.success('导入成功！')
                            this.reload()
                        } else {
                            this.$Message.error('API ERROR！')
                        }
                        this.importData.length = 0
                        this.isLoading = false
                    },
                    (err) => {
                        this.$Message.error('API ERROR！')
                        this.isLoading = false
                        this.importData.length = 0
                    }
                )
            } else {
                this.$Message.warning('暂无需要导入的数据！')
            }
        },
        cancelImport() {
            this.$refs['impXls'].file = undefined
            this.errorClass.length = 0
            this.errorCourse.length = 0
            this.errorTeacher.length = 0
            this.importData.length = 0
        },
        selectClass(index) {
            this.curClassIndex = index
            let roomId = this.roomListShow[this.curClassIndex].id
            if (!this.allClassCus[roomId]) {
                this.isLoading = true
                this.findClassCus()
            }
        },

        //根据班级查询课程安排
        findClassCus() {
            if (this.roomListShow.length > 0) {
                let roomId = this.roomListShow[this.curClassIndex].id
                let requestData = {
                    id: roomId,
                    code: this.$store.state.userInfo.schoolCode,
                    scope: 'school'
                }
                this.$api.courseMgmt.findCusByRoom(requestData).then(
                    (res) => {
                        if (!res.error) {
                            this.$set(this.allClassCus, roomId, res.courses)
                            this.isLoading = false
                        } else {
                            this.$Message.error('API error!')
                            this.isLoading = false
                        }
                    },
                    (err) => {
                        this.isLoading = false
                    }
                )
            } else {
                this.isLoading = false
            }
        },
        //设置课程事件
        selectCell(data) {
            console.log('设置数据', data)
            //data里面包含当前课程完整信息
            let course = data.course
            course.schedule = course.schedule || []
            //先查看是否有还没有设置教室的对应安排
            let schedule = course.schedule.find(item => {
                // return item.room == this.roomListShow[this.curClassIndex].id && item.teacherId == data.teaId
                return !item.room && item.teacherId == data.teaId && item.classId == data.classId && item.stulist == data.stulist
            })
            //1、如果有还未设置教室的课程安排优先使用
            if (schedule) {
                schedule.room = this.roomListShow[this.curClassIndex].id
                schedule.time.push({
                    week: data.col,
                    id: data.row.id
                })
            } else {

                schedule = course.schedule.find(item => {
                    return item.room == this.roomListShow[this.curClassIndex].id && item.teacherId == data.teaId
                })
                //2、如果此教室已经有对应的安排则直接添加时间即可
                if (schedule) {
                    schedule.time.push({
                        week: data.col,
                        id: data.row.id
                    })
                } 
                // 3、如果没有空的课程安排，也没有对应教室的安排，则新建一个schedule
                else {
                    schedule = {
                        room: this.roomListShow[this.curClassIndex].id,
                        classId: data.classId,
                        notice: '',
                        stulist: data.stulist,
                        teacherId: data.teaId,
                        teacherName: data.teaName,
                        time: []
                    }
                    schedule.time.push({
                        week: data.col,
                        id: data.row.id
                    })
                    course.schedule.push(schedule)
                }

            }
            this.updCusInfo(course, 'set')
        },
        //取消设置课程
        cancelCell(data) {
            let roomId = this.roomListShow[this.curClassIndex].id
            let info = data.row.weeklies[data.col]
            let cus = this.allClassCus[roomId].find(item => {
                return item.id == info.courseId
            })
            cus.schedule.forEach(schdItem => {
                if (schdItem.room == roomId && schdItem.teacherId == info.teacherId) {
                    schdItem.time.forEach((item, index) => {
                        if (item.id == data.row.id && item.week == data.col) {
                            schdItem.time.splice(index, 1)
                            this.updCusInfo(cus, 'cancel')
                        }
                    })
                }
            })
        },
        // 更新课程数据
        updCusInfo(course, type) {
            course.code = course.code.replace('Course-', '')
            this.$api.courseMgmt.saveOrUpdateCourse({
                course: course,
                option: 'update',
                scope: course.scope || 'school'
            }).then(
                res => {
                    this.$Message.success(this.$t('cusMgt.updateOk'))
                    let classId = this.roomListShow[this.curClassIndex].id
                    if (type == 'set') {
                        //更新成功后，更新本地数据，刷新课程表

                        this.allClassCus[classId] = this.allClassCus[classId] || []
                        let isExist = false
                        this.allClassCus[classId].forEach((item, index) => {
                            if (item.id == course.id) {
                                this.allClassCus[classId].splice(index, 1, course)
                                this.isExist = true
                            }
                        })
                        if (!isExist) {
                            this.allClassCus[classId].push(course)
                        }
                    } else {
                        this.allClassCus[classId].forEach((item, index) => {
                            if (item.id == course.id) {
                                this.allClassCus[classId].splice(index, 1, course)
                            }
                        })
                    }

                }
            ).catch((e) => {
                this.$Message.error(this.$t('cusMgt.updateErr'))
            })
        },
    },
    created() {
        //直接读取登录成功拿到得学校基础信息
        this.$store.dispatch('user/getSchoolProfile').then(
            res => {
                this.schoolInfo = res.school_base
                if (this.schoolInfo && this.schoolInfo.period) {
                    this.filterPeriod = this.schoolInfo.period[0].id
                    this.hasTimeTable = this.schoolInfo.period[0].timetable ? true : false
                }
                this.roomList = res.school_rooms
                this.roomListShow = [...this.roomList]
            },
            err => {
                this.$Message.warning(this.$t('cusMgt.noSchool'))
            }
        ).finally(() => {
            this.findClassCus()
        })
    },
    computed: {
        //当前班级对应的课程数据
        roomCus() {
            let roomId = this.roomListShow[this.curClassIndex].id
            if (roomId && this.allClassCus[roomId]) {
                return this.allClassCus[roomId]
            } else {
                return []
            }
        }
    }
}
</script>
<style scoped lang="less">
@import "./CoursePlan.less";
</style>
<style>
.cus-table-content .ivu-table {
    width: 100%;
}

.ivu-table .custom-bg {
    background: #404040 !important;
}
</style>