<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>
                <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% - 100px);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-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;color:white;">
                            <Icon type="md-funnel" color="white" 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>
                            <!--<DropdownItem name="total">依學生數排序</DropdownItem>-->
                        </DropdownMenu>
                    </Dropdown>
                </div>
            </div>
            <div class="class-list" id="class-list">
                <vuescroll>
                    <div class="class-list-item" v-for="(item,index) in classroomListShow" :key="index" @click="chooseClassroom(index)" :class="curClassIndex == index ? 'block-bg block-bg-active':'block-bg'">
                        <div class="class-list-item-left">
                            <p style="color: #a5a5a5;">{{$jsFn.getGradeName(schoolBase,item.gradeId)}}</p>
                            <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 v-else>
                                    <div class="iconBoard">
                                        <v-icon iconClass="board" style="color:#333;" />
                                    </div>
                                    <span style="color:#a5a5a5;">
                                        {{$t('schoolBaseInfo.normalClass')}}
                                    </span>
                                </template>
                            <p class="second-text-color" v-if="item.openType == '1'">
                                <span>{{ $t('schoolBaseInfo.headmaster') }}</span>
                                <span class="primary-text-color">{{item.teacher.name}}</span>
                            </p>
                            <p class="second-text-color" v-else>
                                <span class="primary-text-color">{{$t('schoolBaseInfo.dClass')}}</span>
                            </p>
                        </div>
                    </div>
                    <EmptyData v-if="classroomListShow.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>
                <span :class="currentTabIndex == 1 ? 'main-header-tab line-bottom line-bottom-active':'main-header-tab line-bottom'" @click="selectTab(1)">
                    {{$t('schoolBaseInfo.tab3')}}
                </span>
                <span :class="currentTabIndex == 3 ? 'main-header-tab line-bottom line-bottom-active':'main-header-tab line-bottom'" @click="selectTab(3)">
                    {{$t('schoolBaseInfo.tab4')}}
                </span>
                <!-- 编辑教室 -->
                <Button v-if="$access.can('admin.*|classroom-upd')" 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="classroomListShow[curClassIndex]" ref="classInfo" :model="classroomListShow[curClassIndex]" :rules="classValidate" style="padding-top:20px;">
                                <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="classroomListShow[curClassIndex].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="classroomListShow[curClassIndex].no" clearable :placeholder="$t('schoolBaseInfo.classroomCodeHolder')" />
                                </FormItem>
                                <FormItem prop="gradeId" :label="$t('schoolBaseInfo.setGrade')" @click.native.stop class="requird-color">
                                    <span slot="label" class="class-attr-wrap-label">{{$t('schoolBaseInfo.setGrade')}}</span>
                                    <Select @on-change="watchUpdate" :disabled="editStatus" v-model="classroomListShow[curClassIndex].gradeId" clearable>
                                        <Option v-for="(item,index) in $jsFn.getPeriod($store.state.user.schoolProfile.school_base,classroomListShow[curClassIndex].periodId).grades" :value="item.id" :key="index">
                                            {{ item.name }}
                                        </Option>
                                    </Select>
                                </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="classroomListShow[curClassIndex].openType" clearable>
                                        <Option v-for="(item,index) in attributeList" :value="item.value" :key="index">{{ item.label }}</Option>
                                    </Select>
                                </FormItem>
                                <FormItem prop="teacher" :label="$t('schoolBaseInfo.headmaster')" @click.native.stop class="requird-color" v-if="classroomListShow[curClassIndex].openType == '1'">
                                    <span slot="label" class="class-attr-wrap-label">{{$t('schoolBaseInfo.headmaster')}}</span>
                                    <Select @on-change="watchUpdate" :disabled="editStatus" v-model="classroomListShow[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="classroomListShow[curClassIndex].teacher = {id:item.id, name:item.name}">
                                            {{ item.name }}
                                        </Option>
                                    </Select>
                                </FormItem>
                            </Form>
                        </vuescroll>
                    </div>
                </div>
              

                <!-- 關聯 Hiteach -->
                <div id="hiteach-link" style="height: 100%;" v-show="currentTabIndex == 3">
                    <div class="hiteach-code-wrap">
                        <Loading v-show="hiteachListLoading"></Loading>
                        <div class="hiteach-code-wrap-header">
                            <!-- <p>
                                {{$t('schoolBaseInfo.relationHi')}}
                            </p> -->
                            <div class="class-list-filter">
                                <div class="class-list-filter-box">
                                    <Dropdown class="sort-dropdown" trigger="click" placement="bottom-start" @on-click="function(e){ filterHiteachVer = e }">
                                        <span v-if="filterHiteachVer == 'ALL'" style="cursor: pointer;color:white;"> {{ $t('schoolBaseInfo.hiFilter1') }} <Icon type="ios-arrow-down"></Icon></span>
                                        <span v-else-if="filterHiteachVer == 'J223IZ6M'" style="cursor: pointer;color:white;"> {{ $t('schoolBaseInfo.hiFilter2') }} <Icon type="ios-arrow-down"></Icon></span>
                                        <span v-else-if="filterHiteachVer == 'J223IZAM'" style="cursor: pointer;color:white;"> {{ $t('schoolBaseInfo.hiFilter3') }} <Icon type="ios-arrow-down"></Icon></span>
                                        <span v-else-if="filterHiteachVer == '3222C6D2'" style="cursor: pointer;color:white;"> {{ $t('schoolBaseInfo.hiFilter4') }} <Icon type="ios-arrow-down"></Icon></span>
                                        <DropdownMenu slot="list">
                                            <DropdownItem name="ALL">{{ $t('schoolBaseInfo.hiFilter1') }}</DropdownItem>
                                            <DropdownItem name="J223IZ6M">{{ $t('schoolBaseInfo.hiFilter2') }}</DropdownItem>
                                            <DropdownItem name="J223IZAM">{{ $t('schoolBaseInfo.hiFilter3') }}</DropdownItem>
                                            <DropdownItem name="3222C6D2">{{ $t('schoolBaseInfo.hiFilter4') }}</DropdownItem>
                                        </DropdownMenu>
                                    </Dropdown>
                                    <div class="dark-iview-input" style="padding-right:10px;">
                                        <Input clearable v-model="serchCode" size="small" suffix="ios-search"></Input>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="hiteach-code-wrap-list">
                            <vuescroll >
                                <div class="hiteach-collapse" v-for="(item, index) in showHiteachData" :key="index">
                                    <div @click="openHiSub(index)" class="hiteach-collapse-main">
                                        <Icon class="arrowIcon" v-if="item.deviceMax > 1" :type="item.subOpen ? 'ios-arrow-up' : 'ios-arrow-down'" size="30" color="white" />
                                        <v-icon v-if="item.prodCode == 'J223IZ6M'" class="proIcon" iconClass="htc_std" />
                                        <v-icon v-else-if="item.prodCode == '3222C6D2'" class="proIcon" iconClass="htc_tbl" />
                                        <v-icon v-else-if="item.prodCode == 'J223IZAM'" class="proIcon" iconClass="htc_pro" />
                                        <div class="proCont">
                                            <ul>
                                                <li>
                                                    <h1 class="title">
                                                        {{ $t('schoolBaseInfo.' + item.prodCode)}}
                                                    </h1>
                                                    <span class="serialType">
                                                        {{ item.deviceMax == 1 ? $t('schoolBaseInfo.single') : $t('schoolBaseInfo.mach')}}
                                                    </span>
                                                    <span style="color: #1cc0f3;font-size:12px">
                                                        <!-- 要增加被關聯了幾個 -->
                                                        {{ item.deviceBound ? item.linkCount + ' / '+item.deviceMax : '-- / -- '}}
                                                    </span>
                                                </li>
                                                <li><span style="color: #1cc0f3;">{{ item.serial }}</span></li>
                                                <li style="display: block;">
                                                    <div v-for="(aprule, index) in aprules" :key="index" class="tag" :class="{active: item.aprule ? item.aprule[aprule] : false}">{{ $t('schoolBaseInfo.'+ aprule)}}</div>
                                                </li>
                                                <li><span style="color: #8d8d8d;">{{$t('schoolBaseInfo.expireLabel')}}： </span>{{item.endDate | timeFmt}}</li>
                                            </ul>
                                        </div>
                                    </div>
                                    <div v-if="item.subOpen" id="hiteach-1">
                                        <template v-if="item.deviceBound.length >0">
                                            <div v-for="(dbItem, dbIndex) in item.deviceBound" :key="dbIndex" class="hiteach-collapse-sub gradient" :class="{'linked': dbItem.classId != '' && dbItem.classId != null && classroomListShow[curClassIndex].id != dbItem.classId}">
                                                <!-- 被關聯 disabled -->
                                                <Button class="hiteach-collapse-sub-linkBtn" v-model="dbItem.hiteachLink" @click="confirmLink(dbItem.hiteachLink, item.id, dbItem.uuid, dbItem.uuid2, classroomListShow[curClassIndex].id)" >{{ dbItem.hiteachLink ? $t('schoolBaseInfo.deLink') : $t('schoolBaseInfo.link') }}</Button>
                                                <!-- <Checkbox :id="'checkbox-' + (dbItem.uuid + dbItem.uuid2)" @on-change="whatUpdHiLink(dbItem, classroomListShow[curClassIndex].id, item.id)" style="margin-right: 70px;" v-model="dbItem.hiteachLink" :disabled="dbItem.classId != '' && dbItem.classId != null && classroomListShow[curClassIndex].id != dbItem.classId"></Checkbox> -->
                                                <div class="hiteach-collapse-sub-detail">
                                                    <ul>
                                                        <li>
                                                            <h3>{{ dbItem.pcname }}</h3>
                                                        </li>
                                                        <li>
                                                            <span>{{ dbItem.ip }} {{ dbItem.ip && (dbItem.uuid || dbItem.uuid2) ? '|' : '' }} {{ dbItem.uuid }} {{ dbItem.uuid && dbItem.uuid2 ? '|' : '' }} {{ dbItem.uuid2 }}</span>
                                                        </li>
                                                        <li>
                                                            <span>
                                                                {{ dbItem.os }}
                                                            </span>
                                                        </li>
                                                    </ul>
                                                    <span v-if="dbItem.classId && classroomListShow[curClassIndex].id != dbItem.classId" style="color: #1cc0f3;padding: 0 15px;">
                                                        {{$t('schoolBaseInfo.related')}}
                                                    </span>
                                                </div>
                                            </div>
                                        </template>
                                        <template v-else>
                                            <div class="hiteach-collapse-sub gradient" style="display: flex;align-items: center;border-top: 1px solid rgb(66, 66, 66);margin-left: 20px;letter-spacing: 1px;font-size: 12px;padding: 20px;">
                                                <span style="margin-right: 70px;"></span>
                                                <div style="display: flex;justify-content: space-between;align-items: center;width: 100%;color: #8d8d8d">
                                                    {{$t('schoolBaseInfo.noEnable')}}
                                                </div>
                                            </div>
                                        </template>
                                    </div>
                                </div>
                            </vuescroll>
                        </div>
                    </div>
                </div>

                <!--平面位置-->
                <div class="school-plan-wrap" v-show="currentTabIndex == 1">
                    <Upload action="" :on-success="uploadSchoolPlan" :before-upload="getFileData">
                        <Button icon="ios-cloud-upload-outline">{{$t('schoolBaseInfo.uploadPlan')}}</Button>
                    </Upload>
                    <div class="school-plan-zoom">
                        <span @click="defaultSize()">1:1</span>
                        <Icon type="ios-add-circle-outline" color="white" size="24" @click="bigger()" />
                        <Icon type="ios-remove-circle-outline" color="white" size="24" @click="smaller()" />
                    </div>
                    <div class="school-plan-box" id="school-plan-box">
                        <canvas id="school-plan" style="cursor:move;" @mousedown="canvasMouseDown" @mousemove="canvasMouseMove" @mouseup="canvasMouseUp" @mouseout="canvasMouseOut">
                            {{$t('schoolBaseInfo.suportCanvas')}}
                        </canvas>
                    </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="classroomListShow[curClassIndex] && classroomListShow[curClassIndex].openType == '1'">
                        <Table :columns="studentColumn" :data="students" @on-selection-change="(selections)=>{delSelections = selections}" :height="tableHeight" class="system-classroom-table" :loading="stuLoading" no-data-text="暂无学生">
                            <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>
                            <!-- <template slot-scope="{ row, index }" slot="groupId">
                                <span>{{row.groupId ? row.groupId : '- -'}}</span>
                            </template>
                            <template slot-scope="{ row, index }" slot="groupName">
                                <span>{{row.groupName ? row.groupName : '未分组'}}</span>
                            </template> -->
                        </Table>
                    </vuescroll>
                    <h2 v-else style="text-align:center;color:#cccccc;width:100%;padding-top:80px;">{{$t('schoolBaseInfo.onClassStu')}}</h2>
                </div>
            </div>
        </div>
        <!-- 原来可以创建序号，如果现在调整序列号部分后不需要添加可以删除相关代码 -->
        <Modal v-model="addCode" :title="$t('schoolBaseInfo.addCodeTitle')" @on-ok="confirmAdd" class-name="dark-iview-modal dark-iview-form">
            <Form :model="hiTeachItem" :label-width="80" label-position="left">
                <FormItem :label="$t('schoolBaseInfo.hiTeach')">
                    <Input v-model="hiTeachItem.code" :placeholder="$t('schoolBaseInfo.codeHolder')"></Input>
                </FormItem>
                <FormItem :label="$t('schoolBaseInfo.moreAuth')">
                    <Select v-model="hiTeachItem.single">
                        <Option value="1">{{$t('schoolBaseInfo.yes')}}</Option>
                        <Option value="0">{{$t('schoolBaseInfo.no')}}</Option>
                    </Select>
                </FormItem>
            </Form>
        </Modal>
        <Modal v-model="addStuStatus" title="添加学生" width="1200" @on-ok="confirmAddStu" class-name="dark-iview-modal">
            <StudentList @getSelectInfo="(selction)=>{selections = selction}"></StudentList>
        </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 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-9a-zA-Z]+$/
            if (zg.test(value)) {
                callback()
            } else {
                callback(new Error(this.$t('schoolBaseInfo.classNoErr1')))
            }
        }
        return {
            studentColumn: [
                {
                    title: ' ',
                    type: 'selection',
                    width: 60,
                    align: 'center'
                },
                {
                    title: ' ',
                    slot: 'picture',
                    align: 'left ',
                    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: this.$t('courseManage.classroom.studentTableC5'),
                //     slot: 'groupId',
                //     align: 'center',
                //     sortable: true
                // },
                // {
                //     title: this.$t('courseManage.classroom.studentTableC6'),
                //     slot: 'groupName',
                //     align: 'center'
                // }
                {
                    title: ' ',
                    slot: 'action',
                    align: 'left ',
                    width: '150'
                },
            ],
            editIndex: -1,
            resetNoBef: 0,
            updHiteachLink: [],
            orgHiteachData: [],
            hiteachData: [],
            schoolBase: {
                period: []
            },
            delSelections: [],//需要移除的学生
            selections: [],//添加的学生
            addStuStatus: false,
            stuLoading: false,
            orderBy: 'id',
            filterHiteachVer: 'ALL',
            updateBefore: '',
            updateBeforebyHiteach: '',
            filterPeriod: undefined,
            editStatus: true,//可切换编辑状态
            noStatus: false,
            isSearch: false,
            currentTabIndex: 0,
            isListLoading: false,
            isSaveLoading: false,
            hiteachListLoading: true,
            addCode: false,
            isInit: true,
            updated: false,
            hiTeachsShow: [],
            hiTeachs: [],
            classroomList: [],
            classroomListShow: [],
            curClassIndex: 0,
            schoolPlan: '',
            point: {},
            clickPoint: {},
            isMouseDown: false,
            isFirstDraw: 0,
            schoolImageData: [],
            pinImageData: {},
            whiteImageData: {},
            greenImageData: {},
            activeIcon: -1,
            textStatus: true,
            keyword: '',
            serchCode: '',
            scaleDefault: 1,
            maxScale: 3,
            minScale: 0.4,
            scaleStep: 0.1,
            stopScale: false,
            hiTeachItem: {
                code: '',
                single: undefined,
                using: 0
            },
            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' }
                ],
                gradeId: [
                    { required: true, message: this.$t('schoolBaseInfo.gradeWarning'), trigger: 'change' }
                ]
            },
        }
    },
    filters: {
        timeFmt: function (val) {
            if (val == 0 || val == 1) {
                return val == 0 ? this.$t('schoolBaseInfo.expireLabel1') : this.$t('schoolBaseInfo.expireLabel2')
            } else {
                if (val.toString().length < 13) val = val * 1000
                let d = new Date(val),
                    month = '' + (d.getMonth() + 1),
                    day = '' + d.getDate(),
                    year = d.getFullYear();

                if (month.length < 2)
                    month = '0' + month;
                if (day.length < 2)
                    day = '0' + day;

                return [year, month, day].join('/');
            }
        }
    },
    computed: {
        ...mapGetters({
            periods: 'user/getPeriods', // 學制s
            aprules: 'schoolBaseInfo/getAprules',
        }),
        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
        },
        orderByText: function () {
            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;
            }
        },
        showHiteachData: function () {
            let data = this.hiteachData
            let filterText = this.filterHiteachVer
            let nowSeletedClassId = null
            if(this.classroomListShow.length > 0){
                nowSeletedClassId = this.classroomListShow[this.curClassIndex].id
            }

            if(nowSeletedClassId != null && this.isSmart(nowSeletedClassId)){
                
                // 篩選有 deviceBound 且classID 和現在的教室相同的
                data = data.filter(item => {
                    return Array.isArray(item.deviceBound) && item.deviceBound.length > 0 && item.deviceBound.some(s => { return s.classId == nowSeletedClassId })
                })

                // 整形 拿掉不相關的
                data = data.map(item => {
                    let newD = item
                    newD.deviceBound = newD.deviceBound.filter( f => {
                        return f.classId != null && f.classId != ''
                    })
                    return newD
                })
            } else {
                // 整形 拿掉沒被關聯的
                data = data.map(item => {
                    let newD = item
                    if(Array.isArray(item.deviceBound) && item.deviceBound.length > 0){
                        newD.deviceBound = newD.deviceBound.filter( f => {
                            return f.classId == null || f.classId == ''
                        })
                    }
                    return newD
                })
            }
                    

            if (Array.isArray(data) && data.length > 0 && filterText != 'ALL') {
                data = data.filter(item => {
                    return item.prodCode == filterText
                })
            }

            if (this.serchCode != '') {
                let serchCode = this.serchCode.toUpperCase()
                data = data.filter((item, index) => {
                    let verName = this.$t('schoolBaseInfo.' + item.prodCode)
                    let pcNames = false;

                    if (Array.isArray(item.deviceBound) && item.deviceBound.length > 0) {
                        pcNames = item.deviceBound.some(db => {
                            if (db.pcname) {
                                return db.pcname.toUpperCase().indexOf(serchCode) != -1
                            } else {
                                return false
                            }

                        })
                    }

                    return item.serial.toUpperCase().indexOf(serchCode) != -1 || verName.toUpperCase().indexOf(serchCode) != -1 || pcNames
                })
            }

            return data
        },
        students() {
            if (this.currentTabIndex == '2') {
                if (this.classroomListShow[this.curClassIndex] && this.classroomListShow[this.curClassIndex].students) {
                    return this.classroomListShow[this.curClassIndex].students
                } else {
                    let params = {
                        'school_code': this.$store.state.userInfo.schoolCode,
                        'id': this.classroomListShow[this.curClassIndex].id,
                        'scope': 'school'
                    }
                    this.stuLoading = true
                    this.$api.schoolSetting.getClassroomStudent(params).then(
                        res => {
                            if (res.classrooms.length > 0) {
                                this.$set(this.classroomListShow[this.curClassIndex], 'students', res.classrooms[0].students)
                            }
                        },
                        err => {
                            this.$Message.error(this.$t('schoolBaseInfo.findStuErr'))
                        }
                    ).finally(()=>{
                        this.stuLoading = false
                    })
                }
            } else {
                return []
            }
        }
    },
    methods: {
        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: []
            }
            if (index > -1) {
                requestParams.students.push(this.students[index])
            } else if (this.delSelections.length > 0) {
                requestParams.students = this.delSelections
            }
            if (requestParams.students.length) {
                let names = requestParams.students.map(item => {
                    return item.name
                })
                this.$Modal.confirm({
                    title: this.$t('schoolBaseInfo.removeTile'),
                    content: `${this.$t('schoolBaseInfo.removeContent')}${names.join(', ')}?`,
                    onOk: () => {
                        this.$Message.warning('暂未对接API')
                        // this.$api.stuAccount.removeStudent(requestParams).then(
                        //     res => {
                        //         this.$Message.success(this.$t('schoolBaseInfo.removeOk'))
                        //     },
                        //     err => {
                        //         this.$Message.error(this.$t('schoolBaseInfo.removeErr'))
                        //     }
                        // )
                    }
                })
            }
        },
        //确认添加学生
        confirmAddStu() {
            if (this.selections.length > 0) {
                console.log(this.selections)
                this.$Message.warning('暂未对接API')
                //保存操作
                // this.listLoading = true
                // this.courseListP[this.curCusIndex].code = this.$store.state.userInfo.TEAMModelId
                // this.$api.schoolSetting.classUpsert({
                //     classroom: this.courseListP[this.curCusIndex].classes[this.curClassIndex],
                //     option: 'update',
                //     'school_code': this.$store.state.userInfo.TEAMModelId
                // }).then(
                //     (res) => {
                //         if (!res.error) {
                //             this.selections.length = 0
                //             this.$Message.success('添加成功！')
                //         } else {
                //             this.$Message.error('添加失败！')
                //         }
                //     },
                //     (err) => {
                //         this.$Message.error('添加失败！')
                //     }
                // ).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': // ID 排序
                    data.sort(function (a, b) {
                        let nameA = a.id.toUpperCase(); // ignore upper and lowercase
                        let nameB = b.id.toUpperCase(); // ignore upper and lowercase
                        if (nameA < nameB) {
                            return -1;
                        }
                        if (nameA > nameB) {
                            return 1;
                        }

                        // names must be equal
                        return 0;
                    })
                    break;
                case 'state': // 智慧教室排序
                    data.sort(function (a, b) {
                        if (a.style == 'smart') {
                            return 1
                        } else {
                            return -1
                        }
                    })
                    break; // 學生總數排序
                case 'total':
                    data.sort(function (a, b) {
                        return b.studCount - a.studCount;
                    })
                    break;
            }
            return data
        },
        filterByPeriod() {
            this.curClassIndex = 0
            if (this.filterPeriod) {
                this.classroomListShow = this.classroomList.filter(item => item.periodId == this.filterPeriod || !item.periodId)
            } else {
                this.classroomListShow = [...this.classroomList]
            }
            // 排序
            this.classroomListShow = this.dataSort(this.classroomListShow)

            this.$nextTick(() => {
                this.drawSchoolPlan('')
                this.initIcon()
            })
        },
        filterClassname() {
            if (this.keyword == '' || this.keyword == undefined) {
                this.filterByPeriod()
            } else {
                let filterRes = []
                if (this.filterPeriod) {
                    filterRes = this.classroomList.filter(item => item.periodId == this.filterPeriod)
                } else {
                    filterRes = [...this.classroomList]
                }
                this.classroomListShow = filterRes.filter(item => item.name.indexOf(this.keyword) != -1)
                // 排序
                this.classroomListShow = this.dataSort(this.classroomListShow)
                this.curClassIndex = 0
                this.updateBefore = JSON.stringify(this.classroomListShow[this.curClassIndex])
            }
        },
        selectTab(index) {
            this.currentTabIndex = index
            if (index == 1) {
                this.bundleScoll()
            }
        },
        confirmAdd() {
            this.hiTeachs.push(this.hiTeachItem)
            this.hiTeachItem = {
                code: '',
                single: undefined,
                using: 0
            }
        },
        bundleScoll() {
            let schoolPlanBox = document.getElementById('school-plan-box')
            let _this = this
            schoolPlanBox.addEventListener('mousewheel', function (e) {
                if (e.preventDefault) {
                    e.preventDefault()
                } else {
                    window.event.returnValue == false
                }
                _this.scrollFunc(e)
            }, false) || schoolPlanBox.addEventListener('DOMMouseScroll', function (e) {
                if (e.preventDefault) {
                    e.preventDefault()
                } else {
                    window.event.returnValue == false
                }
                _this.scrollFunc(e)
            }, false)
        },
        scrollFunc(e) {
            e = e || window.event
            if (e.wheelDelta) { // 判断浏览器IE，谷歌滑轮事件
                if (e.wheelDelta > 0) { // 当滑轮向上滚动时
                    this.bigger()
                }
                if (e.wheelDelta < 0) { // 当滑轮向下滚动时
                    this.smaller()
                }
            } else if (e.detail) { // Firefox滑轮事件
                if (e.detail > 0) { // 当滑轮向上滚动时
                    this.bigger()
                }
                if (e.detail < 0) { // 当滑轮向下滚动时
                    this.smaller()
                }
            }
        },
        defaultSize() {
            this.scaleDefault = 1
            this.repaint(this.scaleDefault)
        },
        bigger() {
            if (this.scaleDefault + this.scaleStep > this.maxScale) {
                if (!this.stopScale) {
                    this.$Message.warning(this.$t('schoolBaseInfo.csTips1'))
                    this.stopScale = true
                }
            } else {
                this.stopScale = false
                this.scaleDefault += this.scaleStep
                this.repaint(this.scaleDefault)
            }
        },
        smaller() {
            if (this.scaleDefault - this.scaleStep < this.minScale) {
                if (!this.stopScale) {
                    this.$Message.warning(this.$t('schoolBaseInfo.csTips2'))
                    this.stopScale = true
                }
            } else {
                this.stopScale = false
                this.scaleDefault -= this.scaleStep
                this.repaint(this.scaleDefault)
            }
        },
        repaint(scale) {
            this.schoolPlan = document.getElementById('school-plan')
            this.schoolPlan.height = this.schoolImageData.height * this.scaleDefault
            this.schoolPlan.width = this.schoolImageData.width * this.scaleDefault
            this.drawSchoolPlan('imgUrl')
            this.initIcon()
        },

        drawText(text, x, y) {
            this.schoolPlan = document.getElementById('school-plan')
            let ctx = this.schoolPlan.getContext('2d')
            ctx.font = '16px Arial'
            ctx.fillStyle = 'yellow'
            ctx.fillText(text, x, y)
        },
        drawIcon(x, y) {
            this.schoolPlan = document.getElementById('school-plan')
            let ctx = this.schoolPlan.getContext('2d')
            ctx.beginPath()
            ctx.drawImage(this.whiteImageData, x * this.scaleDefault, y * this.scaleDefault, 20 * this.scaleDefault, 20 * this.scaleDefault)
        },
        moveIcon(x, y) {
            this.schoolPlan = document.getElementById('school-plan')
            let ctx = this.schoolPlan.getContext('2d')
            let _this = this
            for (let i = 0; i < _this.classroomListShow.length; i++) {
                if (this.activeIcon == i) {
                    ctx.drawImage(this.greenImageData, x * _this.scaleDefault, y * _this.scaleDefault, 20 * _this.scaleDefault, 20 * _this.scaleDefault)
                    this.updated = true
                } else {
                    ctx.drawImage(this.whiteImageData, _this.classroomListShow[i].x * _this.scaleDefault, _this.classroomListShow[i].y * _this.scaleDefault, 20 * _this.scaleDefault, 20 * _this.scaleDefault)
                }
            }
        },
        initIcon() {
            this.schoolPlan = document.getElementById('school-plan')
            let ctx = this.schoolPlan.getContext('2d')
            for (let i = 0; i < this.classroomListShow.length; i++) {
                let icon = i == this.curClassIndex ? this.greenImageData : this.whiteImageData
                if (icon.complete) {
                    ctx.drawImage(icon,
                        this.classroomListShow[i].x * this.scaleDefault, this.classroomListShow[i].y * this.scaleDefault,
                        20 * this.scaleDefault, 20 * this.scaleDefault)
                }
            }
        },
        checkActivieIcon(point) {
            for (let item in this.classroomListShow) {
                if (point.x > this.classroomListShow[item].x * this.scaleDefault && point.x < (this.classroomListShow[item].x + 15) * this.scaleDefault && point.y > this.classroomListShow[item].y * this.scaleDefault && point.y < (this.classroomListShow[item].y + 15) * this.scaleDefault) {
                    return item
                }
            }
            return -1
        },
        getCanvasPoint(x, y) {
            this.schoolPlan = document.getElementById('school-plan')
            let canvasRect = this.schoolPlan.getBoundingClientRect()
            let ctx = this.schoolPlan.getContext('2d')
            return {
                x: x - canvasRect.left,
                y: y - canvasRect.top
            }
        },
        canvasMouseDown(e) {
            this.point = this.getCanvasPoint(e.clientX, e.clientY)
            this.clickPoint = this.getCanvasPoint(e.clientX, e.clientY)
            this.activeIcon = this.checkActivieIcon(this.point)
            if (this.activeIcon != -1 && this.activeIcon != this.curClassIndex) {
                this.$Message.warning(this.$t('schoolBaseInfo.noStdClass'))
                this.activeIcon = -1
            } else {
                this.isMouseDown = true
            }
        },
        moveCanvas(start, current) {
            let container = document.getElementById('school-plan-box')
            container.scrollLeft = container.scrollLeft + (start.x - current.x)
            container.scrollTop = container.scrollTop + (start.y - current.y)
        },
        canvasMouseMove(e) {
            this.point = this.getCanvasPoint(e.clientX, e.clientY)
            if (this.isMouseDown == true && this.activeIcon != -1) {
                this.drawSchoolPlan('')
                this.moveIcon(this.point.x / this.scaleDefault, this.point.y / this.scaleDefault)
            } else if (this.isMouseDown == true && this.activeIcon == -1) {
                this.moveCanvas(this.clickPoint, this.point)
            } else {
                let index = this.checkActivieIcon(this.point)
                if (index != -1) {
                    if (this.textStatus == true) {
                        this.drawText(this.classroomListShow[index].name, (this.classroomListShow[index].x + 25) * this.scaleDefault, (this.classroomListShow[index].y + 20) * this.scaleDefault)
                        this.textStatus = false
                    }
                } else {
                    this.drawSchoolPlan('')
                    this.initIcon()
                    this.textStatus = true
                }
            }
        },
        canvasMouseUp(e) {
            this.isMouseDown = false
            if (this.activeIcon != -1) {
                this.classroomListShow[this.activeIcon].x = this.point.x / this.scaleDefault
                this.classroomListShow[this.activeIcon].y = this.point.y / this.scaleDefault
            }
            this.activeIcon = -1
        },
        canvasMouseOut(e) {
            this.isMouseDown = false
            if (this.activeIcon != -1) {
                this.classroomListShow[this.activeIcon].point = this.point
            }
            this.activeIcon = -1
        },
        drawSchoolPlan(imgUrl) {
            this.schoolPlan = document.getElementById('school-plan')
            let context = this.schoolPlan.getContext('2d')
            context.clearRect(0, 0, this.schoolPlan.width, this.schoolPlan.height)
            let _this = this
            if (_this.isFirstDraw <= 0) {
                let image = new Image()
                image.crossOrigin = 'anonymous'
                image.src = require('../../../assets/image/school_plan.jpg');
                image.onload = function () {
                    _this.schoolPlan.width = image.width
                    _this.schoolPlan.height = image.height
                    context.drawImage(image, 0, 0)
                    let imgData = context.getImageData(0, 0, _this.schoolPlan.width, _this.schoolPlan.height)
                    for (let i = 0; i < imgData.data.length; i += 4) {
                        let r = imgData.data[i]
                        let g = imgData.data[i + 1]
                        let b = imgData.data[i + 2]
                        let a = imgData.data[i + 3]
                        if (r > 200 && g > 200 && b > 200) {
                            imgData.data[i + 3] = 0
                        } else {
                            imgData.data[i] = 255
                            imgData.data[i + 1] = 255
                            imgData.data[i + 2] = 255
                            imgData.data[i + 3] = 255
                        }
                    }
                    context.putImageData(imgData, 0, 0)
                    let PNGImg = new Image()
                    PNGImg.src = _this.schoolPlan.toDataURL('image/png')
                    PNGImg.onload = function () {
                        _this.schoolImageData = PNGImg
                        _this.isFirstDraw++
                    }
                    _this.initIcon()
                }
            } else {
                if (this.schoolImageData) {
                    context.drawImage(this.schoolImageData, 0, 0, this.schoolImageData.width, this.schoolImageData.height, 0, 0, this.schoolImageData.width * this.scaleDefault, this.schoolImageData.height * this.scaleDefault)
                }
            }
        },
        getFileData(file) {
            let _this = this
            const reader = new FileReader()
            reader.readAsDataURL(file)
            reader.onload = () => {
                const _base64 = reader.result
                _this.drawSchoolPlan(_base64)
            }
            return false
        },
        saveClassroom() {
            this.$refs['classInfo'].validate((valid) => {
                if (!valid) {
                    this.$Message.error(this.$t('schoolBaseInfo.formWarning'))
                } else {
                    let option = this.classroomListShow[this.curClassIndex].option
                    if (!option) {
                        option = 'update'
                    } else {
                        this.classroomListShow[this.curClassIndex]['code'] = this.$store.state.userInfo.schoolCode
                    }
                    delete this.classroomListShow[this.curClassIndex].option
                    this.isSaveLoading = true
                    this.isListLoading = true
                    if (this.classroomListShow[this.curClassIndex].openType == '2') {
                        this.classroomListShow[this.curClassIndex].teacher.id = ''
                        this.classroomListShow[this.curClassIndex].teacher.name = ''
                    }
                    this.$api.schoolSetting.classUpsert({
                        classroom: this.classroomListShow[this.curClassIndex],
                        option: option,
                        school_code: this.$store.state.userInfo.schoolCode
                    }).then(
                        res => {
                            if (res) {
                                if (res.error) {
                                    this.classroomListShow[this.curClassIndex].option = 'insert'
                                    this.$Message.error(res.v)
                                } else {
                                    this.$Message.success(this.$t('schoolBaseInfo.csTips3'))
                                    this.updated = false
                                    this.updHiteachLink = []
                                    if (option == 'insert') {
                                        this.classroomListShow[this.curClassIndex].code = 'Class-' + this.classroomListShow[this.curClassIndex].code
                                        this.classroomList.unshift(this.classroomListShow[this.curClassIndex])
                                        this.$store.dispatch('user/addSchoolClasses', this.classroomListShow[this.curClassIndex]);
                                    }
                                }
                            } else {
                                this.$Message.error('API error!')
                            }
                        },
                        err => {
                            this.$Message.error('API error!')
                        }
                    ).finally(
                        () => {
                            this.isSaveLoading = false
                            this.isListLoading = false
                        }
                    )
                }
            })
        },
        getClassroom() {
            this.isListLoading = true
            this.$store.dispatch('user/getSchoolProfile').then(
                (res) => {
                    if (res) {
                        this.classroomList = res.school_classes
                        this.schoolBase = res.school_base
                        if (this.classroomList.length > 0) {
                            this.updateBefore = JSON.stringify(this.classroomList[0])
                        }
                        this.filterClassname()
                        // 預設搜尋給第一個
                        // this.filterPeriod = res.school_base.period[0].id
                        if (this.periods) this.filterPeriod = this.periods[0].id
                        this.filterByPeriod()
                    }
                },
                (err) => {
                    this.$Message.error('API error!')
                }
            ).finally(() => {
                setTimeout(() => {
                    this.isListLoading = false
                }, 500)
            })
        },
        /**显示确认删除班级对话框 */
        showConfirmDelete() {
            if (this.$access.can('admin.*|classroom-upd')) {
                this.$Modal.confirm({
                    title: this.$t('schoolBaseInfo.delClass'),
                    content: this.$t('schoolBaseInfo.delete') + this.classroomListShow[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.classroomListShow[index].option !== 'insert') {
                this.$api.schoolSetting.delClassroom({
                    id: this.classroomListShow[index].id,
                    scope: this.classroomListShow[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.classroomListShow[this.curClassIndex])
                            }
                            let originIndex = -1
                            for (let i in this.classroomList) {
                                if (this.classroomList[i].id == this.classroomListShow[index].id) {
                                    originIndex = i
                                    break
                                }
                            }
                            this.$api.schoolSetting.hiteachUnlinkByClassId({
                                classId: this.classroomListShow[index].id,
                                school_code: this.$store.state.userInfo.schoolCode
                            })
                            this.unlinkHiteachByClassId(this.classroomListShow[index].id) // 刪掉指定的classId                                
                            this.$store.dispatch('user/delSchoolClasses', this.classroomListShow[index].id);
                            this.classroomList.splice(originIndex, 1)
                            this.classroomListShow.splice(index, 1)
                            this.$Message.success(this.$t('schoolBaseInfo.csTips7'))
                            this.updated = false
                            this.updHiteachLink = []
                        }
                    },
                    (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.classroomListShow[this.curClassIndex])
                }
                this.classroomListShow.splice(index, 1)
                this.unlinkHiteachByClassId(this.classroomListShow[index].id)// 刪掉指定的classId
                this.isListLoading = false
                this.updated = false
                this.updHiteachLink = []
            }
        },
        uploadSchoolPlan(res, file) {
            this.$Message.success(this.$t('schoolBaseInfo.csTips5'))
        },
        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.classroomListShow[this.curClassIndex].option == 'insert') {
                                this.delClassroom(this.curClassIndex)
                            } else {
                                this.updated = false
                                this.updHiteachLink = []
                                this.$set(this.classroomListShow, this.curClassIndex, JSON.parse(this.updateBefore))
                                this.curClassIndex = index
                                this.updateBefore = JSON.stringify(this.classroomListShow[this.curClassIndex])
                                this.hiteachData = JSON.parse(this.orgHiteachData)
                            }
                        }
                    }
                    this.$Modal.confirm(config)
                } else {
                    this.curClassIndex = index
                    this.updateBefore = JSON.stringify(this.classroomListShow[this.curClassIndex])
                    this.hiteachData = JSON.parse(this.orgHiteachData)
                }
                if (this.currentTabIndex == 1) {
                    this.drawSchoolPlan('')
                    this.initIcon()
                }
            }
        },

        // 这段代码应该是原来的hiteach序号相关代码，调整之后没用就可以删掉了, 我看没有调用这个方法了
        chooseHiTeach(index) {
            if (this.editStatus) {
                this.$Message.warning('当前为不可编辑状态')
            } else {
                let i = this.hiTeachs.indexOf(this.hiTeachsShow[index])
                if (this.hiTeachs[i].single == 0) {
                    if (this.hiTeachs[i].using > 0) {
                        this.$Message.warning(this.$t('schoolBaseInfo.csTips6'))
                    } else {
                        if (this.classroomListShow[this.curClassIndex].sn) {
                            let showIndex = -1
                            let allIndex = -1
                            this.hiTeachsShow.forEach((v, i) => {
                                if (v.code == this.classroomListShow[this.curClassIndex].sn) {
                                    showIndex = i
                                }
                            })
                            this.hiTeachs.forEach((v, i) => {
                                if (v.code == this.classroomListShow[this.curClassIndex].sn) {
                                    allIndex = i
                                }
                            })
                            if (showIndex != -1 && allIndex != -1) {
                                this.hiTeachs[allIndex].using--
                            }
                        }
                        this.hiTeachs[i].using = 1
                        this.classroomListShow[this.curClassIndex].sn = this.hiTeachsShow[index].code
                        // smart 由右邊的Hiteach List 判斷
                        // this.classroomListShow[this.curClassIndex].style = 'smart'
                        this.updated = true
                    }
                } else {
                    if (!this.isEmpty(this.classroomListShow[this.curClassIndex].sn)) {
                        let showIndex = -1
                        let allIndex = -1
                        this.hiTeachsShow.forEach((v, i) => {
                            if (v.code == this.classroomListShow[this.curClassIndex].sn) {
                                showIndex = i
                            }
                        })
                        this.hiTeachs.forEach((v, i) => {
                            if (v.code == this.classroomListShow[this.curClassIndex].sn) {
                                allIndex = i
                            }
                        })
                        if (showIndex != -1 && allIndex != -1) {
                            this.hiTeachs[allIndex].using--
                        }
                    }
                    this.hiTeachs[i].using++
                    this.classroomListShow[this.curClassIndex].sn = this.hiTeachsShow[index].code
                    // smart 由右邊的Hiteach List 判斷
                    // this.classroomListShow[this.curClassIndex].style = 'smart'
                    this.updated = true
                }
                // this.filterCode()
            }
        },
        initData() {
            let white = new Image()
            let pink = new Image()
            let green = new Image()
            white.crossOrigin = 'anonymous'
            pink.crossOrigin = 'anonymous'
            green.crossOrigin = 'anonymous'
            white.src = require('../../../assets/pin.svg')
            pink.src = require('../../../assets/redpin.svg')
            green.src = require('../../../assets/greenpin.svg')
            let _this = this
            white.onload = function () {
                _this.whiteImageData = white
                _this.drawSchoolPlan()
            }
            pink.onload = function () {
                _this.pinImageData = pink
            }
            green.onload = function () {
                _this.greenImageData = green
            }
        },
        addClassroom() {
            if (this.$access.can('admin.*|classroom-upd')) {
                this.keyword = ''
                this.classroomListShow.unshift({
                    id: this.$jsFn.uuid(),
                    name: this.$t('schoolBaseInfo.presetClassroomName') + (this.classroomList.length + 1),
                    style: 'normal',
                    sn: '',
                    no: '',
                    openType: '1',
                    teacher: {
                        id: '',
                        name: ''
                    },
                    periodId: this.filterPeriod,
                    gradeId: '',
                    x: 20 * (this.classroomList.length % 5),
                    y: 20 * (this.classroomList.length / 5).toFixed(0),
                    scope: 'school',
                    option: 'insert'
                })
                this.drawIcon(5, 6)
                this.curClassIndex = 0
                this.updateBefore = JSON.stringify(this.classroomListShow[this.curClassIndex])
            } else {
                this.$Message.warning(this.$t('schoolBaseInfo.authWarning'))
            }
        },
        initHiteachData: async function () {
            let temp;
            let linkedClassIds = []
            await this.getHiteachList().then(res => {
                temp = res.map(item => {
                    // 子項目開關
                    item.subOpen = false
                    if (item.deviceMax == 1) item.subOpen = true

                    // 已被關聯數量
                    let linkCount = 0

                    // 關聯開關
                    item.deviceBound.map(db => {
                        db.hiteachLink = false
                        if (db.classId) {
                            db.hiteachLink = true
                            linkedClassIds.push(db.classId)
                            linkCount++;
                        }
                    })

                    item.linkCount = linkCount

                    return item
                })
            })
            this.orgHiteachData = JSON.stringify(temp)
            this.hiteachData = temp

            if (this.classroomList.length > 0) {
                this.classroomList.forEach(item => {
                    item.style = "normal"
                    if (linkedClassIds.indexOf(item.id) >= 0) {
                        item.style = "smart"
                    }
                })
            }
        },
        getHiteachList: async function () {
            let data = []
            await this.$api.classroom.GetHiteachList(this.$store.state.user.schoolCode).then(
                (res) => {
                    this.hiteachListLoading = false;
                    data = res.serial
                },
                (err) => {
                    this.$Message.error('API error!')
                }
            )
            return data
        },
        openHiSub(index) {
            if (this.showHiteachData.length > 0 && this.showHiteachData[index].deviceMax > 1) {
                this.showHiteachData[index].subOpen = !this.showHiteachData[index].subOpen
            }
        },
        isSmart: function (classId) {
            let style = false
            if (this.orgHiteachData != '') {
                let orgHiData = JSON.parse(this.orgHiteachData)
                let exist = orgHiData.some(item => {
                    let dbexist;
                    if (Array.isArray(item.deviceBound) && item.deviceBound.length > 0) {
                        dbexist = item.deviceBound.some(dbItem => {
                            return dbItem.classId == classId
                        })
                    }
                    return dbexist
                })
                style = exist
            }
            return style
        },
        pushCheckbox(item, disabled) {
            if (!disabled) {
                document.getElementById('checkbox-' + item.uuid + item.uuid2).click()
            }
        },
        whatUpdHiLink: function (item, classId, id) {
            if (item) {
                this.updated = true

                let arrayIndex = null
                this.updHiteachLink.forEach((updItem, updIndex) => {
                    // 利用相加字串來判斷
                    if (updItem.uuid + updItem.uuid2 == item.uuid + item.uuid2) {
                        arrayIndex = updIndex
                    }
                })

                if (arrayIndex != null) {
                    this.updHiteachLink.splice(arrayIndex, 1)
                }

                this.updHiteachLink.push(
                    {
                        id: id,
                        uuid: item.uuid,
                        uuid2: item.uuid2,
                        classId: item.hiteachLink ? classId : null,
                        deviceId: item.deviceId
                    }
                )
            }
        },
        unlinkHiteachByClassId: function (classId) {
            // 刪掉指定的classId
            let orgHiData = JSON.parse(this.orgHiteachData)
            orgHiData.forEach(item => {
                if (Array.isArray(item.deviceBound) && item.deviceBound.length > 0) {
                    item.deviceBound.forEach(db => {
                        if (db.classId == classId) {
                            db.classId = null
                            db.hiteachLink = false
                        }
                    })
                }
            })
            this.hiteachData = orgHiData
            this.orgHiteachData = JSON.stringify(orgHiData)
        },
        // 詢問視窗
        confirmLink: function(linkFlag, pid, uuid, uuid2, classId){
            let action = linkFlag ? 'unLink' : 'link';
            if(action == 'unLink'){
                this.$Modal.confirm({
                    title: this.$t('schoolBaseInfo.deLink'),
                    content: `${this.$t('schoolBaseInfo.confirmDelink')}?`,
                    onOk: () => {
                        this.executeHiteachLink(action, pid, uuid, uuid2, classId)                        
                    }
                })
            } else {
                this.executeHiteachLink(action, pid, uuid, uuid2, classId)
            }
        },
        executeHiteachLink: function(action, pid, uuid, uuid2, classId){
            // Hiteach 與教室綁定
            this.hiteachListLoading = true
            this.$api.schoolSetting.hiteachLink({
                school_code: this.$store.state.userInfo.schoolCode,
                // linkList: this.updHiteachLink
                action: action,
                pid: pid,
                uuid: uuid,
                uuid2: uuid2,
                classId: classId
            }).then(res => {
                if (res.error == 0) {
                    let orgHiData = JSON.parse(this.orgHiteachData)

                    let tempIndex;
                    let temp = orgHiData.find((hiItem, hiIndex) => {
                        tempIndex = hiIndex
                        return hiItem.id == pid
                    })
                    temp.deviceBound.forEach((dbItem, dbIndex, dbArray) => {
                        if ((dbItem.uuid + dbItem.uuid2) == (uuid + uuid2)) {
                            if(action == 'link'){
                                dbItem.classId = classId
                                dbItem.hiteachLink = true
                            } else if(action == 'unLink'){
                                dbItem.classId = null
                                dbItem.hiteachLink = false
                            }
                        }
                    })

                    orgHiData[tempIndex] = temp
                    
                    // 新增加
                    this.hiteachData = orgHiData
                    this.orgHiteachData = JSON.stringify(orgHiData)
                } else if (res.error == 1){
                    this.$Message.error(this.$t('無法關聯已被關聯的Hiteach'))
                }
            },
            err => {
                this.$Message.error(this.$t('參數錯誤'))
            }).finally(()=>{
                this.hiteachListLoading = false
            })
        }
    },
    mounted() {
        this.filterClassname()
        this.initData()
        this.initHiteachData()
        this.tableHeight = document.getElementById('class-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.initData()
        if (this.$access.can('admin.*|classroom-upd')) this.editStatus = this.noStatus
        this.getClassroom()
        this.$store.dispatch('teachers/getTeacherList').then(res => { })
    }
}
</script>
<style lang="less" scoped>
@import "./ClassroomSetting.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;
}

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

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

.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;
}

.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 {
    //     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>