<!-- 设备管理 -->
<template>
    <div class="default-main device-manage" :style="{ height: pageHeight.height }" v-loading="loading">
        <DeviceTree @node-click="nodeClick" @init="nodeClick" @deviceTypeChange="deviceTypeChange"></DeviceTree>
        <div class="device-manage-right" v-if="deviceData">
            <el-descriptions title="基础信息" class="mb10" :column="3" border>
                <template #extra>
                    <!-- <el-button
                        type="primary"
                        icon="el-icon-Share"
                        @click="openGroup"
                        :loading="getGroupLoading"
                    >
                    模版数据分组
                    </el-button> -->
                    <el-button
                        icon="el-icon-Refresh"
                        v-if="showButtom && pName == '治理设备'"
                        @click="handleRestartDevice"
                        type="primary"
                        :loading="deviceRestartLoading"
                    >
                        设备重启
                    </el-button>
                </template>
                <el-descriptions-item label="名称">
                    {{ deviceData.name || '/' }}
                </el-descriptions-item>
                <el-descriptions-item label="类型">
                    {{ echoName(deviceData.devType, devTypeOptions) || '/' }}
                </el-descriptions-item>

                <el-descriptions-item label="接入方式">
                    {{ deviceData.devAccessMethod == 'CLD' ? '1056协议' : deviceData.devAccessMethod || '/' }}
                </el-descriptions-item>
                <el-descriptions-item label="网络设备ID">
                    {{ deviceData.ndid || '/' }}
                </el-descriptions-item>
                <el-descriptions-item label="型号">
                    {{ echoName(deviceData.devModel, devModelOptions) || '/' }}
                </el-descriptions-item>
                <el-descriptions-item label="首次接入日期">
                    {{ deviceData.time || '/' }}
                </el-descriptions-item>
                <el-descriptions-item label="应用程序版本号">
                    {{ deviceData.appVersion || '/' }}
                </el-descriptions-item>
                <el-descriptions-item label="应用程序发布日期">
                    {{ deviceData.appDate || '/' }}
                </el-descriptions-item>
                <el-descriptions-item label="应用程序校验码">
                    {{ deviceData.appCheck || '/' }}
                </el-descriptions-item>
            </el-descriptions>
            <div style="position: relative">
                <el-tabs
                    v-model.trim="dataSet"
                    type="border-card"
                    class="device-manage-box-card"
                    @tab-click="handleClick"
                >
                    <el-tab-pane
                        lazy
                        :label="item.name"
                        :name="item.id"
                        v-for="(item, index) in deviceData.dataSetList"
                        :key="index"
                    ></el-tab-pane>
                    <div :style="{ height: tableHeight }" v-loading="tableLoading">
                        <vxe-table
                            v-bind="defaultAttribute"
                            :data="tableData"
                            height="auto"
                            ref="xTableRef"
                            style="width: 100%"
                        >
                            <vxe-column type="seq" title="序号" width="80"></vxe-column>
                            <vxe-column field="name" title="指标名称" minWidth="200"></vxe-column>
                            <vxe-column field="phasic" title="相别" minWidth="150"></vxe-column>
                            <vxe-column field="type" title="数据类型" minWidth="100"></vxe-column>
                            <vxe-column field="unit" title="单位" minWidth="100"></vxe-column>
                            <vxe-column field="startTimes" title="开始次数"minWidth="100"></vxe-column>
                            <vxe-column field="endTimes" title="结束次数" minWidth="100"></vxe-column>
                        </vxe-table>
                    </div>
                </el-tabs>
                <el-button icon="el-icon-Download" type="primary" @click="exportData" class="export-btn">
                    导出
                </el-button>
            </div>
        </div>
        <el-empty v-else description="请选择设备" class="device-manage-right" />
        <MangePopup ref="mangePopup" />
    </div>
</template>

<script setup lang="ts">
defineOptions({
    name: 'govern/device/manage'
})

import MangePopup from './popup.vue'
import DeviceTree from '@/components/tree/govern/deviceTree.vue'
import { mainHeight } from '@/utils/layout'
import { queryByCode, queryByid, queryCsDictTree } from '@/api/system-boot/dictTree'
import { getDeviceData } from '@/api/cs-device-boot/EquipmentDelivery'
import { buildExportBaseName } from '@/utils/echartMethod'
import { getTargetById } from '@/api/cs-device-boot/csDataArray'
import { getGroup } from '@/api/cs-device-boot/csGroup'
import { ref } from 'vue'
import { useAdminInfo } from '@/stores/adminInfo'
import { passwordConfirm } from '@/api/user-boot/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { reStartDevice } from '@/api/cs-device-boot/fileService'
import { defaultAttribute } from '@/components/table/defaultAttribute'
const pageHeight = mainHeight(20)
const adminInfo = useAdminInfo()
const showButtom = ref(adminInfo.roleCode.includes('operation_manager') || adminInfo.roleCode.includes('root'))
const pName = ref('')
const loading = ref(true)
const nDid = ref<string>('')
const tableLoading = ref(false)
const getGroupLoading = ref(false)
const deviceData = ref<any>(null)
const dataSet = ref('')
const devTypeOptions: any = ref([])
const devModelOptions = ref([])
const tableData = ref([])
const tableHeight = mainHeight(260).height
const mangePopup = ref()
const activeName = ref(0)
const xTableRef = ref()
//治理设备和便携式设备切换判断
const deviceType = ref('0')
const deviceTypeChange = (val: any, obj: any) => {
    deviceType.value = val
    nodeClick(obj)
}
const exportSubjectName = ref('')
// 树节点点击
const nodeClick = (e: anyObj) => {
    if (!e) {
        loading.value = false
        return
    }
    if (e.level == 2 || e.level == 3) {
        exportSubjectName.value = e.name || ''
        pName.value = e.pName
        nDid.value = e.ndid
        loading.value = true
        getDeviceData(e.id, 'rt', '').then((res: any) => {
            deviceData.value = res.data
            loading.value = false
            if (!res.data.dataSetList) {
                dataSet.value = ''
                tableData.value = []
            } else {
                if (res.data.dataSetList && res.data.dataSetList[0]?.id) {
                    dataSet.value = res.data.dataSetList[0]?.id
                } else {
                    dataSet.value = ''
                    tableData.value = []
                }
                handleClick()
            }
        })
    }
}
//tab点击事件
const handleClick = () => {
    tableLoading.value = true
    tableData.value = []
    setTimeout(() => {
        getTargetById(dataSet.value).then(res => {
            tableData.value = res.data
            tableLoading.value = false
        })
    }, 100)
}
queryByCode('Device_Type').then(async res => {
    await queryCsDictTree(res.data.id).then(res => {
        devTypeOptions.value = res.data.map((item: any) => {
            return {
                value: item.id,
                label: item.name,
                ...item
            }
        })
    })
    await queryByid(res.data.id).then(res => {
        devModelOptions.value = res.data.map((item: any) => {
            return {
                value: item.id,
                label: item.name,
                ...item
            }
        })
    })
    await queryByCode('DEV_CLD').then(k => {
        devTypeOptions.value.push(k.data)
        return queryCsDictTree(k.data.id).then(s => {
            let list = s.data.map((item: any) => {
                return {
                    value: item.id,
                    label: item.name,
                    ...item
                }
            })

            devModelOptions.value.push(...list)
        })
    })
})
const echoName = (value: any, arr: any[]) => {
    return arr.find(item => item.id == value)?.name
}
const openGroup = () => {
    if (!dataSet.value) {
        return ElMessage.warning('暂无数据')
    }
    getGroupLoading.value = true
    getGroup(dataSet.value).then((res: any) => {
        const call = (data: any[]) => {
            data.forEach(item => {
                item.label = item.name
                item.isShow = item.isShow == 1
                if (item.children && item.children.length > 0) {
                    call(item.children)
                }
            })
        }
        call(res.data)
        getGroupLoading.value = false
        mangePopup.value.open({
            deviceData: deviceData.value,
            dataSetName: deviceData.value.dataSetList.filter((item: any) => item.id == dataSet.value)[0]?.name,
            dataSet: dataSet.value,
            tree: res.data
        })
    })
}
//设备重启
const deviceRestartLoading = ref<boolean>(false)
const handleRestartDevice = () => {
    deviceRestartLoading.value = true
    ElMessageBox.prompt('二次校验密码确认', '设备重启', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        customClass: 'customInput',
        inputType: 'text',
        beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
                if (instance.inputValue == null) {
                    return ElMessage.warning('请输入密码')
                } else if (instance.inputValue?.length > 32) {
                    return ElMessage.warning('密码长度不能超过32位,当前密码长度为' + instance.inputValue.length)
                } else {
                    done()
                }
            } else {
                done()
            }
        }
    })
        .then(({ value }) => {
            if (!value) {
                ElMessage.warning('请输入密码')

                deviceRestartLoading.value = false
            } else {
                passwordConfirm(value)
                    .then((resp: any) => {
                        if (resp.code == 'A0000') {
                            reStartDevice({ nDid: nDid.value })
                                .then((res: any) => {
                                    deviceRestartLoading.value = false
                                    ElMessage({ message: res.message, type: 'success', duration: 3000 })
                                })
                                .catch(e => {
                                    deviceRestartLoading.value = false
                                })
                        }
                    })
                    .catch(e => {
                        deviceRestartLoading.value = false
                    })
            }
        })
        .catch(() => {
            deviceRestartLoading.value = false
        })
}
const exportData = () => {
    const dataSetName = deviceData.value.dataSetList.filter((item: any) => item.id == dataSet.value)[0]?.name
    xTableRef.value.exportData({
        filename: buildExportBaseName({
            subject: exportSubjectName.value || deviceData.value?.name,
            feature: dataSetName || '数据集'
        }), // 文件名字
        sheetName: 'Sheet1',
        type: 'xlsx', //导出文件类型 xlsx 和 csv
        useStyle: true,
        download: false,
        data: tableData.value, // 数据源 // 过滤那个字段导出
        columnFilterMethod: function (column, $columnIndex) {
            return !(column.$columnIndex === 0)
        }
    })
}
</script>

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

    &-left {
        width: 280px;
    }

    &-right {
        overflow: hidden;
        flex: 1;
        padding: 10px 10px 10px 0;

        .el-descriptions__header {
            height: 36px;
            margin-bottom: 7px;
            display: flex;
            align-items: center;
        }
    }
}

.customInput {
    .el-input__inner {
        -webkit-text-security: disc !important;
    }
}

.export-btn {
    position: absolute;
    top: 4px;
    right: 10px;
    z-index: 10;
}
:deep(.el-tabs__header) {
    width: calc(100% - 100px);
}
</style>
