<template>
    <div ref="refheader" v-show="!isWaveCharts" style="width: 100%">
        <TableHeader datePicker showExport showCustomColumn @onResetForm="onResetForm">
            <template v-slot:select>
                <el-form-item label="设备选取">
                    <el-tree-select
                        v-model="tableStore.table.params.cascader"
                        :data="deviceTree"
                        clearable
                        :props="treeProps"
                        filterable
                        :filter-node-method="filterNode"
                        check-strictly
                        default-expand-all
                        placeholder="请选择需要筛选的数据"
                        @node-click="sourceChange"
                          @clear="onTreeClear"
                        style="width: 100%"
                    ></el-tree-select>
                </el-form-item>
                <!-- <el-form-item label="关键字筛选">
                    <el-input
                        maxlength="32"
                        show-word-limit
                        style="width: 240px"
                        v-model.trim="tableStore.table.params.searchValue"
                        clearable
                        placeholder="请输入监测点名称"
                    />
                </el-form-item> -->
                <!-- <el-form-item>
                    <el-button type="primary" plain @click="openFilterDialog">事件筛选</el-button>
                </el-form-item> -->
            </template>
            <template v-slot:operation>
                <el-button type="primary" icon="el-icon-Operation" @click="openFilterDialog">事件筛选</el-button>
                <el-button type="primary" icon="el-icon-Histogram" @click="statistics">暂降原因分析</el-button>
            </template>
        </TableHeader>

        <MultiCondition
            v-model:visible="filterVisible"
            :params="tableStore.table.params"
            ref="multiConditionRef"
            @confirm="onFilterConfirm"
        />

        <Table ></Table>
        <!-- 补召日志 -->
        <analysisList ref="analysisListRef"></analysisList>
    </div>
    <waveFormAnalysis
        v-loading="loading"
        v-if="isWaveCharts"
        ref="waveFormAnalysisRef"
        @handleHideCharts="isWaveCharts = false"
        :wp="wp"
    />
</template>
<script setup lang="ts">
import { ref, onMounted, provide, nextTick } from 'vue'
import TableStore from '@/utils/tableStore'
import Table from '@/components/table/index.vue'
import TableHeader from '@/components/table/header/index.vue'
import MultiCondition from '@/views/govern/alarm/multiCondition.vue'
import waveFormAnalysis from '@/views/govern/device/control/tabs/components/waveFormAnalysis.vue'
import { analyseWave, getFileByEventId } from '@/api/common'
import { mainHeight } from '@/utils/layout'
import { ElMessage } from 'element-plus'
import { getFileZip } from '@/api/cs-harmonic-boot/datatrend'
import { buildWaveExportFileName, getExportSubjectFromRow } from '@/utils/echartMethod'
import { useDictData } from '@/stores/dictData'
import { queryByCode, queryByid, queryCsDictTree } from '@/api/system-boot/dictTree'
import analysisList from '@/views/govern/device/control/analysisList/index.vue'
import { createTreeFilterNode } from '@/components/tree/govern/treeFilterUtils'
const props = defineProps(['deviceTree'])
const emit = defineEmits(['statistics'])

const refheader = ref()
const waveFormAnalysisRef = ref()
const isWaveCharts = ref(false)
const loading = ref(false)
const boxoList: any = ref({})
const analysisListRef = ref()
const wp = ref({})
const dictData = useDictData()
const ReasonList: any = dictData.getBasicData('Event_Reason')
const DeviceType = ref([])
const EventTypeList: any = dictData.getBasicData('Event_Type')

const filterVisible = ref(false)
const multiConditionRef = ref<InstanceType<typeof MultiCondition>>()
const treeProps = {
    value: 'id',
    label: 'name',
    children: 'children'
}
const tableStore = new TableStore({
    url: '/cs-harmonic-boot/eventUser/queryEventpageWeb',
    method: 'POST',
    publicHeight: 65,
    exportName: '暂态事件',
    column: [
        {
            title: '序号',
            width: 80,
            formatter: (row: any) => {
                return (tableStore.table.params.pageNum - 1) * tableStore.table.params.pageSize + row.rowIndex + 1
            }
        },
        { title: '发生时刻', field: 'startTime', align: 'center', minWidth: 180, sortable: true },

        { title: '暂降幅值(%)', minWidth: 120, field: 'evtParamVVaDepth', align: 'center', sortable: true },

        { title: '持续时间(s)', field: 'evtParamTm', minWidth: 110, align: 'center', sortable: true },
        {
            title: '严重度',
            field: 'severity',
            minWidth: 80,
            align: 'center',
            sortable: true,
            formatter: (row: any) => {
                return row.cellValue ? row.cellValue : '/'
            }
        },
        { title: '相别', field: 'evtParamPhase', minWidth: 80, align: 'center' },
        { title: '触发类型', field: 'showName', minWidth: 100, align: 'center' },
        {
            title: '暂降原因',
            field: 'advanceReason',
            minWidth: 100,
            align: 'center',
            formatter: (row: any) => {
                return ReasonList.find((item: any) => item.id == row.cellValue)?.name || '其他'
            }
        },
        {
            title: '暂降类型',
            field: 'advanceType',
            minWidth: 100,
            align: 'center',
            formatter: (row: any) => {
                return EventTypeList.find((item: any) => item.id == row.cellValue)?.name || '其他'
            }
        },
        { title: '监测点名称', field: 'lineName', minWidth: 150, align: 'center' },
        { title: '电压等级(kV)', field: 'lineVoltage', minWidth: 120, align: 'center', sortable: true },
        { title: '设备名称', field: 'equipmentName', minWidth: 150, align: 'center' },
        { title: '项目名称', field: 'projectName', minWidth: 150, align: 'center' },
        { title: '工程名称', field: 'engineeringName', minWidth: 150, align: 'center' },
        {
            title: '发生位置',
            field: 'sagSource',
            minWidth: 120,
            align: 'center',
            formatter: (row: any) => {
                return row.cellValue == 1 ? '上游' : row.cellValue == 2 ? '下游' : '暂无'
            }
        },
        {
            title: '操作',
            fixed: 'right',
            align: 'center',
            width: '180',

            render: 'buttons',
            buttons: [
                {
                    name: 'edit',
                    title: '波形分析',
                    type: 'primary',
                    icon: 'el-icon-DataLine',
                    render: 'basicButton',
                    loading: 'loading1',
                    disabled: row => {
                        return !row.wavePath
                    },
                    click: async row => {
                        row.loading1 = true
                        await analyseWave(row.id)
                            .then(res => {
                                row.loading1 = false
                                if (res != undefined) {
                                    loading.value = true
                                    isWaveCharts.value = true

                                    boxoList.value = {
                                        ...row,
                                        engineeringName: row.projectName,
                                        persistTime: row.evtParamTm,
                                        featureAmplitude:
                                            row.evtParamVVaDepth != '-' ? (row.evtParamVVaDepth - 0) / 100 : null,
                                        systemType: 'YPT'
                                    }
                                    wp.value = res.data
                                }
                                loading.value = false
                            })
                            .catch(() => {
                                row.loading1 = false
                                loading.value = false
                            })

                        nextTick(() => {
                            waveFormAnalysisRef.value &&
                                waveFormAnalysisRef.value.getWpData(wp.value, boxoList.value, true)
                            // waveFormAnalysisRef.value && waveFormAnalysisRef.value.setHeight(200, 190)
                        })
                    }
                },
                {
                    name: 'edit',
                    title: '波形下载',
                    type: 'primary',
                    icon: 'el-icon-Check',
                    loading: 'loading2',
                    render: 'basicButton',
                    disabled: row => {
                        return !row.wavePath
                    },
                    click: row => {
                        row.loading2 = true
                        ElMessage.info('下载中......')
                        getFileZip({ eventId: row.id })
                            .then(res => {
                                let blob = new Blob([res], { type: 'application/zip' }) // console.log(blob) // var href = window.URL.createObjectURL(blob); //创建下载的链接
                                const url = window.URL.createObjectURL(blob)
                                const link = document.createElement('a') // 创建a标签
                                link.href = url
                                link.download = buildWaveExportFileName(getExportSubjectFromRow(row))
                                document.body.appendChild(link)
                                link.click() //执行下载
                                document.body.removeChild(link) //释放标签
                                ElMessage.success('波形下载成功')
                                row.loading2 = false
                            })
                            .catch(() => {
                                row.loading2 = false
                            })
                    }
                },
                {
                    name: 'edit',
                    text: '暂不支持补召',
                    type: 'info',
                    icon: 'el-icon-DataLine',
                    render: 'basicButton',
                    disabled: row => {
                        let code = DeviceType.value.filter((item: any) => item.id == row.devType)[0]?.code
                        return !((code == 'Direct_Connected_Device' || code == 'Gateway') && row.wavePath == null)
                    }
                },
                {
                    name: 'edit',
                    text: '波形补召',
                    type: 'primary',
                    icon: 'el-icon-DataLine',
                    render: 'basicButton',
                    loading: 'loading2',
                    disabled: row => {
                        let code = DeviceType.value.filter((item: any) => item.id == row.devType)[0]?.code
                        return !((code == 'Portable' || code == 'DEV_CLD') && row.wavePath == null)
                    },
                    click: row => {
                        let code = DeviceType.value.filter((item: any) => item.id == row.devType)[0]?.code

                        if (code == 'Portable') {
                            // 便携式设备
                            analysisListRef.value &&
                                analysisListRef.value.open({
                                    lineId: row.lineId,
                                    deviceData: row,
                                    deviceId: row.deviceId
                                })
                        } else if (code == 'DEV_CLD') {
                            row.loading2 = true
                            // 监测设备
                            getFileByEventId(row.id)
                                .then(res => {
                                    ElMessage.success(res.message)
                                    tableStore.index()
                                    row.loading2 = false
                                })
                                .catch(() => {
                                    row.loading2 = false
                                })
                        }
                    }
                }
            ]
        }
    ],
    beforeSearchFun: () => {
        // if (!tableStore.table.params.deviceId) {
        //     delete tableStore.table.params.deviceId
        // }
    },
    loadCallback: () => {
        tableStore.table.data.forEach((item: any) => {
            item.loading = false
            item.evtParamTm =
                item.evtParamTm.split('s')[0] != '-' ? (item.evtParamTm.split('s')[0] - 0).toFixed(2) : '-'
            item.evtParamVVaDepth =
                item.evtParamVVaDepth.split('%')[0] != '-' ? (item.evtParamVVaDepth.split('%')[0] - 0).toFixed(2) : '-'
        })
    }
})

provide('tableStore', tableStore)
//   "target": [],
//   "type": "",
//   "userId": ""
tableStore.table.params.searchValue = ''
tableStore.table.params.engineeringid = ''
tableStore.table.params.projectId = ''
tableStore.table.params.deviceId = ''
tableStore.table.params.lineId = ''
tableStore.table.params.cascader = ''

tableStore.table.params.type = 0

Object.assign(tableStore.table.params, {
    featureAmplitudeMin: undefined,
    featureAmplitudeMax: undefined,
    evtParamTmMin: undefined,
    evtParamTmMax: undefined,
    severityMin: undefined,
    severityMax: undefined,
    fileFlag: ''
})
// tableStore.table.params.level=''

const openFilterDialog = () => {
    filterVisible.value = true
}
const onTreeClear = () => {
    tableStore.table.params.engineeringid = ''
    tableStore.table.params.projectId = ''
    tableStore.table.params.deviceId = ''
    tableStore.table.params.lineId = ''
}

const sourceChange = (e: any) => {
    onTreeClear()
    if (e.level == 0) {
        tableStore.table.params.engineeringid = e.id
    } else if (e.level == 1) {
        tableStore.table.params.projectId = e.id
    } else if (e.level == 2) {
        tableStore.table.params.deviceId = e.id
    } else if (e.level == 3) {
        tableStore.table.params.lineId = e.id
    }
}

const filterNode = createTreeFilterNode()
const onFilterConfirm = () => {
    tableStore.onTableAction('search', {})
}

// 重置
const onResetForm = () => {
    filterVisible.value = false
    tableStore.table.params.cascader = ''
    tableStore.table.params.deviceTypeId = ''
    tableStore.table.params.engineeringid = ''
    tableStore.table.params.projectId = ''
    tableStore.table.params.deviceId = ''
    tableStore.table.params.deviceTypeName = ''
    multiConditionRef.value?.reset()
}

onMounted(() => {
    queryByCode('Device_Type').then(res => {
        queryCsDictTree(res.data.id).then((list: any) => {
            DeviceType.value = list.data
        })
    })
    tableStore.index()
})

const statistics = () => {
    emit('statistics')
}
const bxecharts = mainHeight(175).height as any
setTimeout(() => {
    tableStore.table.height = mainHeight(200).height as any
}, 0)

const addMenu = () => {}
</script>
<style scoped lang="scss"></style>
