<template>
    <div>
        <el-dialog draggable title="暂态事件" v-model="dialogVisible" append-to-body width="70%">
            <TableHeader datePicker showExport showCustomColumn 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" :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 tableHeaderRef = ref()
const filterVisible = ref(false)
const multiConditionRef = ref<InstanceType<typeof MultiCondition>>()
const currentOpenTime = ref('')

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

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

const tableStore: any = new TableStore({
    url: '/cs-harmonic-boot/eventUser/queryEventpageWeb',
    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
            }
        },
        { 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) => 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) => 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: '监测点名称', 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) => row.cellValue == 1 ? '上游' : row.cellValue == 2 ? '下游' : '暂无'
        },
        {
            title: '操作',
            fixed: 'right',
            align: 'center',
            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-DataLine',
                    render: 'basicButton',
                    loading: 'loading1',
                    disabled: (row: any) => !row.wavePath,
                    click: async (row: any) => {
                        row.loading1 = true
                        dialogVisible.value = false
                        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(() => {
                            if (waveFormAnalysisRef.value) {
                                waveFormAnalysisRef.value.getWpData(wp.value, boxoList.value, true)
                                waveFormAnalysisRef.value.setHeight(999, 130, 1.6666666)
                            }
                        })
                    }
                },
                {
                    name: 'edit',
                    title: '波形下载',
                    type: 'primary',
                    icon: 'el-icon-Check',
                    loading: 'loading2',
                    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: () => { },
    resetCallback: () => {
        restoreOpenDayTime()
    },
    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)
                    : '-'
        })
    }
})

tableStore.table.params.type = 0
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 restoreOpenDayTime = () => {
    if (!currentOpenTime.value || !tableHeaderRef.value) return
    tableHeaderRef.value.setInterval(5)
    tableHeaderRef.value.setTimeInterval([currentOpenTime.value, currentOpenTime.value])
    tableStore.table.params.searchBeginTime = currentOpenTime.value
    tableStore.table.params.searchEndTime = currentOpenTime.value
}

const syncInitDataForReset = () => {
    if (!tableStore.initData) return
    Object.assign(tableStore.initData, {
        searchBeginTime: currentOpenTime.value,
        searchEndTime: currentOpenTime.value,
        startTime: currentOpenTime.value,
        endTime: currentOpenTime.value,
        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()
    syncInitDataForReset()
    nextTick(() => {
        restoreOpenDayTime()
    })
}

const open = (time: string) => {
    currentOpenTime.value = time
    dialogVisible.value = true
    filterVisible.value = false
    resetFilterParams()
    multiConditionRef.value?.reset()
    tableStore.table.params.pageNum = 1

    nextTick(() => {
        restoreOpenDayTime()
        tableStore.index()
        nextTick(() => {
            syncInitDataForReset()
        })
    })
}

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

defineExpose({ open })
</script>

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