<template>
    <div class="default-main" style="position: relative">
        <TableHeader>
            <template #select>
                <el-form-item label="终端型号">
                    <el-select
                        v-model="tableStore.table.params.devType"
                        filterable
                        clearable
                        placeholder="请选择终端型号"
                    >
                        <el-option
                            v-for="item in teriminaloption"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="终端状态">
                    <el-select v-model="tableStore.table.params.runFlag" clearable placeholder="请选择终端状态">
                        <el-option
                            v-for="item in teriminalstatusoption"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="通讯状态">
                    <el-select v-model="tableStore.table.params.comFlag" clearable placeholder="请选择通讯状态">
                        <el-option
                            v-for="item in stateoption"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        ></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="筛选数据">
                    <el-input
                        v-model="tableStore.table.params.filterName"
                        @keyup="searchEvent"
                        clearable
                        placeholder="输入关键字筛选"
                    />
                </el-form-item>
            </template>
            <template #operation>
                <el-button type="primary" icon="el-icon-DataLine" @click="manage('终端状态管理', 0)">
                    终端状态管理
                </el-button>
                <!-- <el-button type="primary" icon="el-icon-Operation" @click="manage('流量套餐配置', 1)">
                    流量套餐配置
                </el-button> -->
                <!-- <el-button type="primary" icon="el-icon-Menu" @click="manage('流量策略配置', 2)">
                    流量策略配置
                </el-button>
                <el-button type="primary" icon="el-icon-Histogram" @click="liultjData">流量统计</el-button> -->
                <!-- <el-button type="primary" icon="el-icon-Setting" @click="resect">重启前置程序</el-button> -->
            </template>
        </TableHeader>
        <div :style="`height: calc(${tableStore.table.height} + 58px)`">
            <vxe-table
                v-loading="tableStore.table.loading"
                height="auto"
                auto-resize
                ref="tableRef"
                v-bind="defaultAttribute"
                :data="treeData"
                show-overflow
                :tree-config="{ transform: true, parentField: 'uPid', rowField: 'uId' }"
                :scroll-y="{ enabled: true }"
                :checkbox-config="{ labelField: 'name' }"
            >
                <vxe-column
                    field="name"
                    align="left"
                    type="checkbox"
                    title="电网拓扑"
                    min-width="200"
                    tree-node
                ></vxe-column>
                <vxe-column field="devType" title="终端型号">
                    <template #default="{ row }">
                        {{ teriminaloption.find((item: any) => item.id === row.devType)?.name }}
                    </template>
                </vxe-column>
                <vxe-column field="version" title="版本信息"></vxe-column>
                <vxe-column field="ip" title="网络参数" width="120px"></vxe-column>

                <vxe-column field="runFlag" title="终端状态">
                    <template #default="{ row }">
                        <el-tag v-if="row.runFlag === 0" type="success" :disable-transitions="true" size="small">投运</el-tag>
                        <el-tag v-if="row.runFlag === 1" type="warning" :disable-transitions="true" size="small">检修</el-tag>
                        <el-tag v-if="row.runFlag === 2" type="danger" :disable-transitions="true" size="small">停运</el-tag>
                    </template>
                </vxe-column>
                <vxe-column field="comFlag" title="通讯状态">
                    <template #default="{ row }">
                        <el-tag v-if="row.comFlag === 0" type="danger" :disable-transitions="true" size="small">中断</el-tag>
                        <el-tag v-if="row.comFlag === 1" type="success" :disable-transitions="true" size="small">正常</el-tag>
                    </template>
                </vxe-column>
                <vxe-column title="操作" width="160">
                    <template #default="{ row }">
                        <!-- <el-button v-if="row.level === 4" type="primary" size="small" link @click="uesdealia(row)">
                            终端详情
                        </el-button> -->
                        <el-button v-if="row.level === 4" type="primary" size="small" link @click="log(row)">
                            查看日志
                        </el-button>
                    </template>
                </vxe-column>
            </vxe-table>
        </div>
        <!-- 终端详情 -->
        <detail ref="detailRef" />
        <!-- 配置 -->
        <disposition ref="dispositionRef" @onSubmit="tableStore.index()" />
        <!-- 日志 -->
        <Log ref="logRef" v-if="logFlag" @close="logFlag = false" />
    </div>
</template>
<script setup lang="ts">
import { ref, onMounted, provide, nextTick, reactive } from 'vue'
import TableStore from '@/utils/tableStore'
import { defaultAttribute } from '@/components/table/defaultAttribute'
import TableHeader from '@/components/table/header/index.vue'
import { ElMessage } from 'element-plus'
import { getDevTypeList } from '@/api/device-boot/modelManage'
import XEUtils from 'xe-utils'
import { debounce } from 'lodash-es'

import disposition from './components/disposition.vue'
import detail from './components/detail.vue'
import Log from './components/log.vue'
import { useDictData } from '@/stores/dictData'

defineOptions({
    name: 'BusinessAdministrator/TerminalManagement/TerminalManagement'
})
const dispositionRef = ref()
const detailRef = ref()
const logRef = ref()
const dictData = useDictData()
const logFlag = ref(false)
const teriminaloption: any = ref([])

const teriminalstatusoption = ref([
    { name: '全部', id: '' },
    { name: '投运', id: 0 },
    { name: '检修', id: 1 },
    { name: '停运', id: 2 }
])
const stateoption = ref([
    { name: '全部', id: '' },
    { name: '正常', id: 1 },
    { name: '中断', id: 0 }
])
const treeData: any = ref([])
const treeDataCopy: any = ref([])

const tableRef = ref()

const tableStore = new TableStore({
    url: '/device-boot/maintain/getTerminalMainList',
    method: 'POST',
    column: [],
    loadCallback: () => {
        treeData.value = tree2List(tableStore.table.data, Math.random() * 1000)
        treeDataCopy.value = JSON.parse(JSON.stringify(treeData.value))
        setTimeout(() => {
            tableRef.value.setAllTreeExpand(true)
        }, 0)
        searchEvent()
    }
})
tableStore.table.params.devType = ''
tableStore.table.params.runFlag = ''
tableStore.table.params.comFlag = ''
tableStore.table.params.filterName = ''
// 处理大数据卡顿
const tree2List = (list: any, id: any) => {
    //存储结果的数组
    let arr: any = []
    // 遍历 tree 数组
    list.forEach((item: any) => {
        item.uPid = id
        item.uId = Math.random() * 1000

        // 判断item是否存在children
        if (!item.children) return arr.push(item)
        // 函数递归，对children数组进行tree2List的转换
        const children = tree2List(item.children, item.uId)
        // 删除item的children属性
        delete item.children
        // 把item和children数组添加至结果数组
        //..children: 意思是把children数组展开
        arr.push(item, ...children)
    })
    // 返回结果数组
    return arr
}

provide('tableStore', tableStore)
tableStore.table.params.searchValue = ''
tableStore.table.params.searchState = 0
onMounted(() => {
    getDevTypeList().then(res => {
        teriminaloption.value = res.data
    })

    tableStore.index()
})

// 终端状态管理
const manage = (name: string, key: number) => {
    const $table = tableRef.value
    if ($table) {
        const selectRecords = $table
            .getCheckboxRecords()
            .filter((item: any) => item.level == 4)
            .map(item => item.id)
        console.log('🚀 ~ deviceData ~ selectRecords:', selectRecords)
        if (selectRecords.length == 0) {
            return ElMessage({
                message: '请至少选择一台装置',
                type: 'warning'
            })
        }
        dispositionRef.value.open({
            title: name,
            id: selectRecords,
            key: key
        })
    }
}

// 流量统计
const liultjData = () => {}
// 重启前置程序
const resect = () => {}

// 终端详情
const uesdealia = (row: any) => {
    detailRef.value.open(row)
}
// 流量详情
const log = (row: any) => {
    logFlag.value = true
    setTimeout(() => {
        logRef.value.open(row)
    }, 100)
}

// 表格过滤
const searchEvent = debounce(() => {
    const filterVal = XEUtils.toValueString(tableStore.table.params.filterName).trim().toLowerCase()
    if (filterVal) {
        const options = { children: 'children' }
        const searchProps = ['name']
        const rest = XEUtils.searchTree(
            treeDataCopy.value,
            (item: any) => searchProps.some(key => String(item[key]).toLowerCase().indexOf(filterVal) > -1),
            options
        )
        treeData.value = rest

        // 搜索之后默认展开所有子节点
    } else {
        treeData.value = treeDataCopy.value
    }
    nextTick(() => {
        const $table = tableRef.value
        if ($table) {
            $table.setAllTreeExpand(true)
        }
    })
}, 500)
</script>
