<script setup>
import { onMounted, ref, inject, watch, computed } from "vue";
import { useI18n } from "vue-i18n";
import mqtt from "mqtt";
import dayjs from "dayjs";

const { t } = useI18n();
const { openToast, cancelToastOpen } = inject("app_toast");
const { formState } = inject("asset_table_modal_form");
const BASEURL = import.meta.env.VITE_MQTT_BASEURL;
// MQTT相關
const mqttClient = ref(null); // MQTT客戶端
const receivedMessages = ref([]); // 儲存接收到的訊息
const countdown = ref(60); // 倒計時初始為 60 秒
let timer = null; // 記錄計時器

const openModal = () => {
  if (!mqttClient.value) {
    connectMqtt();
  }
  mqtt_test.showModal();
  startCountdown(); // 開始倒計時
};

const connectMqtt = () => {
  const topic = formState.value.topic || ""; // 取得主題
  const mqttHost = `${BASEURL}`;
  const protocol = "wss"; // 根據伺服器配置，需要設置為 "ws" 或 "wss"
  mqttClient.value = mqtt.connect(mqttHost, {
    protocol,
    reconnectPeriod: 1000, // 每秒嘗試重新連線
    username: "admin", // MQTT 帳號
    password: "mjmadmin@99", // MQTT 密碼
    port: 443,
  });

  mqttClient.value.on("connect", () => {
    console.log("MQTT 已連接");
    if (topic) {
      mqttClient.value.subscribe(topic, (err) => {
        if (!err) {
          console.log(`已訂閱主題: ${topic}`);
        } else {
          console.error("訂閱失敗: ", err);
        }
      });
    }
  });

  mqttClient.value.on("message", (topic, message) => {
    // 儲存接收到的訊息
    const now = dayjs(); // 使用 dayjs() 取得當前時間
    const timestamp = now.format("YYYY-MM-DD HH:mm:ss");

    receivedMessages.value.push({
      topic,
      message: message.toString(),
      timestamp: timestamp,
    });
    clearInterval(timer); // 收到訊息後清除倒計時
  });

  mqttClient.value.on("error", (err) => {
    console.error("MQTT 連線錯誤: ", err);
  });
};

const startCountdown = () => {
  if (timer) return; // 防止重複啟動計時器
  timer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--;
    } else {
      onCancel(); // 1分鐘後如果沒有收到訊息則觸發 onCancel
    }
  }, 1000);
};

const onCancel = () => {
  receivedMessages.value = [];
  mqtt_test.close();

  // 斷開 MQTT 連線
  if (mqttClient.value) {
    mqttClient.value.end();
    mqttClient.value = null;
  }

  // 重置倒計時
  if (timer) {
    clearInterval(timer);
    timer = null; // 清除計時器引用
  }
  countdown.value = 60;
};
</script>

<template>
  <div class="flex w-72">
    <Input :value="formState" name="topic">
      <template #topLeft>MQTT Topic</template>
    </Input>
    <button type="button" class="btn btn-add mt-11 ms-1" @click="openModal">
      <font-awesome-icon :icon="['fas', 'cog']" />
      Test
    </button>
  </div>

  <Modal id="mqtt_test" title="MQTT Topic" :onCancel="onCancel" width="400">
    <template #modalContent>
      <!-- 顯示接收到的訊息 -->
      <div v-if="receivedMessages.length > 0" class="overflow-y-auto h-96">
        <ul>
          <li
            v-for="(message, index) in receivedMessages"
            :key="index"
            class="bg-base-200 rounded-md text-wrap shadow shadow-slate-400 p-4 my-2 me-2"
          >
            <strong class="text-base block text-info mb-2"
              >{{ message.topic }} :</strong
            >
            <p class="text-sm break-words">{{ message.message }}</p>
            <p class="text-xs text-slate-200 pt-2">
              <FontAwesomeIcon :icon="['fas', 'clock']" class="me-1" />
              {{ message.timestamp }}
            </p>
          </li>
        </ul>
      </div>
      <!-- 顯示 loading 和倒計時 -->
      <p v-else class="text-center mt-20">
        <Loading />
        <br />
        <span class="text-base">{{ countdown }} seconds</span>
      </p>
    </template>
    <template #modalAction>
      <button
        type="reset"
        class="btn btn-outline-success mr-2"
        @click.prevent="onCancel"
      >
        {{ t("button.cancel") }}
      </button>
    </template>
  </Modal>
</template>

<style lang="scss" scoped></style>
