<template>
    <div>
        <div v-show="!isWaveCharts">
            <TableHeader showExport ref="headerRef" :showQuery="false" @onResetForm="onResetForm">
                <template v-slot:operation>
                    <el-button type="primary" icon="el-icon-Operation" @click="openFilterDialog">事件筛选</el-button>
                </template>
            </TableHeader>
            <Table ref="tableRef" />
            <MultiCondition v-model:visible="filterVisible" :params="tableStore.table.params" ref="multiConditionRef"
                @confirm="onFilterConfirm" />
            <!-- 补召日志 -->
            <analysisList ref="analysisListRef"></analysisList>
        </div>
        <waveFormAnalysis v-loading="loading" v-if="isWaveCharts" ref="waveFormAnalysisRef"
            @handleHideCharts="isWaveCharts = false" :wp="wp" />
    </div>

    <!-- <TableHeader :showReset="false">
       
    </TableHeader> -->


</template>
<script setup lang='ts'>
import { ref, provide, onMounted, nextTick } from 'vue'
import { getEventByItem } from '@/api/cs-device-boot/planData'
import TableStore from '@/utils/tableStore'
import Table from '@/components/table/index.vue'
import TableHeader from '@/components/table/header/index.vue'
import { ElMessage } from 'element-plus'
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 { getFileZip } from '@/api/cs-harmonic-boot/datatrend'
import { buildWaveExportFileName, getExportSubjectFromRow } from '@/utils/echartMethod'
import { queryByCode, queryByid, queryCsDictTree } from '@/api/system-boot/dictTree'
import analysisList from '@/views/govern/device/control/analysisList/index.vue'

import { useDictData } from '@/stores/dictData'
const props = defineProps({
    activeName: String,
    activeColName: [Object, String]
})
const loading = ref(false)
const dictData = useDictData()
const ReasonList: any = dictData.getBasicData('Event_Reason')
const EventTypeList: any = dictData.getBasicData('Event_Type')
const DeviceType = ref([])
const waveFormAnalysisRef = ref()
const isWaveCharts = ref(false)
const boxoList: any = ref([])
const analysisListRef = ref()
const wp = ref({})
const filterVisible = ref(false)
const multiConditionRef = ref()
const tableStore = new TableStore({
    url: '/cs-harmonic-boot/data/getEventByItem',
    method: 'POST',
    // paramsPOST: true,
    exportName: '暂态事件',
    showPage: false,
    publicHeight: 355,
    column: [
        // { width: '60', type: 'checkbox', fixed: 'left' },
        {
            title: '序号', width: 80, formatter: (row: any) => {
                return (tableStore.table.params.pageNum - 1) * tableStore.table.params.pageSize + row.rowIndex + 1
            }
        },
        { field: 'startTime', title: '发生时刻', minWidth: 170, sortable: true },
        {
            field: 'featureAmplitude',
            title: '暂降幅值(%)',
            minWidth: 120,
            formatter: (row: any) => {
                row.cellValue = row.cellValue + '' ? row.cellValue.toFixed(2) : '/'
                if (String(row.cellValue).split('.')[1] == '00') {
                    row.cellValue = String(row.cellValue).split('.')[0]
                }
                return row.cellValue
            }, sortable: true
        },
        {
            field: 'persistTime',
            title: '持续时间(s)',
            minWidth: 110,
            formatter: (row: any) => {
                row.cellValue = row.cellValue ? row.cellValue.toFixed(2) : '/'
                return row.cellValue
            }, sortable: true
        },
        {
            title: '严重度', field: 'severity', minWidth: 80, align: 'center', sortable: true, formatter: (row: any) => {
                return row.cellValue ? row.cellValue : '/'
            }
        },
        {
            field: 'phaseType',
            title: '相别',
            minWidth: 100,
            formatter: (row: any) => {
                row.cellValue = row.cellValue ? row.cellValue : '/'
                return row.cellValue
            }
        },


        { field: 'showName', title: '触发类型', minWidth: 100 },
        {
            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: 'devName', minWidth: 150, align: 'center' },
        {
            title: '发生位置', field: 'sagSource', minWidth: 120, align: 'center', formatter: (row: any) => {

                return row.cellValue == 1 ? '上游' : row.cellValue == 2 ? '下游' : '未知'
            }
        },
        {
            title: '操作', fixed: 'right',
            width: 180,
            render: 'buttons',

            buttons: [
                {
                    name: 'edit',
                    title: '波形分析',
                    type: 'primary',
                    icon: 'el-icon-Check',
                    render: 'basicButton',
                    loading: 'loading1',
                    disabled: row => {
                        // && row.evtParamTm < 20
                        return !row.wavePath
                    },
                    click: async row => {
                        row.loading1 = true

                        await analyseWave(row.id)
                            .then(res => {
                                loading.value = true
                                isWaveCharts.value = true
                                row.loading1 = false
                                if (res != undefined) {
                                    boxoList.value = {
                                        ...row,
                                        featureAmplitude:
                                            row.featureAmplitude != '-' ? (row.featureAmplitude - 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)
                            setHeight()
                        })
                    }
                },
                // {
                //     name: 'edit',
                //     text: '暂无波形',
                //     type: 'info',
                //     icon: 'el-icon-DataLine',
                //     render: 'basicButton',
                //     disabled: row => {
                //         return row.wavePath
                //     }
                // },
                {
                    name: 'edit',
                    title: '波形下载',
                    type: 'primary',
                    loading: 'loading2',
                    icon: 'el-icon-Check',
                    render: 'basicButton',
                    disabled: row => {
                        // && row.evtParamTm < 20
                        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
                            })
                        }

                    }
                },

            ]
        }
    ],

    loadCallback: () => {

    }
})
Object.assign(tableStore.table.params, {
    featureAmplitudeMin: undefined,
    featureAmplitudeMax: undefined,
    evtParamTmMin: undefined,
    evtParamTmMax: undefined,
    severityMin: undefined,
    severityMax: undefined,
    fileFlag: ''
})
const setHeight = () => {
    if (props.activeColName == '0') {
        waveFormAnalysisRef.value && waveFormAnalysisRef.value.setHeight(350, 485)
        tableStore.table.height = mainHeight(380).height

    } else {
        waveFormAnalysisRef.value && waveFormAnalysisRef.value.setHeight(350, 350)
        tableStore.table.height = mainHeight(240).height
    }
}

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

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()
}
provide('tableStore', tableStore)
const init = () => {
    tableStore.table.params.id = props.activeName
    // getEventByItem({ id: props.activeName }).then(res => {

    // })
    tableStore.index()
}
const onFilterConfirm = () => {
    tableStore.onTableAction('search', {})
}
const openFilterDialog = () => {
    filterVisible.value = true
}
onMounted(() => {

})
defineExpose({ init, setHeight })

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