<template>
  <el-card title="MQTT 消息监听（TS 版本）">
    <el-alert
      v-if="mqttMessage"
      title="收到新消息"
      type="success"
      :description="JSON.stringify(mqttMessage, null, 2)"
      show-icon
      style="margin-bottom: 20px;"
    />
    <el-button
      type="primary"
      @click="initMqttConnect"
      :disabled="isConnected"
    >
      连接 MQTT
    </el-button>
    <el-button
      type="danger"
      @click="disconnectMqttConnect"
      :disabled="!isConnected"
      style="margin-left: 10px;"
    >
      断开连接
    </el-button>
    <el-tag v-if="isConnected" type="success">已连接</el-tag>
    <el-tag v-else type="danger">未连接</el-tag>
  </el-card>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { initMqtt, disconnectMqtt, getMqttStatus } from '@/utils/mqtt'

// 定义消息类型接口
interface MqttReceivedMessage {
  topic: string
  message: Record<string, any>
}

// 响应式数据（添加类型注解）
const mqttMessage = ref<MqttReceivedMessage | null>(null)
const isConnected = ref<boolean>(false)

// 计算属性：实时获取连接状态
const mqttStatus = computed(() => getMqttStatus())

// 初始化 MQTT 连接
const initMqttConnect = (): void => {
  initMqtt((message: MqttReceivedMessage) => {
    // 接收消息并更新到页面
    mqttMessage.value = message
    // 业务逻辑处理
    console.log('收到 MQTT 消息：', message)
    ElMessage.success(`收到主题 [${message.topic}] 的新消息`)
  })
  isConnected.value = true
}

// 断开 MQTT 连接
const disconnectMqttConnect = (): void => {
  disconnectMqtt()
  isConnected.value = false
  mqttMessage.value = null
}

// 组件挂载时检查连接状态
onMounted(() => {
  isConnected.value = mqttStatus.value
  // 自动连接（可选）
  // if (!isConnected.value) {
  //   initMqttConnect()
  // }
})

// 组件卸载时断开连接，避免内存泄漏
onUnmounted(() => {
  if (isConnected.value) {
    disconnectMqttConnect()
  }
})
</script>

<style scoped>
.el-card {
  width: 800px;
  margin: 20px auto;
}

.el-tag {
  margin-left: 10px;
}
</style>
