<template>
    <div class="course-plan-container">
        <Loading v-if="isLoading"></Loading>
        <div class="class-list-wrap">
            <div class="class-list-header">
                <!--<span>班级列表</span>-->
                <Dropdown class="sort-dropdown" trigger="click" placement="bottom-start" @on-click="selectPeriod" @on-visible-change="dropdownStates" v-if="$store.state.user.schoolProfile.school_base">
                    <span style="cursor: pointer;">
                        <b class="title">{{ filterPeriodName }}</b>
                        <!--{{ '班级列表' }}-->
                        <Icon type="ios-arrow-down" style="margin-left:8px;"></Icon>
                    </span>
                    <DropdownMenu slot="list" v-for="(item,index) in schoolBase.period" :value="item.id" :key="index">
                        <DropdownItem :name="item.id">{{ item.name }}</DropdownItem>
                    </DropdownMenu>
                </Dropdown>
                <Icon v-if="!isSearch" type="md-search" class="action-btn-icon" @click="toggleSearch" />
                <div v-else class="dark-iview-input" style="float:right;width: calc(100% - 100px);margin-right:10px;">
                    <Input icon="ios-close" v-model="classFilter.keyWord" :placeholder="$t('cusMgt.searchHolder')" autofocus @on-click="toggleSearch" @on-change="onSearchClass" @on-enter="onSearchClass" />
                </div>
            </div>
            <div class="class-list-content">
                <vuescroll>
                    <div class="class-list-item" v-for="(item,index) in classListShow" :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" v-if="item.openType == '1'">
                                <span>{{$t('schoolBaseInfo.headmaster')}}</span>
                                <span class="primary-text-color">{{item.teacher.name}}</span>
                            </p>
                            <p class="head-teacher" v-else>
                                <span>{{$t('cusMgt.spClass')}}</span>
                            </p>
                        </div>
                    </div>
                    <EmptyData v-if="classListShow.length == 0" style="padding-top:120px;"></EmptyData>
                </vuescroll>
            </div>
        </div>
        <div class="cus-table-wrap">
            <div class="cus-table-header common-save-btn">
                <span>{{$t('cusMgt.cusPlan')}}</span>
                <Button v-if="$access.can('admin.*|coursePlan-upd')" style="float:right;margin-right:10px;margin-top:6px;" :loading="isLoading" :disabled="!updated" icon="ios-albums-outline" @click="saveCusPlan()">
                    {{$t('schoolBaseInfo.saveInfo')}}
                </Button>
                <Button v-if="$access.can('admin.*|coursePlan-upd')" style="float:right;margin-right:10px;margin-top:6px;" @click="showImportCus" icon="md-arrow-round-up">
                    {{$t('cusMgt.importPlan')}}
                </Button>
            </div>
            <div class="cus-table-content dark-iview-select">
                <vuescroll>
                    <div :class="$access.can('admin.*|coursePlan-upd') ? 'course-setting-wrap':'course-setting-wrap disabled-iview-select'">
                        <div v-if="classListShow[curClassIndex] && classListShow[curClassIndex].cusSetting">
                            <div v-for="(cusItem,cusIndex) in classListShow[curClassIndex].cusSetting.courses" :key="cusIndex" style="margin-top:10px;">
                                <span class="label-text">{{$t('cusMgt.course')}}{{ cusIndex + 1 }}：</span>
                                <Select :disabled="!$access.can('admin.*|coursePlan-upd')" @on-change="selectCus($event,cusIndex)" v-model="classListShow[curClassIndex].cusSetting.courses[cusIndex].course.id" filterable label-in-value style="width:200px;" placeholder="请选择课程">
                                    <Option @click.native="handleUpdate" v-for="(item,index) in courseList.filter(item=>{return item.period.id == filterPeriod})" :value="item.id" :key="item.id">
                                        {{ item.name }}
                                    </Option>
                                </Select>
                                <Select :disabled="!$access.can('admin.*|coursePlan-upd')" @on-clear="handleUpdate" @on-change="selectTea($event,cusIndex)" v-model="selectTeaIds[cusIndex]" multiple filterable label-in-value style="width:calc(100% - 360px);margin-left:10px;" placeholder="请选择上课老师">
                                    <Option @click.native="handleUpdate" v-for="(item,index) in getCusTeaList(cusItem.course.id)" :value="item.id" :key="item.id">
                                        {{ item.name }}
                                    </Option>
                                </Select>
                                <Icon v-if="$access.can('admin.*|coursePlan-upd')" type="md-remove-circle" color="#ed4014" size="20" style="margin-left:10px;cursor:pointer" @click="delCusSetting(cusIndex)" />
                                <Icon v-if="$access.can('admin.*|coursePlan-upd')" v-show="(cusIndex + 1) == classListShow[curClassIndex].cusSetting.courses.length" type="md-add-circle" color="white" size="20" style="margin-left:10px;cursor:pointer" @click="addCusSetting" />
                            </div>
                            <div v-if="$access.can('admin.*|coursePlan-upd') && classListShow[curClassIndex].cusSetting.courses.length == 0" class="add-cus-box" @click="addCusSetting">
                                <Icon type="ios-add-circle" size="40" />
                                <span>{{$t('cusMgt.addCusPlan')}}</span>
                            </div>
                        </div>
                    </div>
                </vuescroll>
            </div>
        </div>
        <Modal v-model="importCusStatus" :title="$t('cusMgt.importPlan')" 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 ImportExcel from '@/common/ImportExcel.vue'
export default {
    components: {
        ImportExcel
    },
    inject: ['reload'],
    data() {
        return {
            schoolBase: {
                period: []
            },
            filterPeriod: '',
            orderBy: 'id',
            updated: false,
            selectedCus: [],
            confImpStatus: false,
            classFilter: {
                keyWord: ''
            },
            isSearch: false,
            isLoading: false,
            courseList: [],
            errorClass: [],
            errorCourse: [],
            errorTeacher: [],
            excelData: [],
            headerKeys: ['classroomCode', 'courseName', 'courseCode', 'teacher', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN'],
            headerTitles: ['班级', '课程名称', '课程编码', '授课老师', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'],
            importCusStatus: false,
            setCusStatus: false,
            moreClass: false,
            schoolInfo: {},
            isListLoading: false,
            classList: [],
            classListShow: [],
            curClassIndex: 0,
            importData: [],
        }
    },
    methods: {
        selectPeriod(data) {
            if (this.updated) {
                this.$Modal.confirm(
                    {
                        title: this.$t('cusMgt.saveTips'),
                        content: this.$t('cusMgt.tipsContent'),
                        okText: this.$t('cusMgt.leaveText'),
                        onOk: () => {
                            this.updated = false
                            this.filterPeriod = data
                            this.filterByPeriod()
                        }
                    }
                )
            } else {
                this.filterPeriod = data
            }
        },
        dropdownStates(flag) {
            if (!flag && !this.updated) this.filterByPeriod()
        },
        filterByPeriod() {
            this.curClassIndex = 0
            if (this.filterPeriod) {
                this.classListShow = this.classList.filter(item => item.periodId == this.filterPeriod || !item.periodId)
            } else {
                this.classListShow = [...this.classList]
            }
            // 排序
            this.classListShow = this.dataSort(this.classListShow)
            this.findClassPlan(0)
        },
        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;
            }
            console.log(data)
            return data
        },
        handleUpdate() {
            this.updated = true
        },
        //处理设置教师选择事件
        selectTea(data, index) {
            if (data.length < this.classListShow[this.curClassIndex].cusSetting.courses[index].teachers.length) {
                this.handleUpdate()
            }
            this.classListShow[this.curClassIndex].cusSetting.courses[index].teachers.length = []
            for (let item of data) {
                this.classListShow[this.curClassIndex].cusSetting.courses[index].teachers.push({
                    id: item.value,
                    name: item.label
                })
            }
        },
        //处理选择课程事件
        selectCus(data, index) {
            this.classListShow[this.curClassIndex].cusSetting.courses[index].course.id = data.value ? data.value : ''
            this.classListShow[this.curClassIndex].cusSetting.courses[index].course.name = data.label ? data.label : ''
        },
        getTableData() {

        },
        delCusSetting(index) {
            this.classListShow[this.curClassIndex].cusSetting.courses.splice(index, 1)
            this.updated = true
        },
        addCusSetting() {
            if (this.checkFull()) {
                this.classListShow[this.curClassIndex].cusSetting.courses.push(
                    {
                        course: {
                            id: '',
                            name: ''
                        },
                        teachers: []
                    }
                )
                this.updated = true
            } else {
                this.$Message.warning(this.$t('cusMgt.fullTips'))
            }
        },
        checkFull() {
            let flag = true
            for (let item of this.classListShow[this.curClassIndex].cusSetting.courses) {
                if (!item.course.id || item.teachers.length == 0) {
                    flag = false
                    break
                }
            }
            return flag
        },
        //获取当前课程授课老师
        getCusTeaList(code) {
            let curCus = this.courseList.filter((item) => {
                return item.id == code
            })
            if (curCus.length > 0) {
                return curCus[0].teachers
            } else {
                return []
            }
        },

        //关键字搜索班级
        onSearchClass() {
            this.curClassIndex = 0
            this.classListShow = this.classList.filter((item) => {
                return item.name.indexOf(this.classFilter.keyWord) !== -1
            })
        },
        /**切换搜索状态 */
        toggleSearch() {
            this.isSearch = !this.isSearch
            this.classFilter.keyWord = ''
            this.onSearchClass()
        },
        //获取课程列表
        getCourseList() {
            let requestData = {
                'school_code': this.$store.state.userInfo.schoolCode
            }
            this.$api.courseMgmt.findCourse(requestData).then(
                (res) => {
                    if (res) {
                        this.courseList = res.courses
                    }
                },
                (err) => {
                    this.$Message.error('API error！')
                }
            )
        },
        //确认设置课程
        saveCusPlan() {
            this.isLoading = true
            this.classListShow[this.curClassIndex].cusSetting.code = this.$store.state.userInfo.schoolCode
            this.$api.courseMgmt.upsertPlanDto(this.classListShow[this.curClassIndex].cusSetting).then(
                (res) => {
                    if (!res.error) {
                        this.$Message.success(this.$t('cusMgt.saveOk'))
                        this.updated = false
                    } else {
                        this.$Message.error(this.$t('cusMgt.saveErr'))
                    }
                },
                (err) => {
                    this.$Message.error(this.$t('cusMgt.saveErr'))
                }
            ).finally(() => {
                setTimeout(() => {
                    this.isLoading = false
                }, 500)
            })
        },
        //显示导入课程
        showImportCus() {
            this.$Message.warning('导入功能即将上线！')
            //this.importCusStatus = true
            //this.moreClass = false
        },
        //确认导入课程
        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
                    },
                    (err) => {
                        this.$Message.error('API ERROR！')
                        this.importData.length = 0
                    }
                ).finally(() => {
                    setTimeout(() => {
                        this.isLoading = false
                    }, 500)
                })
            } 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) {
            if (this.updated) {
                this.$Modal.confirm({
                    title: this.$t('cusMgt.saveTips'),
                    content: this.$t('cusMgt.tipsContent'),
                    okText: this.$t('cusMgt.leaveText'),
                    onOk: () => {
                        this.updated = false
                        if (!this.classListShow[index].cusSetting) {
                            this.findClassPlan(index)
                        }
                        this.curClassIndex = index
                    }
                })
            } else {
                if (!this.classListShow[index].cusSetting) {
                    this.findClassPlan(index)
                }
                this.curClassIndex = index
            }

        },
        //根据班级查询课程安排
        findClassPlan(index) {
            if (this.classListShow.length > 0) {
                this.isLoading = true
                let requestData = {
                    'id': this.classListShow[index].id,
                    'code': this.$store.state.userInfo.schoolCode
                }
                this.$api.courseMgmt.findPlan(requestData).then(
                    (res) => {
                        if (res.error) {
                            this.$Message.error(res.v)
                        } else {
                            if (res.courses.length > 0) {
                                this.$set(this.classListShow[index], 'cusSetting', res.courses[0])
                            } else {
                                this.$set(this.classListShow[index], 'cusSetting', {
                                    id: this.classListShow[index].id,
                                    code: this.$store.state.userInfo.schoolCode,
                                    name: this.classListShow[index].name,
                                    teacher: JSON.parse(JSON.stringify(this.classListShow[index].teacher)),
                                    scope: 'school'
                                })
                                this.$set(this.classListShow[index].cusSetting, 'courses', [])
                            }
                        }
                    },
                    (err) => {

                    }
                ).finally(() => {
                    setTimeout(() => {
                        this.isLoading = false
                    }, 500)
                })
            }
        }
    },
    async created() {
        this.isLoading = true
        await this.getCourseList()
        await this.$store.dispatch('user/getSchoolProfile').then(res => {
            //this.classList = JSON.parse(JSON.stringify(this.$store.state.schoolBaseInfo.classroomList))
            //this.classListShow = [...this.classList]
            //this.findClassPlan(0)
            //this.schoolInfo = this.$store.state.schoolBaseInfo.schoolBaseInfo
            this.classList = res.school_classes
            this.schoolBase = res.school_base
            if (this.schoolBase.period.length) {
                // 預設搜尋給第一個
                this.filterPeriod = res.school_base.period[0].id
                this.filterByPeriod()
            }
            this.findClassPlan(0)
        })
    },
    computed: {
        filterPeriodName() {
            let pId = this.filterPeriod
            let name = ''
            if (pId) {
                let temp = this.$store.state.user.schoolProfile.school_base.period.filter(item => {
                    return pId == item.id
                })
                if (temp.length > 0) name = temp[0].name
            }
            return name
        },
        //动态绑定已选择教师id
        selectTeaIds() {
            if (this.classListShow[this.curClassIndex].cusSetting) {
                let data = {}
                if (this.classListShow[this.curClassIndex].cusSetting.courses) {
                    for (let index in this.classListShow[this.curClassIndex].cusSetting.courses) {
                        data[index] = this.classListShow[this.curClassIndex].cusSetting.courses[index].teachers.map((item) => {
                            return item.id
                        })
                    }
                    return data
                }
            }
            return {}
        },
    }
}
</script>
<style scoped lang="less">
@import "./DelCoursePlan.less";
</style>
<style lang="less">
.cus-table-content .ivu-table {
    width: 100%;
}

.ivu-table .custom-bg {
    background: #404040 !important;
}
.sort-dropdown {
    .title {
        color: white;
        font-size: 14px;
    }
    .ivu-select-dropdown {
        background-color: #2d2d2d;
        border-radius: 2px;
        border: 1px #464646 solid;
        .ivu-dropdown-menu {
            li {
                color: #ccc;
                font-size: 12px !important;
                &:hover {
                    color: #2d2d2d;
                }
            }
        }
    }
}
</style>