<template>
    <div>
        <div class="analyze-dvr" v-show="!isWaveCharts" :style="{ height: pageHeight.height }" v-loading="loading">
            <!-- <DeviceTree @node-click="nodeClick" @init="nodeClick" @deviceTypeChange="deviceTypeChange"></DeviceTree> -->
            <APFTree @node-click="nodeClick" :height="60" :type="'dvr'" @init="nodeClick"
                @deviceTypeChange="deviceTypeChange"></APFTree>
            <div class="analyze-dvr-right" v-if="tableStore.table.params.deviceId">
                <TableHeader datePicker showExport @onResetForm="onResetForm">
                    <template v-slot:select>
                        <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 label="触发类型">
                            <el-select v-model.trim="tableStore.table.params.eventType" clearable placeholder="请选择事件类型">
                                <el-option v-for="item in eventList" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item> -->
                        <!-- <el-form-item label="位置">
                            <el-select v-model.trim="tableStore.table.params.location" clearable placeholder="请选择位置">
                                <el-option v-for="item in locationList" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item> -->
                    </template>
                    <template v-slot:operation>
                        <el-button type="primary" icon="el-icon-Operation" @click="openFilterDialog">事件筛选</el-button>
                    </template>
                </TableHeader>
                <Table v-if="view" ref="tableRef"></Table>
            </div>
            <el-empty v-else description="请选择设备" class="analyze-dvr-right" />

            <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>
</template>

<script setup lang="ts">
import { ref, nextTick, provide, onMounted } from 'vue'
import { mainHeight } from '@/utils/layout'
import DeviceTree from '@/components/tree/govern/deviceTree.vue'
import TableStore from '@/utils/tableStore'
import APFTree from '@/components/tree/govern/APFTree.vue'
import Table from '@/components/table/index.vue'
import analysisList from '@/views/govern/device/control/analysisList/index.vue'
import waveFormAnalysis from '@/views/govern/device/control/tabs/components/waveFormAnalysis.vue'
import { analyseWave } from '@/api/common'
import TableHeader from '@/components/table/header/index.vue'
import { useDictData } from '@/stores/dictData'
import { getFileZip } from '@/api/cs-harmonic-boot/datatrend'
import { buildWaveExportFileName, getExportSubjectFromRow } from '@/utils/echartMethod'
import MultiCondition from '@/views/govern/alarm/multiCondition.vue'
import { queryByCode, queryByid, queryCsDictTree } from '@/api/system-boot/dictTree'
import { ElMessage } from 'element-plus'
defineOptions({
    name: 'govern/analyze/DVR/index'
})
const DeviceType = ref([])
const pageHeight = mainHeight(80)
const loading = ref(false)
const view = ref(true)

const isWaveCharts = ref(false)
const analysisListRef = ref()
const boxoList: any = ref({})
const wp = ref({})
const filterVisible = ref(false)

const waveFormAnalysisRef = ref()
const dictData = useDictData()
const ReasonList: any = dictData.getBasicData('Event_Reason')
const EventTypeList: any = dictData.getBasicData('Event_Type')
const multiConditionRef = ref<InstanceType<typeof MultiCondition>>()
const tableStore = new TableStore({
    url: '/cs-harmonic-boot/eventUser/queryEventpageWeb',
    method: 'POST',
    publicHeight: 60,
    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')
                    },

                },
                {
                    name: 'edit',
                    text: '波形补召',
                    type: 'primary',
                    icon: 'el-icon-DataLine',
                    render: 'basicButton',
                    loading: 'loading2',
                    disabled: row => {
                        return row.wavePath
                    },
                    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: () => {
        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) : '-'
        })
    }
})
Object.assign(tableStore.table.params, {
    featureAmplitudeMin: undefined,
    featureAmplitudeMax: undefined,
    evtParamTmMin: undefined,
    evtParamTmMax: undefined,
    severityMin: undefined,
    severityMax: undefined,
    fileFlag: ''
})
const flag = ref(false)
tableStore.table.params.type = 0
tableStore.table.params.eventType = ''
tableStore.table.params.location = ''
provide('tableStore', tableStore)
const deviceTypeChange = (val: any, obj: any) => {
    flag.value = true
    nodeClick(obj)
}
const nodeClick = async (e: anyObj) => {
    // console.log("🚀 ~ nodeClick ~ e:", e)
    if ((e.level == 2 || e.level == 3)) {
        loading.value = false
        tableStore.table.params.deviceId = e.id
        nextTick(() => {
            tableStore.index()
        })
    }
}
const openFilterDialog = () => {
    filterVisible.value = true
}
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
        })
    })
})

const bxecharts = mainHeight(95).height as any
</script>

<style lang="scss">
.analyze-dvr {
    display: flex;

    &-right {
        height: 100%;
        overflow: hidden;
        flex: 1;
        // padding: 10px 10px 10px 0;
        display: flex;
        flex-direction: column;
    }
}
</style>
