<template>
    <div class="default-main">

        <TableHeader area>
            <template #select>
                <el-form-item label="监测点性质">
                    <el-select v-model="tableStore.table.params.powerFlag" filterable  collapse-tags 
                        placeholder="请选择监测点性质">
                        <el-option v-for="item in terminalstatus" :key="item.value" :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="电压等级">
                    <el-select v-model="tableStore.table.params.scale" filterable multiple collapse-tags clearable
                        placeholder="请选择电压等级" value-key="id">
                        <el-option v-for="item in voltageleveloption" :key="item.id" :label="item.name" :value="item">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="终端厂家">
                    <el-select v-model="tableStore.table.params.manufacturer" filterable multiple collapse-tags
                        clearable placeholder="请选择终端厂家" value-key="id">
                        <el-option v-for="item in terminaloption" :key="item.id" :label="item.name" :value="item">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="干扰源类型">
                    <el-select v-model="tableStore.table.params.loadType" filterable multiple collapse-tags clearable
                        placeholder="请选择干扰源类型" value-key="id">
                        <el-option v-for="item in interfereoption" :key="item.id" :label="item.name" :value="item">
                        </el-option>
                    </el-select>
                </el-form-item>




                <el-form-item label="上报类型">
                    <el-select v-model="tableStore.table.params.monitorFlag" 
                        placeholder="请选择上报类型">
                        <el-option v-for="item in communicationstatus" :key="item.value" :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>


            </template>

        </TableHeader>
        <div :style="{ height: tableStore.table.height }" v-loading="tableStore.table.loading">
            <vxe-table  height="auto" auto-resize v-bind="defaultAttribute" :stripe='false' :scroll-y="{ enabled: false }"
                :span-method="rowspanMethod" :data="tableData">
                <vxe-column field="name1" title="区域">
                </vxe-column>
                <vxe-column field="name2" title="类型">
                </vxe-column>
                <vxe-column field="name3" title="分类型">
                    <template #default="{ row }">
                        <span>{{ Number.isFinite(row.name3-0)? row.name3+'kV':row.name3}}</span>
                    </template>
                </vxe-column>
                <vxe-column field="subCount" title="变电站个数(个)">
                     <template #default="{ row }">
                        <span style="color: blue">{{ row.subCount }}</span>
                    </template>
                </vxe-column>
                <vxe-column field="devCount" title="终端个数(个)">
                    <template #default="{ row }">
                        <span style="color: #006699">{{ row.devCount }}</span>
                    </template>
                </vxe-column>
                <vxe-column field="lineCount" title="监测点个数(个)">
                    <template #default="{ row }">
                        <span style="color: green">{{ row.lineCount }}</span>
                    </template>
                </vxe-column>
            </vxe-table>
        </div>




    </div>
</template>
<script setup lang="ts">
import { ref, onMounted, provide } from 'vue'
import TableStore from '@/utils/tableStore'
import Table from '@/components/table/index.vue'
import { useDictData } from '@/stores/dictData'
import TableHeader from '@/components/table/header/index.vue'
import { defaultAttribute } from '@/components/table/defaultAttribute'
import type { VxeTablePropTypes } from 'vxe-table'
import XEUtils from 'xe-utils'
const dictData = useDictData()
defineOptions({
    name: 'harmonic-boot/run/terminalconts'
})
const treeData: any = ref([])
const treeDataCopy: any = ref([])

const classificationData = dictData.getBasicData('Statistical_Type', ["Report_Type"])
const voltageleveloption = dictData.getBasicData('Dev_Voltage_Stand')
const terminaloption = dictData.getBasicData('Dev_Manufacturers')
const interfereoption = dictData.getBasicData('Interference_Source')
//上报类型
const communicationstatus = [

    { value: 2, label: "全部" },
    { value: 1, label: "灿能上报" },
    { value: 0, label: "非灿能上报" },
]
//终端状态
const terminalstatus = [
    { value: 2, label: "全部" },
    { value: 1, label: "非电网侧" },
    { value: 0, label: "电网侧" },
]


const tableStore = new TableStore({
    url: '/device-boot/runManage/getTerminalLedger',
    method: 'POST',
    showPage: false,
    column: [
        {
            field: 'index',
            title: '序号',
            width: '80',
            formatter: (row: any) => {
                return (tableStore.table.params.pageNum - 1) * tableStore.table.params.pageSize + row.rowIndex + 1
            }
        },
        { field: 'areaName', title: '区域' },
        { field: 'gdName', title: '类型' },
        { field: 'flx', title: '分类型' },
        { field: 'gdName', title: '变电站个数(个)' },
        { field: 'gdName', title: '终端个数(个)' },
        { field: 'gdName', title: '监测点个数(个)' },
    ],

    loadCallback: () => {

        treeData.value = tree2List(tableStore.table.data, Math.random() * 1000)

        toColTreeData(XEUtils.toArrayTree(JSON.parse(JSON.stringify(treeData.value))))

    }
})
tableStore.table.params.statisticalType = classificationData[0]
tableStore.table.params.serverName = "harmonic-boot"
tableStore.table.params.monitorFlag = 2
tableStore.table.params.powerFlag = 2
tableStore.table.params.evaluate = ''


tableStore.table.params.scale = voltageleveloption
tableStore.table.params.manufacturer = terminaloption
tableStore.table.params.loadType = interfereoption
// 处理大数据卡顿
const tree2List = (list: any, id: any) => {
    //存储结果的数组
    let arr: any = []
    // 遍历 tree 数组
    list.forEach((item: any) => {
        item.parentId = id
        item.id = (Math.random() * 1000)

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

const toColTreeData = (treeData: any[]) => {
    const options = { children: 'children' }
    const list: any[] = []
    const keyMap: any = {}
    XEUtils.eachTree(treeData, (item, index, result, paths, parent) => {
        keyMap[item.id] = item
        item.keys = parent ? parent.keys.concat([item.id]) : [item.id]
        if (!item.children || !item.children.length) {
            const row: any = {}
            // console.log("🚀 ~ item.keys.forEach ~ item:", item)

            item.keys.forEach((key: any, index: number) => {
                const level = index + 1
                const obj = keyMap[key]

                row[`id${level}`] = obj.id
                row[`name${level}`] = obj.areaName || obj.name || obj.dicName
                row[`subCount`] = obj.subCount
                row[`devCount`] = obj.devCount
                row[`lineCount`] = obj.lineCount
            })
            list.push(row)
        }
    }, options)

    tableData.value = list
}

const tableData: any = ref([])

// 通用行合并函数（将相同多列数据合并为一行）
const rowspanMethod: VxeTablePropTypes.SpanMethod = ({ row, _rowIndex, column, visibleData }) => {
    // console.log("🚀 ~ row:", row)
    const fields = ['name1', 'name2', 'name3', 'name4', 'name5', 'name6']
    const cellValue = row[column.field]
    // console.log("🚀 ~ cellValue:", cellValue)
    if (cellValue && fields.includes(column.field)) {
        const prevRow = visibleData[_rowIndex - 1]
        let nextRow = visibleData[_rowIndex + 1]
        if (prevRow && prevRow[column.field] === cellValue) {
            return { rowspan: 0, colspan: 0 }
        } else {
            let countRowspan = 1
            while (nextRow && nextRow[column.field] === cellValue) {
                nextRow = visibleData[++countRowspan + _rowIndex]
            }
            if (countRowspan > 1) {
                return { rowspan: countRowspan, colspan: 1 }
            }
        }
    }
}



provide('tableStore', tableStore)
onMounted(() => {
    tableStore.index()
})





</script>
