<template>
    <div>
        <!-- 全局暂降事件 -->
        <el-drawer v-model="drawer" title="暂降事件" size="1050px" :before-close="handleClose">
            <div :style="height">
                <vxe-table
                    v-bind="defaultAttribute"
                    v-loading="isLoading"
                    height="100%"
                    ref="xTable1Ref"
                    :data="eventList.slice((pageNum - 1) * pageSize, pageNum * pageSize)"
                >
                    <!-- <vxe-column type="seq" width="70px" title="序号"></vxe-column> -->
                    <vxe-column field="time" width="180px"       sortable title="暂降发生时刻"></vxe-column>
                    <vxe-column field="eventValue" width="160px" sortable title="暂降(骤升)幅值(%)">
                        <template #default="{ row }">
                            {{ Math.floor(row.eventValue * 10000) / 100 }}
                        </template>
                    </vxe-column>
                    <vxe-column field="persistTime" width="120px" sortable title="持续时间(s)">
                        <template #default="{ row }">
                            {{ Math.floor(row.persistTime * 1000) / 1000 }}
                        </template>
                    </vxe-column>
                    <vxe-column field="eventType" width="100px" title="触发类型">
                        <template #default="{ row }">
                            {{ event.filter(item => item.id == row.eventType)[0]?.name || '/' }}
                        </template>
                    </vxe-column>
                    <vxe-column field="powerCompany" title="变电站" width="100px"></vxe-column>
                    <vxe-column field="powerCompany" title="供电公司" width="100px"></vxe-column>
                    <vxe-column field="lineName" title="监测点"></vxe-column>
                </vxe-table>
                <div class="table-pagination mt10">
                    <el-pagination
                        v-model:currentPage="pageNum"
                        v-model:page-size="pageSize"
                        :page-sizes="[10, 20, 50, 100, 200]"
                        background
                        layout="sizes,total, ->, prev, pager, next, jumper"
                        :total="eventList.length"
                    ></el-pagination>
                </div>
            </div>
        </el-drawer>
    </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { defaultAttribute } from '@/components/table/defaultAttribute'
import { mainHeight } from '@/utils/layout'
import { useDictData } from '@/stores/dictData'
// import MQTT from '@/utils/mqtt'
import socketClient from '@/utils/webSocketClient'
const dictData = useDictData()
const event = dictData.getBasicData('Event_Statis')
import { useAdminInfo } from '@/stores/adminInfo'
const adminInfo = useAdminInfo()
const height = mainHeight(20)
const drawer = ref(false)
const isLoading = ref(false)
const eventList = ref([])
const pageNum = ref(1)
const pageSize = ref(20)
const open = () => {
    drawer.value = true
}
const handleClose = (done: any) => {
    drawer.value = false
    done()
}
const dataSocket = reactive({
    socketServe: socketClient.Instance
})
// const init = async () => {
//     const mqttClient = new MQTT('/sendEvent')
//     // 设置消息接收回调
//     try {
//         await mqttClient.init()

//         // 订阅主题
//         await mqttClient.subscribe()
//         // 设置消息接收回调
//         mqttClient.onMessage((topic, message) => {
//             const msg = JSON.parse(message.toString())
//         //    console.log('🚀 ~ init ~ msg:', msg)
//             if (msg.deptList.includes(adminInfo.$state.deptId)) {
//                 drawer.value = true
//                 isLoading.value = true
//                 eventList.value.unshift(msg)
//                 setTimeout(() => {
//                     isLoading.value = false
//                 }, 500)
//             }
//         })
//     } catch (error) {
//         // console.error('MQTT 初始化失败:', error)
//     }
// }
const socket = async () => {
    const url = localStorage.getItem('WebSocketUrl3') || 'null' //'ws://192.168.2.130:10203/event/'

    // const url = 'ws://192.168.1.68:10203/event/'

    await dataSocket.socketServe.connect(`${url}${adminInfo.id}`)

    await dataSocket.socketServe.registerCallBack('message', (res: any) => {
        if (res.deptList.includes(adminInfo.$state.deptId)) {
            drawer.value = true
            isLoading.value = true
            eventList.value.unshift(res)
            setTimeout(() => {
                isLoading.value = false
            }, 500)
        }
        // logList.value.push({
        //     type: res.code == 500 ? 'error' : '',
        //     time: formatDate(new Date(), 'YYYY-MM-DD hh:mm:ss'),
        //     name: res.message
        // })
    })
}

onUnmounted(() => {
    dataSocket.socketServe?.closeWs()
})

onMounted(() => {
    // startMqtt('/sendEvent', (topic, message) => {
    //     const msg = JSON.parse(message.toString())
    //     console.log(msg)
    // })

    setTimeout(() => {
        socket()
    }, 3000)
})
defineExpose({
    open,
    eventList
})
</script>
<style lang="scss" scoped></style>
