<template>
    <div ref="refheader" v-if="!isWaveCharts">
        <TableHeader datePicker showExport>
            <template v-slot:select>
                <el-form-item label="数据来源">
                    <el-cascader
                        placeholder="请选择数据来源"
                        @change="sourceChange"
                        filterable
                        v-model.trim="tableStore.table.params.cascader"
                        :options="deviceTreeOptions"
                        :show-all-levels="false"
                        :props="{ checkStrictly: true }"
                        clearable
                    ></el-cascader>
                    <!-- <el-input maxlength="32" show-word-limit v-model.trim="tableStore.table.params.searchValue" placeholder="请输入设备名称" /> -->
                </el-form-item>
                <!-- <el-form-item label="级别">
                    <el-select v-model.trim="tableStore.table.params.level" placeholder="请选择级别" clearable>
                        <el-option v-for="item in rankOptions" :key="item.value" :label="item.label"
                            :value="item.value"></el-option>
                    </el-select>
                </el-form-item> -->
            </template>
        </TableHeader>

        <Table></Table>
    </div>
    <waveFormAnalysis
        v-loading="loading"
        v-if="isWaveCharts"
        ref="waveFormAnalysisRef"
        @handleHideCharts="isWaveCharts = false"
        :wp="wp"
    />
    <!-- <div style="height: 300px;"> -->

    <!-- <div style="padding: 10px" v-if="!view" v-loading="loading">
        <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" 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> -->
</template>
<script setup lang="ts">
import { ref, onMounted, provide, nextTick } from 'vue'
import TableStore from '@/utils/tableStore'
import Table from '@/components/table/index.vue'
import TableHeader from '@/components/table/header/index.vue'
import shushiboxi from '@/components/echarts/shushiboxi.vue'
import waveFormAnalysis from '@/views/govern/device/control/tabs/components/waveFormAnalysis.vue'
import rmsboxi from '@/components/echarts/rmsboxi.vue'
import { analyseWave, getFileByEventId } from '@/api/common'
import { mainHeight } from '@/utils/layout'
import { ElMessage } from 'element-plus'
import { getFileZip } from '@/api/cs-harmonic-boot/datatrend'
const props = defineProps(['deviceTree'])
const refheader = ref()
const waveFormAnalysisRef = ref()
const view = ref(true)
const isWaveCharts = ref(false)
const view2 = ref(false)
const showBoxi = ref(true)
const loading = ref(false)
const bxactiveName = ref('ssbx')
const boxoList: any = ref({})
const wp = ref({})
const value = ref(1)
const options = ref([
    {
        value: 1,
        label: '一次值'
    },
    {
        value: 2,
        label: '二次值'
    }
])
const rankOptions = ref([
    {
        value: '1',
        label: '1级'
    },
    {
        value: '2',
        label: '2级'
    },
    {
        value: '3',
        label: '3级'
    }
])

const tableStore = new TableStore({
    url: '/cs-harmonic-boot/eventUser/queryEventpageWeb',
    method: 'POST',
    publicHeight: 65,
    exportName: '暂态事件',
    column: [  {
            title: '序号',
            width: 80,
            formatter: (row: any) => {
                return (tableStore.table.params.pageNum - 1) * tableStore.table.params.pageSize + row.rowIndex + 1
            }
        },
        { title: '设备名称', field: 'equipmentName', align: 'center' },
        { title: '工程名称', field: 'engineeringName', align: 'center' },
        { title: '项目名称', field: 'projectName', align: 'center' },
        { title: '发生时刻', field: 'startTime', align: 'center', width: '240',sortable: true },
        { title: '监测点名称', field: 'lineName', align: 'center' },
        { title: '事件描述', field: 'showName', align: 'center' },
        { title: '事件发生位置', field: 'evtParamPosition', align: 'center' },
        { title: '相别', field: 'evtParamPhase', align: 'center' },
        { title: '持续时间(s)', field: 'evtParamTm', align: 'center',sortable: true },
        { title: '暂降(聚升)幅值(%)', minWidth: 100, field: 'evtParamVVaDepth', align: 'center',sortable: true },

        {
            title: '操作',
            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
                        loading.value = true
                        isWaveCharts.value = true
                        await analyseWave(row.id)
                            .then(res => {
                                row.loading1 = false
                                if (res != undefined) {
                                    boxoList.value = row
                                    boxoList.value.featureAmplitude =
                                        row.evtParamVVaDepth != '-' ? row.evtParamVVaDepth - 0 : null
                                    boxoList.value.systemType = 'WX'
                                    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)
                        })
                        // row.loading1 = true
                        // view.value = false
                        // view2.value = true
                        // loading.value = true
                        // boxoList.value = row
                        // boxoList.value.systemType = 'WX'

                        // boxoList.value.persistTime = row.evtParamTm != '-' ? row.evtParamTm - 0 : null
                        // await analyseWave(row.id)
                        //     .then(res => {
                        //         row.loading1 = false
                        //         if (res != undefined) {
                        //             wp.value = res.data

                        //         }
                        //         loading.value = false
                        //     })
                        //     .catch(() => {
                        //         row.loading1 = false
                        //         loading.value = false
                        //     })
                    }
                },
                {
                    name: 'edit',
                    title: '波形下载',
                    type: 'primary',
                    icon: 'el-icon-Check',
                    loading: 'loading2',
                    render: 'basicButton',
                    disabled: row => {
                        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) //释放标签
                        })
                    }
                },
                {
                    name: 'edit',
                    text: '暂无波形',
                    type: 'info',
                    icon: 'el-icon-DataLine',
                    render: 'basicButton',
                    disabled: row => {
                        return  row.showName != '未知'; 
                    }
                },
                {
                 name: 'edit',
                 title: '波形补召',
                 type: 'primary',
                 icon: 'el-icon-Check',
                 render: 'basicButton',
                 disabled: row => {
                     return  row.wavePath || row.showName === '未知';
                 },
                 click: row => {
                        getFileByEventId(row.id).then(res => { 
                            ElMessage.success(res.message)
                            tableStore.index()
                        })
                 }   
                }
            ]
        }
    ],
    beforeSearchFun: () => {
        // if (!tableStore.table.params.deviceId) {
        //     delete tableStore.table.params.deviceId
        // }
    },
    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) : '-'
        })
    }
})

provide('tableStore', tableStore)
//   "target": [],
//   "type": "",
//   "userId": ""
tableStore.table.params.engineeringid = ''
tableStore.table.params.projectId = ''
tableStore.table.params.deviceTypeId = ''
tableStore.table.params.deviceId = ''
tableStore.table.params.type = 0
tableStore.table.params.eventIds = []
tableStore.table.params.status = ''
tableStore.table.params.target = []
tableStore.table.params.userId = ''
tableStore.table.params.cascader = ''
tableStore.table.params.deviceTypeName = ''
// tableStore.table.params.level=''

const deviceTreeOptions: any = ref<any>(props.deviceTree)
deviceTreeOptions.value.map((item: any, index: any) => {
    if (item.children.length == 0) {
        deviceTreeOptions.value.splice(index, 1)
    }
})
const sourceChange = (e: any) => {
    tableStore.table.params.deviceTypeId = ''
    tableStore.table.params.engineeringid = ''
    tableStore.table.params.projectId = ''
    tableStore.table.params.deviceId = ''
    if (e) {
        let name = deviceTreeOptions.value.filter((item: any) => {
            return item.id == e[0]
        })[0].name
        tableStore.table.params.deviceTypeName = name
        if (name == '便携式设备') {
            tableStore.table.params.deviceTypeId = e[0] || ''
            tableStore.table.params.deviceId = e[1] || ''
        } else {
            tableStore.table.params.deviceTypeId = e[0] || ''
            tableStore.table.params.engineeringid = e[1] || ''
            tableStore.table.params.projectId = e[2] || ''
        }
        
    }

    // tableStore.table.params.engineeringid = e[1] || ''
    // tableStore.table.params.projectId = e[2] || ''
    // const zlIndex = deviceTreeOptions.value.findIndex((item: any) => {
    //     return item.name == '治理设备'
    // })
    // const bxsIndex = deviceTreeOptions.value.findIndex((item: any) => {
    //     return item.name == '便携式设备'
    // })

    // console.log("🚀 ~ zlIndex ~ zlIndex:", zlIndex,bxsIndex)

    // //便携式设备特殊处理
    // if (bxsIndex != -1 && deviceTreeOptions.value[bxsIndex].id == e[0] && e.length == 2) {
    //     tableStore.table.params.deviceId = e[1]
    // }
    // //治理设备
    // if (zlIndex != -1 && deviceTreeOptions.value[zlIndex].id == e[0]) {
    //     tableStore.table.params.deviceId = e[2] || ''
    // }
}
const getboxin = async (row: any) => {
    console.log('🚀 ~ getboxin ~ row:', row)
    // boxoList.value = row
    // await analyseWave(row.id).then(res => {
    //     if (res != undefined) {
    //         wp.value = res.data
    //         view.value = false
    //         view2.value = true
    //     }
    // })
}
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
    setTimeout(() => {
        tableStore.table.height = mainHeight(180).height as any
    }, 0)
}
onMounted(() => {
    tableStore.index()
})
const bxecharts = mainHeight(175).height as any
setTimeout(() => {
    tableStore.table.height = mainHeight(200).height as any
}, 0)

const addMenu = () => {}
</script>
<style scoped lang="scss"></style>
