<template>
    <div class=" device-manage" :style="{ height: pageHeight.height }" v-loading="loading">
        <DeviceTree
            :showCheckbox="true"
            :default-checked-keys="defaultCheckedKeys"
            @checkChange="checkChange"
            :height="35"
        ></DeviceTree>
        <div class="device-manage-right" :style="{ height: pageHeight.height }">
            <vxe-table v-bind="defaultAttribute" :data="tableData" height="auto" style="width: 100%">
                <vxe-column field="enginerName" title="工程名称"></vxe-column>
                <vxe-column field="projectName" title="项目名称"></vxe-column>
                <vxe-column field="deviceName" title="装置名称"></vxe-column>
            </vxe-table>
        </div>
    </div>
</template>

<script setup lang="ts">
defineOptions({
    name: 'govern/tourist/index'
})
import { defaultAttribute } from '@/components/table/defaultAttribute'
import DeviceTree from '@/components/tree/govern/deviceTree.vue'
import { mainHeight } from '@/utils/layout'
import { getVisitorConfig, updateVisitorConfig } from '@/api/cs-device-boot/user'
import { ref, onMounted } from 'vue'

const pageHeight = mainHeight(60)
const loading = ref(true)
const defaultCheckedKeys: any = ref([])
const tableData = ref([])

const checkChange = (data: any) => {
    if (data.data.level === 2) {
        if (data.checked) {
            defaultCheckedKeys.value.push(data.data.id)
        } else {
            defaultCheckedKeys.value.splice(defaultCheckedKeys.value.indexOf(data.data.id), 1)
        }
        loading.value = true
        updateVisitorConfigs()
    }
}
const updateVisitorConfigs = () => {
    const result = Array.from(new Set(defaultCheckedKeys.value))
    updateVisitorConfig(
        result.map(item => {
            return {
                deviceId: item
            }
        })
    ).then((res: any) => {
        if (res.code === 'A0000') {
            getVisitorConfigs()
        }
    })
}
const getVisitorConfigs = () => {
    getVisitorConfig().then((res:any) => {
        if (res.code === 'A0000') {
            tableData.value = res.data
            loading.value = false
            if (defaultCheckedKeys.value.length > 0) return
            defaultCheckedKeys.value = [] // 清空
            res.data.forEach((item:any) => {
                defaultCheckedKeys.value.push(item.deviceId)
            })
        }
    })
}

onMounted(() => {
    // if (!adminInfo.token) return router.push({ name: 'login' })

    getVisitorConfigs()
})
</script>

<style lang="scss">
.device-manage {
    display: flex;

    &-right {
        overflow: hidden;
        flex: 1;
        padding: 10px 10px 10px 0;
        .el-descriptions__header {
            height: 36px;
            margin-bottom: 7px;
            display: flex;
            align-items: center;
        }
    }
}
</style>
