<template>
    <div class="cus-table-container dark-iview-table cus-table">
        <vuescroll>
            <div class="cus-table-top dark-iview-input dark-iview-select">
                <div class="class-filter-wrap">
                </div>
            </div>
            <Table :columns="timeColumns" disabled-hover :data="timetable" border :span-method="handleSpan" style="width:calc(100% - 15px);margin-top:00px;">
                <!--上午/下午-->
                <template slot-scope="{ row, index }" slot="sub">
                    <p class="am-pm" style="">
                        {{parseInt(row.time.substr(0,2)) > 12 ? $t('cusMgt.pm') : $t('cusMgt.am')}}
                    </p>
                </template>
                <!--时段-->
                <template slot-scope="{ row, index }" slot="time">
                    <p style="padding:10px 0px 4px 0px;font-size: 20px;">
                        {{row.time}}
                    </p>
                    <p style="font-size:12px;padding:4px 0px 10px 0px;">
                        {{'('+row.label+')'}}
                    </p>
                </template>
                <!--星期一-->
                <template slot-scope="{ row, column }" slot="MON">
                    <div :class="row.weeklies.MON.status == 1 ? 'week-day-cell':'week-day-cell vact-status'">
                        <div class="toggle-status-btn-wrap" v-show="mode == 'set'">
                            <Icon class="cell-action-icon" v-show="!row.weeklies[column.slot].courseName" custom="iconfont icon-choose" :title="$t('cusMgt.setCus')" @click="selectCell(row, column.slot)" />
                            <Icon class="cell-action-icon" v-show="row.weeklies[column.slot].courseName" type="md-create" :title="$t('cusMgt.modifyCus')" @click="selectCell(row, column.slot)" />
                            <Icon class="cell-action-icon" v-show="row.weeklies[column.slot].courseName" type="md-close" :title="$t('cusMgt.cancelCus')" @click="cancelCell(row, column.slot)" />
                            <Icon class="cell-action-icon" v-show="schd.setCus && schd.setTea" type="md-copy" :title="$t('cusMgt.repeat')" @click="copyCell(row, column.slot)" />
                        </div>
                        <p :class="['course-name']">{{row.weeklies.MON.courseName}}</p>
                        <p :class="['classroom-name']">{{row.weeklies.MON.teacherName}}</p>
                    </div>
                </template>
                <!--星期二-->
                <template slot-scope="{ row, column }" slot="TUE">
                    <div :class="row.weeklies.TUE.status == 1 ? 'week-day-cell':'week-day-cell vact-status'">
                        <div class="toggle-status-btn-wrap" v-show="mode == 'set'">
                            <Icon class="cell-action-icon" v-show="!row.weeklies[column.slot].courseName" custom="iconfont icon-choose" :title="$t('cusMgt.setCus')" @click="selectCell(row, column.slot)" />
                            <Icon class="cell-action-icon" v-show="row.weeklies[column.slot].courseName" type="md-create" :title="$t('cusMgt.modifyCus')" @click="selectCell(row, column.slot)" />
                            <Icon class="cell-action-icon" v-show="row.weeklies[column.slot].courseName" type="md-close" :title="$t('cusMgt.cancelCus')" @click="cancelCell(row, column.slot)" />
                            <Icon class="cell-action-icon" v-show="schd.setCus && schd.setTea" type="md-copy" :title="$t('cusMgt.repeat')" @click="copyCell(row, column.slot)" />
                        </div>
                        <p :class="['course-name']">{{row.weeklies.TUE.courseName}}</p>
                        <p :class="['classroom-name']">{{row.weeklies.TUE.teacherName}}</p>
                    </div>
                </template>
                <!--星期三 -->
                <template slot-scope="{ row, column }" slot="WED">
                    <div :class="row.weeklies.WED.status == 1 ? 'week-day-cell':'week-day-cell vact-status'">
                        <div class="toggle-status-btn-wrap" v-show="mode == 'set'">
                            <Icon class="cell-action-icon" v-show="!row.weeklies[column.slot].courseName" custom="iconfont icon-choose" :title="$t('cusMgt.setCus')" @click="selectCell(row, column.slot)" />
                            <Icon class="cell-action-icon" v-show="row.weeklies[column.slot].courseName" type="md-create" :title="$t('cusMgt.modifyCus')" @click="selectCell(row, column.slot)" />
                            <Icon class="cell-action-icon" v-show="row.weeklies[column.slot].courseName" type="md-close" :title="$t('cusMgt.cancelCus')" @click="cancelCell(row, column.slot)" />
                            <Icon class="cell-action-icon" v-show="schd.setCus && schd.setTea" type="md-copy" :title="$t('cusMgt.repeat')" @click="copyCell(row, column.slot)" />
                        </div>
                        <p :class="['course-name']">{{row.weeklies.WED.courseName}}</p>
                        <p :class="['classroom-name']">{{row.weeklies.WED.teacherName}}</p>
                    </div>
                </template>
                <!--星期四-->
                <template slot-scope="{ row, column }" slot="THU">
                    <div :class="row.weeklies.THU.status == 1 ? 'week-day-cell':'week-day-cell vact-status'">
                        <div class="toggle-status-btn-wrap" v-show="mode == 'set'">
                            <Icon class="cell-action-icon" v-show="!row.weeklies[column.slot].courseName" custom="iconfont icon-choose" :title="$t('cusMgt.setCus')" @click="selectCell(row, column.slot)" />
                            <Icon class="cell-action-icon" v-show="row.weeklies[column.slot].courseName" type="md-create" :title="$t('cusMgt.modifyCus')" @click="selectCell(row, column.slot)" />
                            <Icon class="cell-action-icon" v-show="row.weeklies[column.slot].courseName" type="md-close" :title="$t('cusMgt.cancelCus')" @click="cancelCell(row, column.slot)" />
                            <Icon class="cell-action-icon" v-show="schd.setCus && schd.setTea" type="md-copy" :title="$t('cusMgt.repeat')" @click="copyCell(row, column.slot)" />
                        </div>
                        <p :class="['course-name']">{{row.weeklies.THU.courseName}}</p>
                        <p :class="['classroom-name']">{{row.weeklies.THU.teacherName}}</p>
                    </div>
                </template>
                <!--星期五-->
                <template slot-scope="{ row, column }" slot="FRI">
                    <div :class="row.weeklies.FRI.status == 1 ? 'week-day-cell':'week-day-cell vact-status'">
                        <div class="toggle-status-btn-wrap" v-show="mode == 'set'">
                            <Icon class="cell-action-icon" v-show="!row.weeklies[column.slot].courseName" custom="iconfont icon-choose" :title="$t('cusMgt.setCus')" @click="selectCell(row, column.slot)" />
                            <Icon class="cell-action-icon" v-show="row.weeklies[column.slot].courseName" type="md-create" :title="$t('cusMgt.modifyCus')" @click="selectCell(row, column.slot)" />
                            <Icon class="cell-action-icon" v-show="row.weeklies[column.slot].courseName" type="md-close" :title="$t('cusMgt.cancelCus')" @click="cancelCell(row, column.slot)" />
                            <Icon class="cell-action-icon" v-show="schd.setCus && schd.setTea" type="md-copy" :title="$t('cusMgt.repeat')" @click="copyCell(row, column.slot)" />
                        </div>
                        <p :class="['course-name']">{{row.weeklies.FRI.courseName}}</p>
                        <p :class="['classroom-name']">{{row.weeklies.FRI.teacherName}}</p>
                    </div>
                </template>
                <!--星期六-->
                <template slot-scope="{ row, column }" slot="SAT">
                    <div :class="row.weeklies.SAT.status == 1 ? 'week-day-cell':'week-day-cell vact-status'">
                        <p :class="['course-name']">{{row.weeklies.SAT.courseName}}</p>
                        <p :class="['classroom-name']">{{row.weeklies.SAT.teacherName}}</p>
                    </div>
                </template>
                <!--星期日-->
                <template slot-scope="{ row, column }" slot="SUN">
                    <div :class="row.weeklies.SUN.status == 1 ? 'week-day-cell':'week-day-cell vact-status'">
                        <p :class="['course-name']">{{row.weeklies.SUN.courseName}}</p>
                        <p :class="['classroom-name']">{{row.weeklies.SUN.teacherName}}</p>
                    </div>
                </template>
            </Table>
        </vuescroll>
        <Modal v-model="modalStatus" :title="$t('cusMgt.cusClass')" @on-ok="modalOk" @on-cancel="modalCancel" class-name="dark-iview-modal dark-iview-form dark-iview-select">
            <Form ref="setCusForm" :model="schd" :label-width="80" label-colon :rules="ruleValidate">
                <FormItem :label="$t('cusMgt.course')" prop="setCus">
                    <Select v-show="cusListShow.length" v-model="schd.setCus" filterable style="width:90%;" @on-change="getCusFullInfo">
                        <Option v-for="(item,index) in cusListShow" :key="index" :value="item.id">{{item.name}}</Option>
                    </Select>
                </FormItem>
                <FormItem :label="$t('cusMgt.teaLabel')" prop="setTea">
                    <Select v-model="schd.setTea" filterable style="width:90%;" :not-found-text="schd.setCus ? $t('cusMgt.noAddTea') : $t('cusMgt.sltCusTips')">
                        <Option v-for="(item,index) in cusTeaList" :key="index" :value="item.id" @click.native="setTeaName(item)">{{item.name}}</Option>
                    </Select>
                </FormItem>
                <FormItem :label="$t('cusMgt.nameListType')">
                    <RadioGroup v-model="schd.isClass" style="color:white">
                        <Radio :label="1">
                            <span>{{$t('cusMgt.scClass')}}</span>
                        </Radio>
                        <Radio :label="0" style="margin-left:20px">
                            <span>{{$t('cusMgt.customNameList')}}</span>
                        </Radio>
                    </RadioGroup>
                </FormItem>
                <FormItem :label="$t('cusMgt.className')" prop="setTea" v-if="schd.isClass == 1">
                    <Select v-model="schd.classId" filterable style="width:90%;">
                        <Option v-for="(item,index) in teaClassList" :key="index" :value="item.id">{{item.name}}</Option>
                    </Select>
                </FormItem>
                <FormItem :label="$t('cusMgt.nameList')" prop="setTea" v-else>
                    <Select v-model="schd.stulist" filterable style="width:90%;">
                        <Option v-for="(item,index) in teaStuList" :key="index" :value="item.id">{{item.name}}</Option>
                    </Select>
                </FormItem>
            </Form>
        </Modal>
    </div>
</template>
<script>
export default {
    props: {
        periodId: {
            type: String,
            default: ''
        },
        //课程对象数据
        schedData: {
            type: Array,
            default: () => {
                return []
            }
        },
        roomId: {
            type: String,
            default: '',
            required: true
        },
        mode: {
            type: String,
            default: 'set' //set：设置模式 view：视图模式，只渲染功能
        }
    },
    data() {
        return {
            cusList: [],
            classList: [],
            roomList: [],
            stuList: [],
            setClass: '',
            schd: {
                isClass: 1,
                setCus: '',
                setTea: '',
                teaName: '',
                classId: '',
                stulist: ''
            },
            ruleValidate: {
                setCus: [
                    { required: true, message: this.$t('cusMgt.setCusWarning'), trigger: 'change' }
                ],
                setTea: [
                    { required: true, message: this.$t('cusMgt.setTeaWarning'), trigger: 'change' }
                ]
            },
            modalStatus: false,
            subIndex: 0,
            schoolBase: {
                period: []
            },
            timeColumns: [
                {
                    title: ' ',
                    slot: 'sub',
                    width: 80,
                    align: 'center',
                    className: 'custom-bg'
                },
                {
                    title: ' ',
                    slot: 'time',
                    width: 160,
                    align: 'center'
                },
                {
                    title: this.$t('cusMgt.mon'),
                    slot: 'MON',
                    align: 'center'
                },
                {
                    title: this.$t('cusMgt.tue'),
                    slot: 'TUE',
                    align: 'center'
                },
                {
                    title: this.$t('cusMgt.wed'),
                    slot: 'WED',
                    align: 'center'
                },
                {
                    title: this.$t('cusMgt.thu'),
                    slot: 'THU',
                    align: 'center'
                },
                {
                    title: this.$t('cusMgt.fri'),
                    slot: 'FRI',
                    align: 'center'
                },
                {
                    title: this.$t('cusMgt.sat'),
                    slot: 'SAT',
                    align: 'center'
                },
                {
                    title: this.$t('cusMgt.sun'),
                    slot: 'SUN',
                    align: 'center'
                }
            ],
            selectInfo: {}
        }
    },
    methods: {
        //查询名单列表
        findStuList() {
            let params = {
                code: this.$store.state.userInfo.schoolCode,
                scope: 'school'
            }
            this.$api.courseMgmt.findStulist(params).then(
                res => {
                    this.stuList = res.stuList
                },
                err => {
                    this.$Message.error('API error')
                }
            )
        },
        //设置教师姓名
        setTeaName(data) {
            this.schd.teaName = data.name
        },
        //获取课程完整信息
        getCusFullInfo(data) {
            let cusIndex = -1
            let cus = this.cusList.find((item, index) => {
                cusIndex = index
                return item.id == data
            })
            if (cus && !cus.schedule) {
                //获取课程完整信息
                let requestData = {
                    'code': this.$store.state.userInfo.schoolCode,
                    'scope': 'school',
                    'id': data
                }
                this.$api.courseMgmt.findCusInfo(requestData).then(
                    (res) => {
                        if (!res.error && res.courses && res.courses.length > 0) {
                            res.courses[0].schedule = res.courses[0].schedule ? res.courses[0].schedule : []
                            this.$set(this.cusList, cusIndex, res.courses[0])
                        }
                    }
                )
            }
        },
        copyCell(row, col) {
            let data = {
                row,
                col,
                cusId: this.schd.setCus,
                teaId: this.schd.setTea,
                teaName: this.schd.teaName,
                course: this.cusListShow.find(item => {
                    return item.id == this.schd.setCus
                })
            }
            this.$emit('selectCell', data)
        },
        selectCell(row, col) {
            this.modalStatus = true
            this.selectInfo = { row, col }
        },
        modalOk() {
            this.$refs['setCusForm'].validate((valid) => {
                if (valid) {
                    let data = this._.cloneDeep(this.selectInfo)
                    data.cusId = this.schd.setCus //当前设置的课程
                    data.teaId = this.schd.setTea //当前设置的教师
                    data.teaName = this.schd.teaName //当前设置的教师名字
                    data.stulist = this.schd.isClass == 1 ? '' : this.schd.stulist
                    data.classId = this.schd.isClass == 1 ? this.schd.classId : ''
                    data.course = this.cusListShow.find(item => {
                        return item.id == this.schd.setCus
                    })
                    this.$emit('selectCell', data)
                } else {
                    this.$Message.error(this.$t('cusMgt.formTips'))
                }
            })
        },
        cancelCell(row, col) {
            this.$emit('cancelCell', { row, col })
        },
        modalCancel() {

        },
        //根据上下午合并单元格
        handleSpan({ row, column, rowIndex, columnIndex }) {
            this.getSubIndex()
            if (rowIndex === 0 && columnIndex === 0) {
                return [this.subIndex, 1]
            } else if (rowIndex < this.subIndex && columnIndex === 0) {
                return [0, 0]
            }
            if (rowIndex == this.subIndex && columnIndex === 0) {
                return [this.timetable.length - this.subIndex, 1]
            } else if (rowIndex > this.subIndex && columnIndex === 0) {
                return [0, 0]
            }
        },
        getSubIndex() {
            for (let index in this.timetable) {
                if (parseInt(this.timetable[index].time.substr(0, 2)) > 12) {
                    this.subIndex = parseInt(index)
                    break
                }
            }
        },
        //获取课程列表
        getCourseList() {
            let requestData = {
                'code': this.$store.state.userInfo.schoolCode,
                'scope': 'school'
            }
            this.$api.courseMgmt.findCourse(requestData).then(
                (res) => {
                    if (res) {
                        this.cusList = res.courses
                    }
                }
            ).finally(() => {
                setTimeout(() => {
                    this.tableLoading = false
                    this.listLoading = false
                }, 500)
            })
        },
    },
    created() {
        //直接读取登录成功拿到得学校基础信息
        this.$store.dispatch('user/getSchoolProfile').then(
            res => {
                this.schoolBase = res.school_base
                this.classList = res.school_classes
                this.roomList = res.school_rooms
            },
            err => {
                this.$Message.warning(this.$t('cusMgt.noSchool'))
            }
        )
        this.getCourseList()
        this.findStuList()
    },
    watch: {
        roomId() {
            this.schd = {
                setCus: '',
                setTea: ''
            }
        }
    },
    computed: {
        //当前老师班级列表
        teaClassList() {
            let curCus = this.cusListShow.find(item => {
                return item.id == this.schd.setCus
            })
            if (curCus && curCus.schedule) {
                let schedules = curCus.schedule.filter(item=>{
                    return item.teacherId == this.schd.setTea
                })
                let classIds = schedules.map(item => {
                    return item.classId
                })

                let classes = this.classList.filter(item => {
                    return classIds.indexOf(item.id) > -1 
                })
                return classes
            } else {
                return []
            }

        },
        //当前老师班级列表
        teaStuList() {
            let curCus = this.cusListShow.find(item => {
                return item.id == this.schd.setCus
            })
            if (curCus && curCus.schedule) {
                let schedules = curCus.schedule.filter(item=>{
                    return item.teacherId == this.schd.setTea
                })
                let listIds = schedules.map(item => {
                    return item.stulist
                })

                let list = this.stuList.filter(item => {
                    return listIds.indexOf(item.id) > -1
                })
                return list
            } else {
                return []
            }
        },

        //当前课程的授课老师
        cusTeaList() {
            if (this.schd.setCus) {
                let cus = this.cusList.find(item => {
                    return item.id == this.schd.setCus
                })
                if (cus && cus.schedule) {
                    let all = cus.schedule.map(item => {
                        return {
                            id: item.teacherId,
                            name: item.teacherName
                        }
                    })
                    const res = new Map()
                    let removeRep = all.filter((a) => !res.has(a.id) && res.set(a.id, 1))
                    return removeRep
                } else {
                    return []
                }
            }
            return []
        },
        //筛选当前学段的课程
        cusListShow() {
            if (this.periodId) {
                let res = this.cusList.filter(item => {
                    return item.period.id == this.periodId
                })
                return res
            }
            return this.cusList
        },
        timetable() {
            let curPrd = this.schoolBase.period.find(item => {
                return item.id == this.periodId
            })
            curPrd = curPrd || this.schoolBase.period[0] //没有传pdId就默认第一个
            if (curPrd && curPrd.timetable) {
                let timetable = this._.cloneDeep(curPrd.timetable)
                timetable.forEach(item => {
                    item.weeklies = {
                        MON: {
                            status: 1
                        },
                        TUE: {
                            status: 1
                        },
                        WED: {
                            status: 1
                        },
                        THU: {
                            status: 1
                        },
                        FRI: {
                            status: 1
                        },
                        SAT: {},
                        SUN: {},
                    }
                    // 根据课程数据补充课程表
                    this.schedData.forEach(cusItem => {
                        if (cusItem.schedule) {
                            cusItem.schedule.forEach((schedItem, sIndex) => {
                                // 只渲染当前班级的schedule
                                if (schedItem.room == this.roomId) {
                                    let roomInfo = this.roomList.find(roomItem => {
                                        return roomItem.id == schedItem.room
                                    })
                                    if (this.roomId) {
                                        if (this.roomId != schedItem.room) {
                                            return false
                                        }
                                    }
                                    schedItem.time.forEach(timeItem => {
                                        if (timeItem.id == item.id) {
                                            item.weeklies[timeItem.week].courseName = cusItem.name
                                            item.weeklies[timeItem.week].courseId = cusItem.id
                                            item.weeklies[timeItem.week].classId = schedItem.classId
                                            item.weeklies[timeItem.week].roomName = roomInfo ? roomInfo.name : '--'
                                            item.weeklies[timeItem.week].teacherName = schedItem.teacherName
                                            item.weeklies[timeItem.week].teacherId = schedItem.teacherId
                                        }
                                    })
                                }

                            })

                        }
                    })
                })
                return timetable
            } else {
                return []
            }
        }
    }
}
</script>
<style lang="less" scoped>
@import "./ClassTable.less";
</style>
<style lang="less">
.cus-table-container .ivu-table {
    width: 100%;
}
.ivu-table .custom-bg {
    background: #404040 !important;
}
</style>
