<template>
<div class="mqtt-client">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h2>MQTT Client</h2>
          <el-tag :type="connectionStatus === 'Connected' ? 'success' : 'danger'">
            {{ connectionStatus }}
          </el-tag>
        </div>
      </template>

      <!-- 连接配置 -->
      <div class="connection-settings">
        <el-form :model="mqttConfig" label-width="120px">
          <el-form-item label="Broker URL">
            <el-input v-model="mqttConfig.url" :disabled="isConnected" />
          </el-form-item>
          <el-form-item label="Topic">
            <el-input v-model="mqttConfig.topic" :disabled="isConnected" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="toggleConnection" :loading="connecting">
              {{ isConnected ? 'Disconnect' : 'Connect' }}
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 消息发送 -->
      <div class="message-sender" v-if="isConnected">
        <el-input
          v-model="messageToSend"
          placeholder="Enter message to send"
          :rows="3"
          type="textarea"
        />
        <el-button type="primary" @click="sendMessage" :disabled="!messageToSend" class="send-btn">
          Send Message
        </el-button>
      </div>

      <!-- 消息列表 -->
      <div class="message-list">
        <h3>Messages</h3>
        <el-timeline>
          <el-timeline-item
            v-for="(msg, index) in messages"
            :key="index"
            :type="msg.type === 'sent' ? 'primary' : 'success'"
            :timestamp="msg.timestamp"
          >
            <el-card class="message-card">
              <p><strong>{{ msg.type === 'sent' ? 'Sent' : 'Received' }}:</strong></p>
              <p>{{ msg.content }}</p>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-card>
  </div>
</template>
<script>
/**
 * 引入 npm install mqtt --save
 * 父组件用法介绍
 * 引入该组件
 * 使用 <MqttClinent v-model="mqttThemeName" @input="mqttArrived" @mqttError="mqttError" ref="mqttName" />
 * v-model 里面写入订阅的主题（mqttThemeName）
 * mqttArrived(val){} 方法用来处理消息返回的事件方法
 * mqtt链接异常方法的接受 mqttError(error){}
 * 父组件手动调用重连方法 this.$refs.mqttName.mqttReconnect()
 */
import mqtt from "mqtt"
var client
const options = {
  connectTimeout: 40 * 1000,
  clean: true,
  clientId: "clientId",
  username: "MQTT_USERNAME",
  password: "MQTT_PASSWORD"
}
client = mqtt.connect('MQTT_SERVICE', options)

export default {
  name: "MqttClient",
  props: {
    value: {
      type: String,
      default: ""
    },
  },
  data() {
    return {
    };
  },
  created() {
    // this.initConnect()
  },
  methods: {
    initConnect() {
      console.log(2)
      // 订阅消息
      client.on("connect", (e) => {
        client.subscribe(this.value, { qos: 0 }, (error) => {
          if (!error) {
            console.log("消息订阅成功！")
          } else {
            console.log("消息订阅失败！")
          }
        });
      });
      //  接收消息
      client.on("message", (topic, message) => {
        // 消息内容 我这里后台返回的是Json的所以转了一下， 有的是[object object] 就用 message.toString() 转化
        this.$emit("input", JSON.parse(message))
        console.log(`来自:${topic}的消息:${JSON.parse(message)}`)
      })
      // 断开发起重连（非必须）
      client.on("reconnect", (error) => {
        console.log("正在重连:", error)
      })
      // 链接异常处理（非必须）
      client.on("error", (error) => {
        this.$emit("mqttError", error)
        console.log("连接失败:", error)
      })
    },
    // 如果手动发起重连 【 父组件手动调用重连方法 this.$refs.mqttName.mqttReconnect() 】
    mqttReconnect(){
      client.on("reconnect", (error) => {
        console.log("正在手动重连:", error)
      })
    }
  },
};
</script>
<style lang="scss" scoped>
.mqtt-client {
  width: 800px;
  margin: 20px auto;
  padding: 0 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.connection-settings {
  margin-bottom: 20px;
}

.message-sender {
  margin-bottom: 20px;
}

.send-btn {
  margin-top: 10px;
}

.message-list {
  margin-top: 20px;
}

.message-card {
  margin-bottom: 10px;
}

.el-timeline-item {
  margin-bottom: 20px;
}
</style>

