<template>
    <TableHeader area datePicker ref="TableHeaderRef">
        <template #select>
            <el-form-item label="筛选">
                <el-input v-model="tableStore.table.params.filterName" @keyup="searchEvent" placeholder="输入关键字筛选" />
            </el-form-item>
            <el-form-item label="统计类型:">
                <el-select v-model="tableStore.table.params.statisticalType" value-key="id" placeholder="请选择统计类型">
                    <el-option v-for="item in classificationData" :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.scale" multiple collapse-tags clearable value-key="id"
                    placeholder="请选择电压等级">
                    <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" multiple collapse-tags clearable
                    value-key="id" placeholder="请选择终端厂家">
                    <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" multiple collapse-tags clearable value-key="id"
                    placeholder="请选择干扰源类型">
                    <el-option v-for="item in interfereoption" :key="item.id" :label="item.name"
                        :value="item"></el-option>
                </el-select>
            </el-form-item>
        </template>
        <template #operation>
            <!-- <el-button icon="el-icon-Plus" type="primary" @click="addFormModel">新增</el-button> -->
            <el-button icon="el-icon-Download" :loading="loading" @click="exportEvent" type="primary">下载报告</el-button>
        </template>
    </TableHeader>
    <Table ref="tableRef" :radio-config="{
        labelField: 'name',
        highlight: true,
        visibleMethod: row => row.row.level == 6
    }" :tree-config="{ transform: true, parentField: 'uPid', rowField: 'uId' }" :scroll-y="{ enabled: true }" />
</template>
<script setup lang="ts">
import { ref, onMounted, provide, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import TableStore from '@/utils/tableStore'
import Table from '@/components/table/index.vue'
import TableHeader from '@/components/table/header/index.vue'
import { useDictData } from '@/stores/dictData'
import { exportModelJB } from '@/api/harmonic-boot/harmonic.ts'
import { debounce } from 'lodash-es'
import XEUtils from 'xe-utils'
const dictData = useDictData()
const tableRef = ref()
const treeDataCopy: any = ref([])
const treeData: 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 TableHeaderRef = ref()
const tableStore = new TableStore({
    url: '/device-boot/LineIntegrityData/getLineIntegrityData',
    publicHeight: 65,
    showPage: false,
    method: 'POST',
    column: [
        // { width: '60', title: '111',  },
        { field: 'name', title: '电网拓扑', minWidth: '180px', type: 'radio', align: 'left', treeNode: true },
        {
            field: 'ip',
            title: '网络参数',
            formatter: ({ row }: any) => {
                return row.ip || '/'
            }
        },
        {
            field: 'deviceName',
            title: '终端名称',
            formatter: ({ row }: any) => {
                return row.deviceName || '/'
            }
        },
        {
            field: 'manufacturer',
            title: '厂家',
            formatter: ({ row }: any) => {
                return row.manufacturer || '/'
            }
        },
        {
            field: 'comFlag',
            title: '通讯状态',
            render: 'tag',
            custom: {
                0: 'danger',
                1: 'success',
                3: 'info'
            },
            replaceValue: {
                0: '中断',
                1: '正常',
                3: '/'
            }
        },
        {
            field: 'updateTime',
            title: '最新数据时间',
            formatter: ({ row }: any) => {
                return row.updateTime || '/'
            }
        },
        {
            field: 'integrityData',
            title: '完整性(%)',
            formatter: ({ row }: any) => {
                return row.integrityData == 3.14159 ? '暂无数据' : row.integrityData.toFixed(2)
            }
        },
        {
            field: 'assess',
            title: '评估',
            render: 'tag',
            custom: {
                0: 'info',
                1: 'danger',
                2: 'warning',
                3: 'success'
            },
            replaceValue: {
                0: '暂无数据',
                1: '不合格',
                2: '合格',
                3: '优秀'
            }
        }
    ],
    beforeSearchFun: () => {
        tableStore.options.column[0].title = tableStore.table.params.statisticalType.name
    },
    loadCallback: () => {
        setTimeout(() => {
            tableRef.value.getRef().setAllTreeExpand(true)
        }, 1000)
      
        treeData.value = tree2List(tableStore.table.data, Math.random() * 1000)
        treeDataCopy.value = JSON.parse(JSON.stringify(treeData.value))
        tableStore.table.data = treeData.value
        tableStore.table.params.filterName=''
        searchEvent()
    }
})
const loading = ref(false)

tableStore.table.params.statisticalType = classificationData.filter(item => item.name == '电网拓扑')[0]
tableStore.table.params.monitorFlag = 2
tableStore.table.params.powerFlag = 2
tableStore.table.params.serverName = 'harmonicBoot'

provide('tableStore', tableStore)
const tree2List = (list: any, id: any) => {
    //存储结果的数组
    let arr: any = []
    // 遍历 tree 数组
    list.forEach((item: any) => {
        item.uPid = id
        item.uId = (Math.random() * 1000)
        item.comFlag = item.comFlag == null ? 3 : item.comFlag
        item.assess = item.integrityData == 3.14159 ? 0 : item.integrityData < 60 ? 1 : item.integrityData < 90 ? 2 : 3
        // 判断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
}
onMounted(() => {
    tableStore.index()
})
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
        )
        console.log("🚀 ~ searchEvent ~ rest:", rest)

        tableStore.table.data = rest

        // 搜索之后默认展开所有子节点
    } else {
        tableStore.table.data = treeDataCopy.value
    }
    nextTick(() => {
        const $table = tableRef.value.getRef()
        if ($table) {
            $table.setAllTreeExpand(true)
        }
    })
}, 500)
const exportEvent = () => {
    let line = tableRef.value.getRef().getRadioRecord()
    if (!line) {
        ElMessage({
            type: 'warning',

            message: '请选择要导出的数据'
        })
        return
    }
    loading.value = true
    let form = new FormData()
    form.append('isUrl', false)
    form.append('lineIndex', line.id)
    form.append('startTime', TableHeaderRef.value.datePickerRef.timeValue[0])
    form.append('endTime', TableHeaderRef.value.datePickerRef.timeValue[1])
    form.append('type', 0)
    form.append('name', line.name)
    ElMessage({
        message: '下载报告中,请稍等.....',
        duration: 1000
    })
    exportModelJB(form).then(async res => {
        let blob = new Blob([res], {
            type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        })

        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a') // 创建a标签
        link.href = url
        link.download =
            line.name +
            TableHeaderRef.value.datePickerRef.timeValue[0] +
            '_' +
            TableHeaderRef.value.datePickerRef.timeValue[1] // 设置下载的文件名
        document.body.appendChild(link)
        link.click() //执行下载
        document.body.removeChild(link)
        loading.value = false
    }).catch(() => {
        loading.value = false
    })
}
</script>

<style scoped lang="scss"></style>
