<template>
    <div class="view">
        <div v-show="!isWaveCharts">
            <TableHeader datePicker showExport showCustomColumn ref="headerRef" @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" />
        </div>
        <waveFormAnalysis v-loading="loading" v-if="isWaveCharts" ref="waveFormAnalysisRef"
            @handleHideCharts="isWaveCharts = false" :wp="wp" />
    </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, provide, nextTick, } from 'vue'
import { getTabsDataByType } from '@/api/cs-device-boot/EquipmentDelivery'
import TableStore from '@/utils/tableStore'
import Table from '@/components/table/index.vue'
import MultiCondition from '@/views/govern/alarm/multiCondition.vue'
import TableHeader from '@/components/table/header/index.vue'
import waveFormAnalysis from './components/waveFormAnalysis.vue'
import { ArrowLeft, Message } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { analyseWave, getFileByEventId } from '@/api/common'
import { getFileZip } from '@/api/cs-harmonic-boot/datatrend'
import { buildWaveExportFileName, getExportSubjectFromRow } from '@/utils/echartMethod'
import { useDictData } from '@/stores/dictData'
const emit=defineEmits(['fileRecall'])
const tableParams: any = ref({})
const refheader = ref()
const view = ref(true)
const view2 = ref(false)
const loading = ref(false)
const showBoxi = ref(true)
const bxactiveName = ref('ssbx')
const boxoList: any = ref([])
const wp = ref({})
const value = ref(1)
const waveFormAnalysisRef = ref()
const multiConditionRef = ref()

const props = defineProps({
    deviceType: {
        type: String,
        default: '0'
    }
})
const dictData = useDictData()
const ReasonList: any = dictData.getBasicData('Event_Reason')
const EventTypeList: any = dictData.getBasicData('Event_Type')
const tableStore: any = new TableStore({
    url: '/cs-device-boot/csGroup/deviceDataByType',
    publicHeight: 215,
    method: 'POST',
    exportName: '暂态事件',
    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: 180, sortable: true },

        {
            field: 'featureAmplitude',
            title: '暂降幅值(%)',
            minWidth: 120,
            sortable: true,
            formatter: (row: any) => {
                //row.cellValue = row.cellValue + '' ? row.cellValue.toFixed(2) : '/'
                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) => {
                // console.log('🚀 ~  row.cellValue:', row.cellValue)

                return row.cellValue ? (row.cellValue - 0).toFixed(2) : '/'
            },
            sortable: true
        },
        {
            field: 'phaseType',
            title: '相别',
            minWidth: 80,
            formatter: (row: any) => {
                return row.cellValue || '/'
            }
        },
        {
            title: '严重度', field: 'severity', minWidth: 80, align: 'center', sortable: true, formatter: (row: any) => {
                return row.cellValue ? 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: '电压等级(kV)', field: 'lineVoltage', minWidth: 120, align: 'center', sortable: true, },
        {
            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 => {
                                isWaveCharts.value = true
                                loading.value = true
                                row.loading1 = false
                                if (res != undefined) {
                                    boxoList.value = {
                                        ...row,
                                        systemType: 'YPT',
                                        engineeringName: tableParams.value.engineeringName,
                                        featureAmplitude:
                                            row.featureAmplitude != null ? Number(row.featureAmplitude / 100) : '-',
                                        persistTime: row.persistTime ? row.persistTime.toFixed(2) : '-',
                                    }
                                    wp.value = res.data
                                    view.value = false
                                    view2.value = true
                                }
                                loading.value = false
                            })
                            .catch(() => {
                                row.loading1 = false
                                loading.value = false
                            })

                        nextTick(() => {
                            waveFormAnalysisRef.value && waveFormAnalysisRef.value.getWpData(wp.value, boxoList.value)
                            // waveFormAnalysisRef.value && waveFormAnalysisRef.value.setHeight(200, 345)
                            waveFormAnalysisRef.value && waveFormAnalysisRef.value.setHeight(350, 345)
                        })
                    }
                },
                // {
                //     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',
                    title: '波形补召',
                    type: 'primary',
                    icon: 'el-icon-Check',
                    render: 'basicButton',
                    loading: 'loading3',
                    disabled: row => {
                        return !(row.wavePath == null)
                    },
                    click: row => {
                        if (props.deviceType == '2') {
                            row.loading3 = true
                            getFileByEventId(row.id).then(res => {
                                ElMessage.success(res.message)
                                tableStore.index()
                                row.loading3 = false
                            }).catch(() => {
                                row.loading3 = false
                            })
                        }else if(props.deviceType == '1'){
                            emit('fileRecall', row.id)
                        }

                    }
                }
            ]
        }
    ],

    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
    },
    exportProcessingData: () => {
        tableStore.table.allData?.forEach((row: any) => {
            row.lineName = row.lineName || tableParams.value.lineName || '/'
        })
    },
    loadCallback: () => { }
})
Object.assign(tableStore.table.params, {
    featureAmplitudeMin: undefined,
    featureAmplitudeMax: undefined,
    evtParamTmMin: undefined,
    evtParamTmMax: undefined,
    severityMin: undefined,
    severityMax: undefined,
    fileFlag: ''
})
// 重置
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()
}
const filterVisible = ref(false)
provide('tableStore', tableStore)
const isWaveCharts = ref(false)
//获取请求参数
const getTableParams = (val: any) => {
    tableParams.value = val
    isWaveCharts.value = false
    tableStore.exportName = { subject: val.lineName, feature: '暂态事件' }
    tableStore.index()
}
const onFilterConfirm = () => {
    tableStore.onTableAction('search', {})
}
const openFilterDialog = () => {
    filterVisible.value = true
}

defineExpose({ getTableParams })
onMounted(() => {


    // tableStore.index()
})
</script>
<style lang="scss" scoped>
.header_btn {
    width: 100%;
    height: 30px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
}
</style>
