<template>
    <div class="class-mgt-container">
        <Loading v-show="isListLoading"></Loading>
        <div class="class-list-wrap">
            <!--班级列表-->
            <div class="class-list-header">
                <Dropdown class="sort-dropdown" trigger="click" placement="bottom-start" @on-click="function(e){ filterPeriod = e }" @on-visible-change="dropdownStates" v-if="$store.state.user.schoolProfile.school_base">
                    <span style="cursor: pointer;">
                        <!-- {{$t('schoolBaseInfo.pdLabel')}} -->
                        <b class="title">{{ filterPeriodName }}</b>
                        <Icon type="ios-arrow-down" style="margin-left:8px;"></Icon>
                    </span>
                    <DropdownMenu slot="list" v-for="(item,index) in periods" :value="item.id" :key="index">
                        <DropdownItem :name="item.id">{{ item.name }}</DropdownItem>
                    </DropdownMenu>
                </Dropdown>
                <Dropdown class="sort-dropdown" trigger="click" placement="bottom-start" @on-click="function(e){ filterYear = e }" @on-visible-change="filterByYear" style="margin-left:15px">
                    <span style="cursor: pointer;">
                        <b class="title">{{ filterYearName}}</b>
                        <Icon type="ios-arrow-down" style="margin-left:8px;"></Icon>
                    </span>
                    <DropdownMenu slot="list">
                        <DropdownItem name="all">{{$t('schoolBaseInfo.all')}}</DropdownItem>
                    </DropdownMenu>
                    <DropdownMenu slot="list" v-for="(item,index) in years" :value="item.value" :key="index">
                        <DropdownItem :name="item.value">{{ item.label }}</DropdownItem>
                    </DropdownMenu>
                </Dropdown>
                <div v-if="!isSearch" style="float:right;">
                    <Icon class="action-btn-icon" type="ios-search" @click="isSearch = true" />
                    <Icon v-if="$access.can('admin.*|classroom-upd')" class="action-btn-icon" type="md-trash" @click.stop="showConfirmDelete()" />
                    <Icon v-if="$access.can('admin.*|classroom-upd')" class="action-btn-icon" type="md-add" @click="addClassroom()" />
                </div>
                <div v-else class="dark-iview-input" style="float:right;width:calc(100% - 200px);padding-right:10px;">
                    <Input icon="ios-close" v-model="keyword" :placeholder="$t('schoolBaseInfo.codeSearchHolder')" autofocus style="width:100%" @on-click="closeKeySearch" @on-change="filterClassname" />
                </div>
            </div>
            <div class="class-list">
                <vuescroll>
                    <div class="class-list-item" v-for="(item,index) in classListShow" :key="index" @click="chooseClassroom(index)" :class="curClassIndex == index ? 'block-bg block-bg-active':'block-bg'">
                        <div class="class-list-item-left">
                            <p style="color:white;font-size: 12px;">
                                {{item.year ? item.year+'级' : '未设置'}}
                                <span v-show="item.year" style="color: #a5a5a5">{{`(${$jsFn.getGradeNameByYear(schoolBase, filterPeriod, item.year)})`}}</span>
                            </p>
                            <p class="class-name">
                                <span class="class-id-tag">
                                    {{item.no}}
                                </span>
                                <span>
                                    {{item.name}}
                                </span>
                            </p>
                            <p class="class-type">
                            <p class="second-text-color">
                                <span>{{ $t('schoolBaseInfo.headmaster')}}：</span>
                                <span class="primary-text-color">{{item.teacher.name}}</span>
                            </p>
                        </div>
                    </div>
                    <EmptyData v-if="classListShow.length == 0" style="padding-top:120px;"></EmptyData>
                </vuescroll>
            </div>
        </div>
        <div class="class-info-wrap">
            <div class="class-info-header common-save-btn">
                <span :class="currentTabIndex == 0 ? 'main-header-tab line-bottom line-bottom-active':'main-header-tab line-bottom'" @click="selectTab(0)">
                    {{$t('schoolBaseInfo.tab1')}}
                </span>
                <span :class="currentTabIndex == 2 ? 'main-header-tab line-bottom line-bottom-active':'main-header-tab line-bottom'" @click="selectTab(2)">
                    {{$t('schoolBaseInfo.tab2')}}
                </span>
                <!-- 编辑教室 -->
                <Button class="save-btn" :loading="isSaveLoading" :disabled="!updated" icon="ios-albums-outline" @click="saveClassroom()" v-show="currentTabIndex == 0">
                    {{$t('schoolBaseInfo.saveInfo')}}
                </Button>
                <!-- 添加学生 -->
                <Button v-if="$access.can('admin.*|student-upd')" class="save-btn" :loading="isSaveLoading" icon="md-add" @click="addStuStatus = true" v-show="currentTabIndex == 2">
                    {{$t('schoolBaseInfo.addStuBtn')}}
                </Button>
                <!-- 移除学生 -->
                <Button v-if="$access.can('admin.*|student-upd')" class="save-btn" style="margin-right:10px;" :loading="isSaveLoading" icon="md-remove-circle" @click="removeStudent(-1)" v-show="currentTabIndex == 2">
                    {{$t('schoolBaseInfo.delStuBtn')}}
                </Button>
            </div>
            <div class="class-info-content">
                <!--基础信息-->
                <div v-show="currentTabIndex == 0" style="display:flex;flex-direction:row;width:100%;height:100%;">
                    <!--班级属性-->
                    <div class="class-attr-wrap disabled-iview-select dark-iview-select">
                        <vuescroll>
                            <Form v-if="classListShow[curClassIndex]" ref="classInfo" :model="classListShow[curClassIndex]" :rules="classValidate" style="padding-top:20px;">
                                <FormItem prop="name" @click.native.stop class="requird-color">
                                    <span slot="label" class="class-attr-wrap-label">{{$t('schoolBaseInfo.className')}}</span>
                                    <Input @on-change="watchUpdate" :disabled="editStatus" v-model="classListShow[curClassIndex].name" clearable :placeholder="$t('schoolBaseInfo.classroomNameHolder')" />
                                </FormItem>

                                <FormItem prop="year" @click.native.stop class="requird-color">
                                    <span slot="label" class="class-attr-wrap-label">{{$t('schoolBaseInfo.yearGrade')}}</span>
                                    <!-- 暂未入学班级 -->
                                    <p v-if="classListShow[curClassIndex].year > maxYear" class="grade-year-tips">
                                        {{$t('schoolBaseInfo.untimed')}}
                                    </p>
                                    <!-- 在校班级 -->
                                    <Select v-else-if="classListShow[curClassIndex].year <= maxYear && classListShow[curClassIndex].year > minYear" @on-change="watchUpdate" :disabled="editStatus" v-model="classListShow[curClassIndex].year" clearable>
                                        <Option v-for="(item,index) in years" :value="item.value" :key="index">
                                            {{ item.label }}
                                        </Option>
                                    </Select>
                                    <!-- 毕业班级 -->
                                    <p v-else-if="classListShow[curClassIndex].year <= minYear && classListShow[curClassIndex].year > 0" class="grade-year-tips">
                                        {{$t('schoolBaseInfo.graduated')}}
                                    </p>
                                    <!-- 未设置 -->
                                    <Select v-else @on-change="watchUpdate" :disabled="editStatus" v-model="classListShow[curClassIndex].year" clearable>
                                        <Option v-for="(item,index) in years" :value="item.value" :key="index">
                                            {{ item.label }}
                                        </Option>
                                    </Select>
                                </FormItem>
                                <FormItem prop="no" @click.native.stop class="requird-color">
                                    <span slot="label" class="class-attr-wrap-label">{{$t('schoolBaseInfo.classLabel')}}</span>
                                    <Input @on-change="watchUpdate" :disabled="editStatus" v-model="classListShow[curClassIndex].no" clearable :placeholder="$t('schoolBaseInfo.classroomCodeHolder')" />
                                </FormItem>

                                <FormItem prop="teacher" @click.native.stop class="requird-color">
                                    <span slot="label" class="class-attr-wrap-label">{{$t('schoolBaseInfo.headmaster')}}</span>
                                    <Select @on-change="watchUpdate" :disabled="editStatus" v-model="classListShow[curClassIndex].teacher.id" clearable filterable>
                                        <Option v-for="(item,index) in $store.state.teachers.teacherList.filter(item=>item.status == 'join')" :value="item.id" :key="index" @click.native="classListShow[curClassIndex].teacher.name = item.name">
                                            {{ item.name }}
                                        </Option>
                                    </Select>
                                </FormItem>
                                <!-- 第一阶段暂时隐藏 -->
                                <!-- <FormItem prop="profession" @click.native.stop class="requird-color">
                                    <span slot="label" class="class-attr-wrap-label">默认教室</span>
                                    <Select @on-change="watchUpdate" :disabled="editStatus" v-model="classListShow[curClassIndex].room" clearable not-found-text="暂无教室">
                                        <Option v-for="(item,index) in roomList" :value="item.id" :key="index">
                                            {{ item.name }}
                                        </Option>
                                    </Select>
                                </FormItem> -->
                                <FormItem prop="profession" @click.native.stop class="requird-color">
                                    <span slot="label" class="class-attr-wrap-label">{{$t('schoolBaseInfo.profession')}}</span>
                                    <Select @on-change="watchUpdate" :disabled="editStatus" v-model="classListShow[curClassIndex].marjorId" clearable :not-found-text="$t('schoolBaseInfo.noProfession')">
                                        <Option v-for="(item,index) in $jsFn.getPeriod($store.state.user.schoolProfile.school_base,classListShow[curClassIndex].periodId).majors" :value="item.id" :key="index">
                                            {{ item.name }}
                                        </Option>
                                    </Select>
                                </FormItem>
                            </Form>
                        </vuescroll>
                    </div>
                </div>

                <!--学生名单-->
                <div id="sut-list-box" class="dark-iview-table dark-iview-input" style="width:100%;height:100%;" v-show="currentTabIndex == 2">
                    <vuescroll style="height:100%;" v-if="classListShow[curClassIndex]">
                        <Table :columns="studentColumn" :data="students" @on-selection-change="(selections)=>{delSelections = selections}" :height="tableHeight" class="system-classroom-table" :loading="stuLoading" :no-data-text="$t('schoolBaseInfo.noStu')">
                            <Loading slot="loading" :top="0" bgColor="rgba(103, 103, 103, 0.27)"></Loading>
                            <template slot-scope="{ row }" slot="picture">
                                <PersonalPhoto :name="row.name" :picture="row.picture" />
                            </template>
                            <template slot-scope="{ row,index }" slot="no">
                                <span v-show="editIndex !== index">{{row.no}}</span>
                                <Input v-model="students[index].no" v-show="editIndex == index" style="width: 60px;" type="number" />
                                <Icon type="md-checkmark" v-show="editIndex == index" @click="confirmSetNo()" class="reset-no-btn" />
                                <Icon type="md-close" v-show="editIndex == index" @click="cancelSetNo()" class="reset-no-btn" />
                            </template>
                            <template slot-scope="{ row ,index}" slot="action">
                                <div class="item-tools" v-if="$access.can('admin.*|student-upd')">
                                    <Icon type="md-create" size="18" color="white" @click="resetNo(index)" :title="$t('schoolBaseInfo.editSeat')" />
                                    <Icon type="md-remove-circle" size="18" color="white" style="margin-left:10px" @click="removeStudent(index)" :title="$t('schoolBaseInfo.delStuBtn')" />
                                </div>
                            </template>
                        </Table>
                    </vuescroll>
                </div>
            </div>
        </div>
        <Modal v-model="addStuStatus" :title="$t('schoolBaseInfo.addStuBtn')" width="1200" @on-ok="confirmAddStu" class-name="dark-iview-modal">
            <StudentList @getSelectInfo="(selction)=>{selections = selction}"></StudentList>
        </Modal>
    </div>
</template>

<script>
import { mapGetters } from 'vuex'
import PersonalPhoto from "@/components/public/personalPhoto/Index.vue"
import StudentList from '@/components/coursemgt/StudentList.vue'
export default {
    components: {
        PersonalPhoto, StudentList
    },
    data() {
        // 验证只能是字母和数字
        const validateCode = (rule, value, callback) => {
            if (!value) {
                return callback(new Error(this.$t('schoolBaseInfo.classNoErr')))
            }
            let zg = /^[0-9]+$/
            if (zg.test(value)) {
                callback()
            } else {
                callback(new Error(this.$t('schoolBaseInfo.classNoErr1')))
            }
        }
        return {
            roomList: [],
            filterYear: 'all',
            studentColumn: [
                {
                    title: ' ',
                    type: 'selection',
                    width: 60,
                    align: 'center'
                },
                {
                    title: ' ',
                    slot: 'picture',
                    align: 'center ',
                    width: '150'
                },
                {
                    title: this.$t('courseManage.classroom.studentTableC2'),
                    key: 'name',
                    align: 'center '
                },
                {
                    title: this.$t('courseManage.classroom.studentTableC7'),
                    key: 'id',
                    align: 'center',
                    sortable: true
                },
                {
                    title: this.$t('courseManage.classroom.studentTableC1'),
                    slot: 'no',
                    align: 'center',
                    sortable: true
                },
                {
                    title: ' ',
                    slot: 'action',
                    align: 'center',
                    width: '150'
                }
            ],
            editIndex: -1,
            resetNoBef: 0,
            schoolBase: {
                period: []
            },
            delSelections: [],//需要移除的学生
            selections: [],//添加的学生
            addStuStatus: false,
            stuLoading: false,
            orderBy: 'id',
            updateBefore: '',
            filterPeriod: undefined,
            editStatus: true,//可切换编辑状态
            noStatus: false,
            isSearch: false,
            currentTabIndex: 0,
            isListLoading: false,
            isSaveLoading: false,
            isInit: true,
            updated: false,
            classList: [],
            classListShow: [],
            curClassIndex: 0,
            keyword: '',
            serchCode: '',
            attributeList: [
                {
                    value: '1',
                    label: this.$t('schoolBaseInfo.classAttr1')
                },
                {
                    value: '2',
                    label: this.$t('schoolBaseInfo.classAttr2')
                }
            ],
            classValidate: {
                no: [
                    { required: true, validator: validateCode, trigger: 'change' }
                ],
                name: [
                    { required: true, message: this.$t('schoolBaseInfo.nameWarning'), trigger: 'change' }
                ],
                openType: [
                    { required: true, message: this.$t('schoolBaseInfo.typeWarning'), trigger: 'change' }
                ],
                year: [
                    { required: true, type:'number', message: this.$t('schoolBaseInfo.gradeWarning'), trigger: 'change' }
                ]
            }
        }
    },
    computed: {
        ...mapGetters({
            periods: 'user/getPeriods', // 學制s
        }),
        filterYearName() {
            if (this.filterYear == 'all') {
                return '全部'
            } else {
                let data = this.years.find(item => {
                    return item.value == this.filterYear
                })
                if (data) {
                    return data.label
                } else {
                    return ''
                }
            }
        },
        filterPeriodName: function () {
            let data = this.periods
            let pId = this.filterPeriod
            let name = ''
            if (pId !== '') {
                let temp = data.filter(item => {
                    return pId == item.id
                })
                if (temp.length > 0) name = temp[0].name
            }
            return name
        },

        students() {
            if (this.currentTabIndex == '2') {
                if (this.classListShow[this.curClassIndex] && this.classListShow[this.curClassIndex].students) {
                    return this.classListShow[this.curClassIndex].students
                } else {
                    let params = {
                        'school_code': this.$store.state.userInfo.schoolCode,
                        'ids': [this.classListShow[this.curClassIndex].id],
                        'scope': 'school'
                    }
                    this.stuLoading = true
                    this.$api.schoolSetting.getClassroomStudent(params).then(
                        res => {
                            if (res.stus.length > 0) {
                                this.$set(this.classListShow[this.curClassIndex], 'students', res.stus[0])
                            }
                        },
                        err => {
                            this.$Message.error(this.$t('schoolBaseInfo.findStuErr'))
                        }
                    ).finally(() => {
                        this.stuLoading = false
                    })
                }
            } else {
                return []
            }
        },

        years() {
            if (this.schoolBase && this.schoolBase.period.length && this.filterPeriod) {
                let pData = this.schoolBase.period.find(item => {
                    return item.id == this.filterPeriod
                })
                if (pData) {
                    let date = new Date()
                    let year = date.getFullYear()
                    let month = date.getMonth() + 1
                    let start = pData.semesters.find(item => {
                        return item.start == 1
                    })
                    // 根据入学月份确定当前年级和学级的关系
                    if (start && month < start.month) {
                        year--
                    }
                    let res = pData.grades.map(item => {
                        return {
                            label: `${item}(${year}级)`,
                            value: year--
                        }
                    })
                    // this.filterYear = res[0].label
                    return res
                } else {
                    return []
                }
            }
            return []
        },
        //当前学段在校最大学级
        maxYear() {
            let date = new Date()
            let curYear = date.getFullYear()
            let month = date.getMonth() + 1
            if (this.schoolBase && this.schoolBase.period.length && this.filterPeriod) {
                let pData = this.schoolBase.period.find(item => {
                    return item.id == this.filterPeriod
                })
                if (pData) {
                    let start = pData.semesters.find(item => {
                        return item.start == 1
                    })
                    // 根据入学月份确定当前年级和学级的关系
                    if (start && month < start.month) {
                        curYear--
                    }
                    return curYear
                }
            } else {
                return curYear
            }
        },
        //当前学段在校最小学级
        minYear() {
            let date = new Date()
            let curYear = date.getFullYear()
            let month = date.getMonth() + 1
            if (this.schoolBase && this.schoolBase.period.length && this.filterPeriod) {
                let pData = this.schoolBase.period.find(item => {
                    return item.id == this.filterPeriod
                })
                if (pData) {
                    let start = pData.semesters.find(item => {
                        return item.start == 1
                    })
                    // 根据入学月份确定当前年级和学级的关系
                    if (start && month < start.month) {
                        curYear--
                    }
                    return curYear - pData.grades.length
                }
            } else {
                return curYear
            }
        },
    },
    methods: {
        // 设置班级学年
        getClassYear(value, date) {
            this.classListShow[this.curClassIndex].year = parseInt(value)
            this.updated = true
        },
        resetNo(index) {
            this.editIndex = index
            this.resetNoBef = this.students[index].no
        },
        confirmSetNo() {
            this.$Message.warning('暂未对接API')
            this.editIndex = -1
        },
        cancelSetNo() {
            this.students[this.editIndex].no = this.resetNoBef
            this.editIndex = -1
        },
        //移除班级里面的学生
        removeStudent(index) {
            let requestParams = {
                schoolId: this.$store.state.userInfo.schoolCode,
                students: [],
                grant_type: 'remove'
            }
            let names = []
            if (index > -1) {
                requestParams.students.push(this.students[index].id)
                names = [this.students[index].name]
            } else if (this.delSelections.length > 0) {
                requestParams.students = this.delSelections.map(item => {
                    return item.id
                })
                names = this.delSelections.map(item => {
                    return item.name
                })
            }
            if (requestParams.students.length) {
                this.$Modal.confirm({
                    title: this.$t('schoolBaseInfo.removeTile'),
                    content: `${this.$t('schoolBaseInfo.removeContent')}${names.join(', ')}?`,
                    onOk: () => {
                        this.$api.stuAccount.removeStudent(requestParams).then(
                            res => {
                                this.$Message.success(this.$t('schoolBaseInfo.removeOk'))
                                if (index > -1) {
                                    this.students.splice(index, 1)
                                } else {
                                    for (let i = 0; i < this.students.length; i) {
                                        if (requestParams.students.indexOf(this.students[i].id) > -1) {
                                            this.students.splice(i, 1)
                                            i--
                                        }

                                    }
                                    this.students.forEach()
                                }
                            },
                            err => {
                                this.$Message.error(this.$t('schoolBaseInfo.removeErr'))
                            }
                        )
                    }
                })
            }
        },
        //确认添加学生
        confirmAddStu() {
            if (this.selections.length > 0) {
                let data = this._.cloneDeep(this.selections)
                data.forEach(item => {
                    item.classId = this.classListShow[this.curClassIndex].id
                    item.className = this.classListShow[this.curClassIndex].name
                    item.classNo = this.classListShow[this.curClassIndex].no
                })

                this.listLoading = true
                this.$api.stuAccount.updateStudent({
                    students: data,
                    grant_type: 'update',
                    schoolId: this.$store.state.userInfo.schoolCode
                }).then(
                    (res) => {
                        if (!res.error) {
                            this.selections.length = 0
                            this.students.push(...data)
                            this.$Message.success(this.$t('schoolBaseInfo.addOk'))
                        } else {
                            this.$Message.error(this.$t('schoolBaseInfo.addErr'))
                        }
                    },
                    (err) => {
                        this.$Message.error(this.$t('schoolBaseInfo.addErr'))
                    }
                ).finally(() => {
                    this.listLoading = false
                    this.baseEditStatus = !this.baseEditStatus
                })
            }
        },

        dropdownStates(flag) {
            if (!flag) this.filterByPeriod()
        },
        restOrderBy(flag) {
            if (!flag) this.filterByPeriod()
        },
        closeKeySearch() {
            this.isSearch = false
            this.keyword = ''
            this.filterClassname()
        },
        watchUpdate(data) {
            if (data) {
                this.updated = true
            }
        },
        dataSort(data) {
            switch (this.orderBy) {
                case 'id': // no=>编号 排序
                    data.sort(function (a, b) {
                        let nameA = a.no.toUpperCase(); // ignore upper and lowercase
                        let nameB = b.no.toUpperCase(); // ignore upper and lowercase
                        if (nameA < nameB) {
                            return -1;
                        }
                        if (nameA > nameB) {
                            return 1;
                        }

                        // names must be equal
                        return 0;
                    })
                    break;
                case 'total':
                    data.sort(function (a, b) {
                        return b.studCount - a.studCount
                    })
                    break;
            }
            return data
        },
        // 学级/年级筛选
        filterByYear(status) {
            if (!status) {
                this.curClassIndex = 0
                if (this.filterYear == 'all') {
                    this.filterByPeriod()
                } else {
                    this.classListShow = this.classList.filter(item => (item.year == this.filterYear || !item.year) && item.periodId == this.filterPeriod)
                }
                // 排序
                this.classListShow = this.dataSort(this.classListShow)
            }
        },
        //学段筛选
        filterByPeriod() {
            this.curClassIndex = 0
            this.filterYear = 'all'
            if (this.filterPeriod) {
                this.classListShow = this.classList.filter(item => item.periodId == this.filterPeriod)
            } else {
                this.classListShow = [...this.classList]
            }
            // 排序
            let flag = 0
            this.classListShow.sort((a, b) => {
                let ay = a.year || flag--
                let by = b.year || flag--
                return by - ay
            })

        },
        filterClassname() {
            if (this.keyword == '' || this.keyword == undefined) {
                this.filterByPeriod()
            } else {
                let filterRes = []
                if (this.filterPeriod) {
                    filterRes = this.classList.filter(item => item.periodId == this.filterPeriod)
                } else {
                    filterRes = [...this.classList]
                }
                this.classListShow = filterRes.filter(item => item.name.indexOf(this.keyword) != -1)
                // 排序
                this.classListShow = this.dataSort(this.classListShow)
                this.curClassIndex = 0
                this.updateBefore = JSON.stringify(this.classListShow[this.curClassIndex])
            }
        },
        selectTab(index) {
            this.currentTabIndex = index
        },
        saveClassroom() {
            this.$refs['classInfo'].validate((valid) => {
                if (!valid) {
                    this.$Message.error(this.$t('schoolBaseInfo.formWarning'))
                } else {
                    let option = this.classListShow[this.curClassIndex].option
                    if (!option) {
                        option = 'update'
                    } else {
                        this.classListShow[this.curClassIndex]['code'] = this.$store.state.userInfo.schoolCode
                    }
                    delete this.classListShow[this.curClassIndex].option
                    this.isSaveLoading = true
                    this.isListLoading = true
                    if (this.classListShow[this.curClassIndex].openType == '2') {
                        this.classListShow[this.curClassIndex].teacher.id = ''
                        this.classListShow[this.curClassIndex].teacher.name = ''
                    }
                    this.$api.schoolSetting.classUpsert({
                        classroom: this.classListShow[this.curClassIndex],
                        option: option,
                        school_code: this.$store.state.userInfo.schoolCode
                    }).then(
                        res => {
                            if (res) {
                                if (res.error) {
                                    this.classListShow[this.curClassIndex].option = option
                                    this.$Message.error(res.v)
                                } else {
                                    this.$Message.success(this.$t('schoolBaseInfo.csTips3'))
                                    this.updated = false
                                    if (option == 'insert') {
                                        this.classListShow[this.curClassIndex].code = 'Class-' + this.classListShow[this.curClassIndex].code
                                        this.classList.unshift(this.classListShow[this.curClassIndex])
                                        this.$store.dispatch('user/addSchoolClasses', this.classListShow[this.curClassIndex]);
                                    }
                                }
                            } else {
                                this.$Message.error('API error!')
                            }
                        },
                        err => {
                            this.$Message.error('API error!')
                        }
                    ).finally(
                        () => {
                            this.isSaveLoading = false
                            this.isListLoading = false
                        }
                    )
                }
            })
        },
        /**显示确认删除班级对话框 */
        showConfirmDelete() {
            if (this.$access.can('admin.*|classroom-upd')) {
                this.$Modal.confirm({
                    title: this.$t('schoolBaseInfo.delClass'),
                    content: this.$t('schoolBaseInfo.delete') + this.classListShow[this.curClassIndex].name + this.$t('schoolBaseInfo.delContent'),
                    onOk: () => {
                        this.delClassroom(this.curClassIndex)
                    }
                })
            } else {
                this.$Message.warning(this.$t('schoolBaseInfo.authWarning'))
            }
        },
        delClassroom(index) {
            this.isListLoading = true
            if (this.classListShow[index].option !== 'insert') {
                this.$api.schoolSetting.delClassroom({
                    id: this.classListShow[index].id,
                    scope: this.classListShow[index].scope,
                    school_code: this.$store.state.userInfo.schoolCode
                }).then(
                    (res) => {
                        if (res.error == null) {
                            if (this.curClassIndex >= index && index > 0) {
                                this.curClassIndex = 0
                                this.updateBefore = JSON.stringify(this.classListShow[this.curClassIndex])
                            }
                            let originIndex = -1
                            for (let i in this.classList) {
                                if (this.classList[i].id == this.classListShow[index].id) {
                                    originIndex = i
                                    break
                                }
                            }
                            this.$api.schoolSetting.hiteachUnlinkByClassId({
                                classId: this.classListShow[index].id,
                                school_code: this.$store.state.userInfo.schoolCode
                            })
                            this.$store.dispatch('user/delSchoolClasses', this.classListShow[index].id);
                            this.classList.splice(originIndex, 1)
                            this.classListShow.splice(index, 1)
                            this.$Message.success(this.$t('schoolBaseInfo.csTips7'))
                            this.updated = false
                        }
                    },
                    (err) => {
                        this.$Message.error('API error!')
                    }
                ).finally(() => {
                    this.isListLoading = false
                })
            } else {
                if (this.curClassIndex >= index && index > 0) {
                    this.curClassIndex = 0
                    this.updateBefore = JSON.stringify(this.classListShow[this.curClassIndex])
                }
                this.classListShow.splice(index, 1)
                this.isListLoading = false
                this.updated = false
            }
        },
        chooseClassroom(index) {
            if (index != this.curClassIndex) {
                if (this.updated) {
                    let config = {
                        title: this.$t('schoolBaseInfo.saveWarning'),
                        content: this.$t('schoolBaseInfo.saveClassWarning'),
                        okText: this.$t('schoolBaseInfo.leaveText'),
                        onOk: () => {
                            if (this.classListShow[this.curClassIndex].option == 'insert') {
                                this.delClassroom(this.curClassIndex)
                            } else {
                                this.updated = false
                                this.$set(this.classListShow, this.curClassIndex, JSON.parse(this.updateBefore))
                                this.curClassIndex = index
                                this.updateBefore = JSON.stringify(this.classListShow[this.curClassIndex])
                            }
                        }
                    }
                    this.$Modal.confirm(config)
                } else {
                    this.curClassIndex = index
                    this.updateBefore = JSON.stringify(this.classListShow[this.curClassIndex])
                }
            }
        },
        addClassroom() {
            if (this.$access.can('admin.*|classroom-upd')) {
                this.keyword = ''
                this.classListShow.unshift({
                    id: this.$jsFn.uuid(),
                    name: this.$t('schoolBaseInfo.presetClassroomName') + (this.classList.length + 1),
                    no: '',
                    teacher: {
                        id: '',
                        name: ''
                    },
                    periodId: this.filterPeriod,
                    year: '',
                    scope: 'school',
                    option: 'insert'
                })
                this.curClassIndex = 0
                this.updateBefore = JSON.stringify(this.classListShow[this.curClassIndex])
            } else {
                this.$Message.warning(this.$t('schoolBaseInfo.authWarning'))
            }
        },

    },
    mounted() {
        this.filterClassname()
        this.tableHeight = document.getElementById('class-mgt-list').clientHeight - 45
    },
    beforeRouteLeave(to, from, next) {
        if (this.updated) {
            let config = {
                title: this.$t('schoolBaseInfo.saveWarning'),
                content: this.$t('schoolBaseInfo.saveClassWarning'),
                okText: this.$t('schoolBaseInfo.leaveText'),
                onOk: () => {
                    next()
                },
                onCancel: () => {
                    next(false)
                }
            }
            this.$Modal.confirm(config)
        } else {
            next()
        }
    },
    created() {
        this.isListLoading = true
        this.$store.dispatch('user/getSchoolProfile').then(
            res => {
                this.schoolBase = res.school_base
                this.classList = res.school_classes
                this.roomList = res.school_rooms
                if (this.classList.length > 0) {
                    this.updateBefore = JSON.stringify(this.classList[0])
                }
                this.filterClassname()
                // 預設搜尋給第一個
                if (this.periods) this.filterPeriod = this.periods[0].id
                this.filterByPeriod()
            }
        ).finally(() => {
            setTimeout(() => {
                this.isListLoading = false
            }, 500)
        })
        if (this.$access.can('admin.*|classroom-upd')) this.editStatus = this.noStatus
        this.$store.dispatch('teachers/getTeacherList').then(res => { })
    }
}
</script>
<style lang="less" scoped>
@import "./ClassMgt.less";
</style>
<style>
.class-mgt-container .ivu-table-row-hover .item-tools {
    display: inline-block;
    cursor: pointer;
}
.class-info-content
    .ivu-select-single
    .ivu-select-selection
    .ivu-select-placeholder,
.class-info-content
    .ivu-select-single
    .ivu-select-selection
    .ivu-select-selected-value {
    color: white;
}

.class-search-input .ivu-input {
    height: 30px;
    background: none;
    line-height: 30px;
    border: none;
    color: white;
    font-size: 15px;
}

.class-attr-wrap .ivu-input {
    width: calc(100% - 10px);
    background: none;
    border: none;
    border-radius: 0px;
    font-size: 16px;
    color: white;
    margin-left: 2px;
    border-bottom: 1px solid #424242;
}

.class-attr-wrap .ivu-select {
    width: calc(100% - 10px);
    color: white;
}

.class-attr-wrap .ivu-select-selected-value {
    font-size: 16px !important;
}

.class-attr-wrap .ivu-select-selection {
    background: none;
    border-color: #424242;
}

.class-attr-wrap .ivu-divider {
    background-color: #424242;
}
</style>
<style lang="less">
.gradient {
    @keyframes Itemfadein {
        0% {
            opacity: 0;
            transform: translate(-40px);
        }
        100% {
            opacity: 1;
            transform: translate(0px);
        }
    }
    animation: 0.5s Itemfadein;
}

.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;
                }
            }
        }
    }
}
.requird-color {
    .ivu-form-item-label:before {
        color: #1cc0f3;
    }
}
.hiteach-collapse {
    //     background: transparent;
    //     color: white;
    //     border-top: none;
    //     .ivu-collapse-item{
    //         .ivu-collapse-header{
    //             height: 200px;
    //             line-height: 200px;
    //             display: flex;
    //             align-items: center;
    //             padding-left: 15px;
    .ivu-tag-border {
        background: transparent !important;
        margin-right: 10px;
        border-radius: 5px;
        letter-spacing: 1px;
    }
    //             .ivu-icon-ios-arrow-forward{
    //                 position: absolute;
    //                 right: 2px;
    //                 font-size: 30px;
    //                 color: white;
    //             }
    //         }
    //         .ivu-collapse-content{
    //             background: transparent;
    //         }
    //     }
}
</style>