<template>
    <div>
        <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 && roomListShow[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, roomListShow[curClassIndex].id)">{{ dbItem.hiteachLink ? $t('schoolBaseInfo.deLink') : $t('schoolBaseInfo.link') }}</Button>
                                    <!-- <Checkbox :id="'checkbox-' + (dbItem.uuid + dbItem.uuid2)" @on-change="whatUpdHiLink(dbItem, roomListShow[curClassIndex].id, item.id)" style="margin-right: 70px;" v-model="dbItem.hiteachLink" :disabled="dbItem.classId != '' && dbItem.classId != null && roomListShow[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 && roomListShow[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>
</template>
<script>
export default {
    data() {
        return {
            updHiteachLink: [],
            orgHiteachData: [],
            hiteachData: [],
            filterHiteachVer: 'ALL',
            updateBeforebyHiteach: '',
            hiteachListLoading: true,
            serchCode: '',
        }
    },
    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: {
        showHiteachData: function () {
            let data = this.hiteachData
            let filterText = this.filterHiteachVer
            let nowSeletedClassId = null
            if (this.roomListShow.length > 0) {
                nowSeletedClassId = this.roomListShow[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
        }
    },
    methods: {
        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.roomList.length > 0) {
                this.roomList.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
                })
        }
    }
}
</script>
<style scoped lang="less">
</style>