<template>
    <div class="class-room-container custom-iview-split">
        <Split v-model="split1">
            <div class="class-list-wrap" slot="left">
                <!--教室列表头部-->
                <div class="class-list-header">
                    <span>{{$t('schoolBaseInfo.classroomList')}}</span>
                    <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-create" @click="editClassroom()" />
                        <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 style="float:right;width:calc(100% - 100px);padding-right:10px;">
                        <Input icon="ios-close" v-model="keyword" class="light-iview-input" :placeholder="$t('schoolBaseInfo.codeSearchHolder')" autofocus style="width:100%" @on-click="closeKeySearch" @on-change="filterClassname" />
                    </div>
                </div>
                <!-- 排序条件 -->
                <div class="class-list-filter">
                    <div class="class-list-filter-box">
                        <Dropdown class="sort-dropdown" trigger="click" placement="bottom-start" @on-click="function(e){ orderBy = e }" @on-visible-change="restOrderBy">
                            <span style="cursor: pointer;">
                                <Icon type="md-funnel" size="17" />
                                {{ orderByText }}
                                <Icon type="ios-arrow-down"></Icon>
                            </span>
                            <DropdownMenu slot="list">
                                <DropdownItem name="id">{{$t('schoolBaseInfo.listOrder1')}}</DropdownItem>
                                <DropdownItem name="state">{{$t('schoolBaseInfo.listOrder2')}}</DropdownItem>
                            </DropdownMenu>
                        </Dropdown>
                    </div>
                </div>
                <!-- 教室数据列表 -->
                <div class="class-list" id="class-list">
                    <vuescroll>
                        <div class="class-list-item" v-for="(item,index) in roomListShow" :key="index" @click="chooseClassroom(index)" :class="curRoomIndex == index ? 'block-bg block-bg-active':'block-bg'">
                            <div class="class-list-item-left">
                                <p class="class-name">
                                    <span class="class-id-tag">
                                        {{item.no}}
                                    </span>
                                    <span>
                                        {{item.name}}
                                    </span>
                                </p>
                                <p class="class-type">
                                    <!-- <template v-if="isSmart(item.id)">
                                        <v-icon class="iconHi" iconClass="htc" />
                                        <span>
                                            {{$t('schoolBaseInfo.tmdClass')}}
                                        </span>
                                    </template> -->
                                    <template>
                                        <div class="iconBoard">
                                            <v-icon iconClass="board" />
                                        </div>
                                        <span style="color:#a5a5a5;">
                                            {{ item.openType == '1' ? $t('schoolBaseInfo.roomType1') : $t('schoolBaseInfo.roomType2')}}
                                        </span>
                                    </template>
                                </p>
                            </div>
                        </div>
                        <EmptyData v-if="roomListShow.length == 0" style="padding-top:120px;"></EmptyData>
                    </vuescroll>
                </div>
            </div>
            <div class="class-info-wrap" slot="right">
                <!-- tab菜单 -->
                <div class="class-info-header common-save-btn">
                    <!-- 位置设定 暂时去掉-->
                    <!-- <span :class="currentTabIndex == 1 ? 'main-header-tab line-bottom line-bottom-active':'main-header-tab line-bottom'" @click="selectTab(1)">
                        {{$t('schoolBaseInfo.tab3')}}
                    </span> -->
                    <!-- hiteach关联 暂时去掉-->
                    <!-- <span :class="currentTabIndex == 3 ? 'main-header-tab line-bottom line-bottom-active':'main-header-tab line-bottom'" @click="selectTab(3)">
                        {{$t('schoolBaseInfo.tab4')}}
                    </span> -->
                    <!-- 课表 -->
                    <span :class="currentTabIndex == 4 ? 'main-header-tab line-bottom line-bottom-active':'main-header-tab line-bottom'" @click="selectTab(4)">
                        {{$t('schoolBaseInfo.cusTabel')}}
                    </span>
                    <!-- 编辑课表 -->
                    <span v-show="currentTabIndex == 4" v-if="$access.can('admin.*|course-upd')" class="save-btn" style="margin-top:0px;cursor: pointer;" @click="editCusTable()">
                        <Icon type="ios-settings" />
                        {{$t('schoolBaseInfo.setCusTable')}}
                    </span>
                </div>
                <div class="class-info-content">
                    <!-- 關聯 Hiteach -->
                    <div id="hiteach-link" style="height: 100%;" v-show="currentTabIndex == 3">
                        <!-- <HiTeachLink></HiTeachLink> -->
                    </div>
                    <!--平面位置-->
                    <div class="school-plan-wrap" v-show="currentTabIndex == 1">
                        <RoomMap></RoomMap>
                    </div>
                    <!--课程表-->
                    <div class="cus-table-wrap" v-show="currentTabIndex == 4">
                        <!-- 学段切换，只有大于一个学段才显示 -->
                        <div v-show="cusPds.length > 1">
                            <span v-for="(item,index) in cusPds" :key="index" @click="selectSub(index)" :class="[curPdIndex == index ? 'active-sub-item' : '','cus-sub-item']">
                                {{item.name}}
                            </span>
                        </div>
                        <ClassTable :style="{height: cusPds.length > 1 ? 'calc(100% - 30px)' : '100%'}" mode="view" v-if="this.roomListShow[this.curRoomIndex]" :schedData="roomCus" :roomId="roomListShow[curRoomIndex].id" :periodId="curPd">
                        </ClassTable>
                    </div>
                </div>
            </div>
        </Split>
        <!-- 创建教室表单 -->
        <Modal v-model="addRoomStatus" :title="room.id ? $t('schoolBaseInfo.editClassroom') : $t('schoolBaseInfo.addClassroom')" @on-ok="confirmAddRoom" :loading="mLoading">
            <Form ref="classInfo" :model="room" :rules="classValidate">
                <FormItem prop="name" :label="$t('schoolBaseInfo.classroomName')" @click.native.stop class="requird-color">
                    <span slot="label" class="class-attr-wrap-label">{{$t('schoolBaseInfo.classroomName')}}</span>
                    <Input @on-change="watchUpdate" :disabled="editStatus" v-model="room.name" clearable :placeholder="$t('schoolBaseInfo.classroomNameHolder')" />
                </FormItem>
                <FormItem prop="no" @click.native.stop class="requird-color">
                    <span slot="label" class="class-attr-wrap-label">{{$t('schoolBaseInfo.classroomCode')}}</span>
                    <Input @on-change="watchUpdate" :disabled="editStatus" v-model="room.no" clearable :placeholder="$t('schoolBaseInfo.classroomCodeHolder')" />
                </FormItem>
                <FormItem prop="openType" @click.native.stop class="requird-color">
                    <span slot="label" class="class-attr-wrap-label">{{$t('schoolBaseInfo.classAttr')}}</span>
                    <Select @on-change="watchUpdate" :disabled="editStatus" v-model="room.openType" clearable>
                        <Option v-for="(item,index) in attributeList" :value="item.value" :key="index">{{ item.label }}</Option>
                    </Select>
                </FormItem>
            </Form>
        </Modal>
    </div>
</template>

<script>
import '@/icons/svg/htc.svg'
import '@/icons/svg/htc_pro.svg'
import '@/icons/svg/htc_std.svg'
import '@/icons/svg/htc_tbl.svg'
import '@/icons/svg/board.svg'
import { mapGetters } from 'vuex'
import ClassTable from "@/view/newcourse/ClassTable.vue"
import RoomMap from "./RoomMap.vue"
import HiTeachLink from "./HiTeachLink.vue"
export default {
    components: { ClassTable, RoomMap, HiTeachLink },
    data() {
        let _this = this
        // 教室编码验证规则
        const validateCode = (rule, value, callback) => {
            // 验证必填
            if (!value) {
                return callback(new Error(this.$t('schoolBaseInfo.roomNoErr')))
            }
            //验证字符格式
            let zg = /^[0-9a-zA-Z]+$/
            if (!zg.test(value)) {
                callback(new Error(this.$t('schoolBaseInfo.roomNoErr1')))
            }
            // 验证重复编码
            let data = _this.roomList.filter(item => {
                return item.id !== _this.room.id
            })
            let allNo = data.map(item => {
                return item.no
            })
            if (allNo.includes(value)) {
                callback(new Error(this.$t('schoolBaseInfo.roomNoErr2')))
            }
            callback()
        }
        // 教室名称验证规则
        const validateName = (rule, value, callback) => {
            // 验证必填
            if (!value) {
                return callback(new Error(this.$t('schoolBaseInfo.nameWarning')))
            }
            // 验证重复编码
            let data = _this.roomList.filter(item => {
                return item.id !== _this.room.id
            })
            let names = data.map(item => {
                return item.name
            })
            if (names.includes(value)) {
                callback(new Error('教室名称重复'))
            }
            callback()
        }
        return {
            mLoading: true,
            roomCus: [],//教室课程信息
            split1: 0.2,
            room: {
                id: '',
                name: '',
                no: '',
                openType: ''
            },
            curPdIndex: 0,
            addRoomStatus: false,
            orderBy: 'id',
            updateBefore: '',
            curPd: undefined,
            editStatus: true,//可切换编辑状态
            noStatus: false,
            isSearch: false,
            currentTabIndex: 4,
            updated: false,
            roomListShow: [],
            curRoomIndex: 0,
            keyword: '',
            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, validator: validateName, trigger: 'change' }
                ],
                openType: [
                    { required: true, message: this.$t('schoolBaseInfo.typeWarning'), trigger: 'change' }
                ]
            },
        }
    },

    computed: {
        ...mapGetters({
            periods: 'user/getPeriods', // 學制s
            aprules: 'schoolBaseInfo/getAprules',
            roomList: 'user/getRooms',
        }),
        orderByText() {
            switch (this.orderBy) {
                case 'id':
                    return this.$t('schoolBaseInfo.listOrder1')
                    break;
                case 'state':
                    return this.$t('schoolBaseInfo.listOrder2')
                    break;
                case 'total':
                    return this.$t('依學生數排序')
                    break;
            }
        },
        //当前教室课程对应的学段
        cusPds() {
            if (this.roomCus && this.roomCus.length) {
                let data = this.roomCus.map(item => {
                    return item.period
                })
                //对象数组根据某个属性进行去重
                var obj = {}
                data = data.reduce((item, next) => {
                    obj[next.id] ? '' : obj[next.id] = true && item.push(next)
                    return item
                }, [])
                if (data.length) {
                    this.curPd = data[0].id
                }
                return data
            } else {
                this.curPd = ''
                return []
            }
        }
    },
    methods: {
        editClassroom() {
            this.room = this._.cloneDeep(this.roomListShow[this.curRoomIndex])
            this.addRoomStatus = true
        },
        selectSub(index) {
            this.curPdIndex = index
            this.curPd = this.cusPds[index].id
        },
        //前往编辑课表
        editCusTable() {
            this.$router.push({
                path: '/home/CoursePlan'
            })
        },
        //根据班级查询课程安排
        findClassCus() {
            if (this.roomListShow.length > 0) {
                let roomId = this.roomListShow[this.curRoomIndex].id
                let requestData = {
                    id: roomId,
                    code: this.$store.state.userInfo.schoolCode,
                    scope: 'school'
                }
                this.$api.courseMgmt.findCusByRoom(requestData).then(
                    (res) => {
                        if (!res.error) {
                            this.roomCus = res.courses
                            // this.$set(this.allClassCus, roomId, )
                            this.isLoading = false
                        } else {
                            this.$Message.error('API error!')
                            this.isLoading = false
                        }
                    },
                    (err) => {
                        this.isLoading = false
                    }
                )
            } else {
                this.isLoading = false
            }
        },
        restOrderBy(flag) {
            if (!flag) this.dataSort(this.roomListShow)
        },
        closeKeySearch() {
            this.isSearch = false
            this.keyword = ''
            this.filterClassname()
        },
        watchUpdate(data) {
            if (data) {
                this.updated = true
            }
        },
        dataSort(data) {
            console.log('排序方式', this.orderBy)
            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;
                        }
                        return 0;
                    })
                    break;
                case 'state': // 智慧教室排序
                    data.sort(function (a, b) {
                        if (a.style == 'smart') {
                            return -1
                        } else {
                            return 1
                        }
                    })
                    break; // 學生總數排序
                default:
                    break
            }
            return data
        },
        filterClassname() {
            console.log('初始化')
            if (!this.keyword) {
                this.roomListShow = [...this.roomList]
            } else {
                this.roomListShow = this.roomList.filter(item => item.name.indexOf(this.keyword) != -1)
            }
            // 排序
            this.roomListShow = this.dataSort(this.roomListShow)
            this.curRoomIndex = 0
            this.updateBefore = JSON.stringify(this.roomListShow[this.curRoomIndex])
        },
        selectTab(index) {
            this.currentTabIndex = index
            if (index == 4) {
                this.findClassCus()
            }
        },
        saveClassroom() {
            this.roomListShow[this.curRoomIndex]['code'] = this.$store.state.userInfo.schoolCode
            this.$api.room.RoomUpsert(this.roomListShow[this.curRoomIndex]).then(
                res => {
                    if (res) {
                        if (res.error) {
                            this.$Message.error(res.v)
                        } else {
                            this.$Message.success(this.$t('schoolBaseInfo.csTips3'))
                            this.updated = false
                            this.updHiteachLink = []
                            this.roomListShow[this.curRoomIndex].code = 'Class-' + this.roomListShow[this.curRoomIndex].code
                            // this.roomList.unshift(this.roomListShow[this.curRoomIndex])
                            // this.$store.dispatch('user/addSchoolRoom', this.roomListShow[this.curRoomIndex])
                        }
                    } else {
                        this.$Message.error('API error!')
                    }
                },
                err => {
                    this.$Message.error('API error!')
                }
            )
        },
        /**显示确认删除班级对话框 */
        showConfirmDelete() {
            if (this.$access.can('admin.*|classroom-upd')) {
                this.$Modal.confirm({
                    title: this.$t('schoolBaseInfo.delClass'),
                    content: this.$t('schoolBaseInfo.delete') + this.roomListShow[this.curRoomIndex].name + this.$t('schoolBaseInfo.delContent'),
                    onOk: () => {
                        this.delClassroom(this.curRoomIndex)
                    }
                })
            } else {
                this.$Message.warning(this.$t('schoolBaseInfo.authWarning'))
            }
        },
        delClassroom(index) {
            let roomId = this.roomListShow[index].id
            let requestData = {
                id: roomId,
                code: this.$store.state.userInfo.schoolCode
            }
            this.$api.room.DelRoom(requestData).then(
                res => {
                    this.curRoomIndex = 0
                    this.$Message.success(this.$t('schoolBaseInfo.csTips7'))
                    for (let i in this.roomList) {
                        if (this.roomList[i].id == roomId) {
                            this.roomList.splice(i, 1)
                            break
                        }
                    }
                    this.$store.dispatch('user/delSchoolRoom', roomId)
                    this.roomListShow.splice(index, 1)
                },
                err => {
                    this.$Message.error('API error!')
                }
            )
        },

        chooseClassroom(index) {
            if (this.updated) {
                let config = {
                    title: this.$t('schoolBaseInfo.saveWarning'),
                    content: this.$t('schoolBaseInfo.saveClassWarning'),
                    okText: this.$t('schoolBaseInfo.leaveText'),
                    onOk: () => {
                        if (this.roomListShow[this.curRoomIndex].option == 'insert') {
                            this.delClassroom(this.curRoomIndex)
                        } else {
                            this.updated = false
                            this.updHiteachLink = []
                            this.$set(this.roomListShow, this.curRoomIndex, JSON.parse(this.updateBefore))
                            this.curRoomIndex = index
                            this.updateBefore = JSON.stringify(this.roomListShow[this.curRoomIndex])
                        }
                    }
                }
                this.$Modal.confirm(config)
            } else {
                this.curRoomIndex = index
                this.updateBefore = JSON.stringify(this.roomListShow[this.curRoomIndex])
            }
            if (this.currentTabIndex == 4) {
                this.findClassCus()
            }
        },
        addClassroom() {
            this.addRoomStatus = true
        },
        confirmAddRoom() {
            this.$refs['classInfo'].validate((valid) => {
                if (valid) {
                    this.room.code = this.$store.state.userInfo.schoolCode
                    this.$api.room.RoomUpsert(this.room).then(
                        res => {
                            if (!res.error) {
                                this.$Message.success(this.$t('schoolBaseInfo.csTips3'))
                                //修改
                                if (this.room.id) {
                                    this.$store.commit('user/updRoom', res.room)
                                    let index = this.roomListShow.findIndex(item => {
                                        return item.id == this.room.id
                                    })
                                    if (index > -1) {
                                        this.roomListShow.splice(index, 1, res.room)
                                    }
                                }
                                // 新增
                                else {
                                    this.roomListShow.unshift(this._.cloneDeep(res.room))
                                    this.roomList.unshift(this.roomListShow[this.curRoomIndex])
                                    this.$store.dispatch('user/addSchoolRoom', res.room)
                                }
                                this.updated = false
                                this.addRoomStatus = false
                            } else {
                                this.$Message.error('API error!')
                            }
                        },
                        err => {
                            this.$Message.error('API error!')
                        }
                    ).finally(
                        () => {
                            this.room = {
                                id: '',
                                name: '',
                                no: '',
                                openType: ''
                            }
                        }
                    )
                } else {
                    this.$Message.error(this.$t('schoolBaseInfo.fullRoomInfo'));
                    this.mLoading = false
                    setTimeout(() => {
                        this.mLoading = true
                    }, 0)
                }
            })
        }
    },
    mounted() {
        this.filterClassname()
        this.chooseClassroom(0)
    },
    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() {
        if (this.$access.can('admin.*|classroom-upd')) this.editStatus = this.noStatus
    }
}
</script>
<style lang="less" scoped>
@import "./RoomMgt.less";
</style>
<style>
.cus-table-wrap .cus-table-container {
    padding-top: 5px;
}
.class-room-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;
}

.hiteach-code-wrap-header .ivu-input {
    width: 110px;
    /* color: white; */
    font-size: 15px;

    background: none;
    /* color: white; */
    /* border-color: #606060; */
}

.class-attr-wrap .ivu-input {
    width: calc(100% - 10px);
    background: var(--input-bg-color);
    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; */
}

.school-plan-wrap .ivu-upload {
    position: absolute;
    top: 2px;
    right: 4px;
    color: white;
    cursor: pointer;
}

.school-plan-wrap .ivu-btn {
    background: none;
    border: none;
    color: white;
    padding: 8px 35px 6px 20px;
    border-radius: 0px;
    font-size: 14px;
}

.school-plan-wrap .ivu-upload-list {
    display: none;
}
</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 {
    .ivu-tag-border {
        background: transparent !important;
        margin-right: 10px;
        border-radius: 5px;
        letter-spacing: 1px;
    }
}
</style>