<template>
    <div>
        <el-dialog draggable :title="title" v-model="dialogVisible" append-to-body width="70%">
            <TableHeader datePicker showExport ref="tableHeaderRef" @selectChange="selectChange"
                @onResetForm="onResetForm">
                <template v-slot:operation>
                    <el-button type="primary" icon="el-icon-Operation" @click="openFilterDialog">事件筛选</el-button>
                </template>
            </TableHeader>

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

            <Table ref="tableRef" isGroup :height="heightRef"></Table>
        </el-dialog>

        <el-dialog v-model="isWaveCharts" draggable title="波形分析" append-to-body width="70%" @close="handleHideCharts">
            <waveFormAnalysis v-loading="loading" v-if="isWaveCharts" ref="waveFormAnalysisRef"
                @handleHideCharts="handleHideCharts" :wp="wp" />
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, provide, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import Table from '@/components/table/index.vue'
import TableHeader from '@/components/table/header/index.vue'
import TableStore from '@/utils/tableStore'
import { mainHeight } from '@/utils/layout'
import MultiCondition from '@/views/govern/alarm/multiCondition.vue'
import waveFormAnalysis from '@/views/govern/device/control/tabs/components/waveFormAnalysis.vue'
import { analyseWave } from '@/api/common'
import { getFileZip } from '@/api/cs-harmonic-boot/datatrend'
import { buildWaveExportFileName, getExportSubjectFromRow } from '@/utils/echartMethod'
import { useDictData } from '@/stores/dictData'

const dialogVisible = ref(false)
const waveFormAnalysisRef = ref()
const isWaveCharts = ref(false)
const loading = ref(false)
const wp = ref({})
const boxoList: any = ref({})
const title = ref('暂态事件')
const tableHeaderRef = ref()
const filterVisible = ref(false)
const filterTarget = ref('')
const multiConditionRef = ref<InstanceType<typeof MultiCondition>>()

const dictData = useDictData()
const ReasonList: any = dictData.getBasicData('Event_Reason')
const EventTypeList: any = dictData.getBasicData('Event_Type')

const heightRef = ref(mainHeight(168, 2.2).height)
const tableParams = ref<any>({})
const selectChange = (_flag: boolean, h: number) => {
    heightRef.value = mainHeight(h, 2.2).height
}

const tableStore: any = new TableStore({
    url: '/cs-device-boot/csGroup/deviceDataByType',
    method: 'POST',
    showPage: true,
    exportName: '暂态事件',
    column: [
        {
            title: '序号',
            width: 80,
            formatter: (row: any) => {
                return (tableStore.table.params.pageNum - 1) * tableStore.table.params.pageSize + row.rowIndex + 1
            }
        },
        { field: 'startTime', title: '发生时刻', minWidth: 180, sortable: true },
        {
            field: 'featureAmplitude',
            title: '暂降幅值(%)',
            minWidth: 120,
            sortable: true,
            formatter: (row: any) => {
                row.cellValue = row.cellValue != null ? Number(row.cellValue).toFixed(2) : '/'
                if (String(row.cellValue).split('.')[1] == '00') {
                    row.cellValue = String(row.cellValue).split('.')[0]
                }
                return row.cellValue
            }
        },
        {
            field: 'persistTime',
            title: '持续时间(s)',
            minWidth: 110,
            formatter: (row: any) => row.cellValue ? (row.cellValue - 0).toFixed(2) : '/',
            sortable: true
        },
        {
            field: 'phaseType',
            title: '相别',
            minWidth: 80,
            formatter: (row: any) => row.cellValue || '/'
        },
        {
            title: '严重度',
            field: 'severity',
            minWidth: 80,
            align: 'center',
            sortable: true,
            formatter: (row: any) => row.cellValue ? row.cellValue : '/'
        },
        { field: 'showName', title: '触发类型', minWidth: 100 },
        {
            title: '暂降原因',
            field: 'advanceReason',
            minWidth: 100,
            align: 'center',
            formatter: (row: any) => ReasonList.find((item: any) => item.id == row.cellValue)?.name || '其他'
        },
        {
            title: '暂降类型',
            field: 'advanceType',
            minWidth: 100,
            align: 'center',
            formatter: (row: any) => EventTypeList.find((item: any) => item.id == row.cellValue)?.name || '其他'
        },
        { title: '电压等级(kV)', field: 'lineVoltage', minWidth: 120, align: 'center', sortable: true },
        {
            title: '发生位置',
            field: 'sagSource',
            minWidth: 120,
            align: 'center',
            formatter: (row: any) => row.cellValue == 1 ? '上游' : row.cellValue == 2 ? '下游' : '未知'
        },
        {
            title: '操作',
            fixed: 'right',
            width: 150,
            render: 'buttons',
            buttons: [
                {
                    name: 'edit',
                    text: '暂无波形',
                    type: 'info',
                    icon: 'el-icon-DataLine',
                    render: 'basicButton',
                    disabled: row => {
                        return row.wavePath
                    }
                },
                {
                    name: 'edit',
                    title: '波形分析',
                    type: 'primary',
                    icon: 'el-icon-Check',
                    render: 'basicButton',
                    loading: 'loading1',
                    disabled: (row: any) => !row.wavePath,
                    click: async (row: any) => {
                        row.loading1 = true
                        await analyseWave(row.id)
                            .then(res => {
                                row.loading1 = false
                                if (res != undefined) {
                                    loading.value = true
                                    isWaveCharts.value = true
                                    dialogVisible.value = false
                                    boxoList.value = {
                                        ...row,
                                        systemType: 'YPT',
                                        engineeringName: tableParams.value.projectName,
                                        featureAmplitude:
                                            row.featureAmplitude != null ? Number(row.featureAmplitude / 100) : '-',
                                        persistTime: row.persistTime ? row.persistTime.toFixed(2) : '-',
                                    }
                                    wp.value = res.data
                                }
                                loading.value = false
                            })
                            .catch(() => {
                                row.loading1 = false
                                loading.value = false
                            })

                        nextTick(() => {
                            if (waveFormAnalysisRef.value) {
                                waveFormAnalysisRef.value.getWpData(wp.value, boxoList.value)
                                waveFormAnalysisRef.value.setHeight(999, 130, 1.6666666)
                            }
                        })
                    }
                },
                {
                    name: 'edit',
                    title: '波形下载',
                    type: 'primary',
                    loading: 'loading2',
                    icon: 'el-icon-Check',
                    render: 'basicButton',
                    disabled: (row: any) => !row.wavePath,
                    click: (row: any) => {
                        row.loading2 = true
                        ElMessage.info('下载中......')
                        getFileZip({ eventId: row.id }).then(res => {
                            const blob = new Blob([res as unknown as BlobPart], { type: 'application/zip' })
                            const url = window.URL.createObjectURL(blob)
                            const link = document.createElement('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
                        })
                    }
                }
            ]
        }
    ],
    beforeSearchFun: () => {
        tableStore.table.params.devId = tableParams.value.devId
        tableStore.table.params.lineId = tableParams.value.lineId
        tableStore.table.params.list = tableParams.value.list
        tableStore.table.params.type = 3
    },
    loadCallback: () => { }
})
tableStore.table.params.type = 3
Object.assign(tableStore.table.params, {
    featureAmplitudeMin: undefined,
    featureAmplitudeMax: undefined,
    evtParamTmMin: undefined,
    evtParamTmMax: undefined,
    severityMin: undefined,
    severityMax: undefined,
    fileFlag: ''
})

provide('tableStore', tableStore)

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

const openFilterDialog = () => {
    filterVisible.value = true
}

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

const onResetForm = () => {
    filterVisible.value = false
    resetFilterParams()
    multiConditionRef.value?.reset()
    tableStore.index()
}

const open = (row: any, searchBeginTime: any, searchEndTime: any, type?: string) => {
    filterTarget.value = type || ''
    title.value = row.name + '_暂态事件'
    dialogVisible.value = true
    filterVisible.value = false
    resetFilterParams()
    multiConditionRef.value?.reset()

    const lineId = row.id || row.lineId
    tableParams.value = {
        lineId,
        devId: row.devId,
        engineeringName: row.engineeringName,
        list: row.devId ? [{ lineId, devId: row.devId }] : undefined,
    }
    tableStore.table.params.pageNum = 1

    nextTick(() => {
        tableHeaderRef.value.setTimeInterval([searchBeginTime, searchEndTime])
        tableStore.table.params.searchBeginTime = searchBeginTime
        tableStore.table.params.searchEndTime = searchEndTime
        tableStore.index()
    })
}

const handleHideCharts = () => {
    isWaveCharts.value = false
    dialogVisible.value = true
}

defineExpose({ open })
</script>

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