<template>
    <div class="default-main">
        <div class="analyze-dvr" v-show="!isWaveCharts" :style="{ height: pageHeight.height }" v-loading="loading">
            <DeviceTree @node-click="nodeClick" @init="nodeClick" @deviceTypeChange="deviceTypeChange"></DeviceTree>
            <div class="analyze-dvr-right" v-if="tableStore.table.params.deviceId">
                <TableHeader datePicker showExport>
                    <template v-slot:select>
                        <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>
                </TableHeader>
                <Table v-if="view" ref="tableRef"></Table>
            </div>
            <el-empty v-else description="请选择设备" class="analyze-dvr-right" />
        </div>
        <waveFormAnalysis v-loading="loading" v-if="isWaveCharts" ref="waveFormAnalysisRef"
            @handleHideCharts="isWaveCharts = false" :wp="wp" style="padding: 10px" />
        <!-- <div :style="{ height: pageHeight.height }" style="padding: 10px; overflow: hidden" v-if="!view">
            <el-row>
                <el-col :span="12">
                    <div v-if="view2" style="display: flex">
                        <el-radio-group v-model.trim="value" @change="changeView">
                            <el-radio-button label="一次值" :value="1" />
                            <el-radio-button label="二次值" :value="2" />

                        </el-radio-group>
                    </div>
                </el-col>
                <el-col :span="12">
                    <el-button v-if="view2" @click="backbxlb" class="el-icon-refresh-right" icon="el-icon-Back"
                        style="float: right">
                        返回
                    </el-button>
                </el-col>
            </el-row>

            <el-tabs v-if="view2" class="default-main" v-model.trim="bxactiveName" @tab-click="bxhandleClick">
                <el-tab-pane label="瞬时波形" name="ssbx" class="boxbx pt10 pb10"
                    :style="'height:' + bxecharts + ';overflow-y: scroll;'">
                    <shushiboxi v-if="bxactiveName == 'ssbx' && showBoxi" :value="value" :boxoList="boxoList" :wp="wp">
                    </shushiboxi>
                </el-tab-pane>
                <el-tab-pane label="RMS波形" class="boxbx pt10 pb10" name="rmsbx"
                    :style="'height:' + bxecharts + ';overflow-y: scroll;'">
                    <rmsboxi v-if="bxactiveName == 'rmsbx' && showBoxi" :value="value" :boxoList="boxoList" :wp="wp">
                    </rmsboxi>
                </el-tab-pane>
            </el-tabs>
        </div> -->
    </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 Table from '@/components/table/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 { getFileZip } from '@/api/cs-harmonic-boot/datatrend'
import { ElMessage } from 'element-plus'
defineOptions({
    name: 'govern/analyze/DVR/index'
})
const pageHeight = mainHeight(20)
const loading = ref(false)
const view = ref(true)
const view2 = ref(false)
const showBoxi = ref(true)
const isWaveCharts = ref(false)
const bxactiveName = ref('ssbx')
const boxoList: any = ref({})
const wp = ref({})
const eventList = ref([
    {
        value: 'Evt_Sys_DipStr',
        label: '电压暂降'
    },
    {
        value: 'Evt_Sys_SwlStr',
        label: '电压暂升'
    },
    {
        value: 'Evt_Sys_IntrStr',
        label: '电压中断'
    }
])
const locationList = ref([
    {
        value: 'grid',
        label: '电网侧'
    },
    {
        value: 'load',
        label: '负载侧'
    }
])
const waveFormAnalysisRef = ref()

const tableStore = new TableStore({
    url: '/cs-harmonic-boot/eventUser/queryEventpageWeb',
    method: 'POST',
    column: [
        {
            field: 'index',
            title: '序号',
            width: '80',
            formatter: (row: any) => {
                return (tableStore.table.params.pageNum - 1) * tableStore.table.params.pageSize + row.rowIndex + 1
            }
        },
        { title: '事件描述', field: 'showName', minWidth: 150 },
        {
            title: '发生位置', field: 'evtParamPosition', minWidth: 150,
            formatter: (row: any) => {
                const val = row.cellValue
                if (val === null || val === undefined || val === '' || val === '-') return '/'

                return val
            }
        },
        {
            title: '持续时间(s)',
            field: 'evtParamTm',
            sortable: true,
            minWidth: 110,
            formatter: (row: any) => {
                const val = row.cellValue
                if (val === null || val === undefined || val === '' || val === '-') return '/'
                const num = Number(val)
                if (Number.isNaN(num)) return '/'
                return Math.floor(num * 10000) / 100
            }
        },
        {
            title: '暂降(聚升)幅值(%)',
            field: 'evtParamVVaDepth',
            minWidth: 150,
            formatter: (row: any) => {
                let a = row.cellValue.split('%')[0] - 0
                return a ? a.toFixed(2) : '/'
            },
            sortable: true
        },
        { title: '发生时刻', field: 'startTime', sortable: true, minWidth: 180 },
        {
            title: '操作',
            fixed: 'right',
            align: 'center',
            width: '180',
            render: 'buttons',
            buttons: [
                {
                    name: 'edit',
                    text: '波形分析',
                    type: 'primary',
                    icon: 'el-icon-DataLine',
                    render: 'basicButton',
                    loading: 'loading1', 
                    disabled: row => {
                        return !row.wavePath && row.evtParamTm < 20
                    },

                    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
                                    boxoList.value.featureAmplitude =
                                        row.evtParamVVaDepth != '-' ? row.evtParamVVaDepth.split('%')[0] / 100 : null
                                    boxoList.value.persistTime =
                                        row.evtParamTm != '-' ? Math.floor(row.evtParamTm * 10000) / 100 : null
                                    // boxoList.value.systemType = 'WX'
                                    boxoList.value.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(false, 150)
                        })
                    }
                },
                {
                    name: 'edit',
                    text: '暂无波形',
                    type: 'info',
                    icon: 'el-icon-DataLine',
                    render: 'basicButton',
                    disabled: row => {
                        return !(!row.wavePath && row.evtParamTm < 20)
                    }
                },
                {
                    name: 'edit',
                    title: '波形下载',
                    type: 'primary',
                    icon: 'el-icon-Check',
                    loading: 'loading2',
                    render: 'basicButton',
                    disabled: row => {
                        // && row.evtParamTm < 20
                        return !row.wavePath
                    },
                    click: row => {
                        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 = row.wavePath.split('/')[2] || '波形文件' // 设置下载的文件名
                            document.body.appendChild(link)
                            link.click() //执行下载
                            document.body.removeChild(link) //释放标签
                        })
                    }
                }
            ]
        }
    ],
    loadCallback: () => {
        tableStore.table.data.forEach((item: any) => {
            item.loading = false
            item.evtParamTm = item.evtParamTm.split('s')[0]
        })
    }
})
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 && flag.value) {
        loading.value = false
        tableStore.table.params.deviceId = e.id
        nextTick(() => {
            tableStore.index()
        })
    }
}

const changeView = () => {
    showBoxi.value = false
    setTimeout(() => {
        showBoxi.value = true
    }, 0)
}
const bxhandleClick = (tab: any) => {
    if (tab.name == 'ssbx') {
        bxactiveName.value = 'ssbx'
    } else if (tab.name == 'rmsbx') {
        bxactiveName.value = 'rmsbx'
    }
    //  console.log(tab, event);
}
const backbxlb = () => {
    view.value = true
    view2.value = false
}
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>
