<script setup>
import { onMounted, ref, inject, watch, computed } from "vue";
import { useI18n } from "vue-i18n";
import mqtt from "mqtt";
import dayjs from "dayjs";
import { postMqttTopic, postMqttTopicStop } from "@/apis/system";

const { t } = useI18n();
const { openToast, cancelToastOpen } = inject("app_toast");
const { formState } = inject("asset_table_modal_form");
const BASEURL = import.meta.env.VITE_MQTT_BASEURL;
const iotSchemaTag = inject("iotSchemaTag");

// MQTT相關
const mqttClient = ref(null); // MQTT客戶端
const receivedMessages = ref([]); // 儲存接收到的訊息
const countdown = ref(60); // 倒計時初始為 60 秒
const hasStartedCountdown = ref(false); // 是否已開始倒數
let timer = null; // 記錄計時器
let mqttInterval = null;
const mqttCardDataList = ref([]); // 顯示在畫面上的卡片資料

const openModal = async () => {
  if (!mqttClient.value) {
    connectMqtt();
  }
  mqtt_test.showModal();

  // 先立即呼叫一次
  try {
    await postMqttTopic({
      iotTag: iotSchemaTag?.value,
      Topic: formState.value.topic,
    });
    // console.log("首次 postMqttTopic API 已呼叫");
  } catch (error) {
    console.error("首次 postMqttTopic 發送失敗", error);
  }

  // 啟動每 5 秒重複呼叫
  mqttInterval = setInterval(async () => {
    try {
      const res = await postMqttTopic({
        iotTag: iotSchemaTag?.value,
        Topic: formState.value.topic,
      });

      // console.log("postMqttTopic 回傳：", res?.data);

      const payload = res?.data;

      // 確保 payload 結構正確
      if (payload && payload.data && payload.time) {
        const timeAlreadyExists = mqttCardDataList.value.some(
          (item) => item.time === payload.time
        );

        if (!timeAlreadyExists) {
          mqttCardDataList.value.unshift({
            ...payload.data,
            time: payload.time,
          });

          // ⬇第一次收到資料才開始倒數
          if (!hasStartedCountdown.value) {
            hasStartedCountdown.value = true;
            startCountdown();
          }
        } else {
          // console.log("已存在相同時間略過：", payload.time);
        }
      } else {
        // console.warn("回傳資料結構錯誤或缺少 time");
      }
    } catch (error) {
      console.error("postMqttTopic 呼叫失敗：", error);
    }
  }, 5000);
};

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 = () => {
  countdown.value = 60;

  timer = setInterval(() => {
    if (countdown.value > 1) {
      countdown.value--;
    } else {
      clearInterval(timer);
      timer = null;
      onCancel(); // 60秒結束自動關閉
    }
  }, 1000);
};

const onCancel = async () => {
  // 清空資料與狀態
  receivedMessages.value = [];
  mqttCardDataList.value = [];
  countdown.value = 60;
  hasStartedCountdown.value = false;

  mqtt_test.close();

  // 停止 API 呼叫
  try {
    await postMqttTopicStop({
      iotTag: iotSchemaTag?.value,
      Topic: formState.value.topic,
    });
  } catch (error) {
    console.error("postMqttTopicStop 發送失敗", error);
  }

  // 關閉 MQTT
  if (mqttClient.value) {
    mqttClient.value.end();
    mqttClient.value = null;
  }

  // 清除 API Interval
  if (mqttInterval) {
    clearInterval(mqttInterval);
    mqttInterval = null;
  }

  // 清除倒數 Timer
  if (timer) {
    clearInterval(timer);
    timer = null;
  }
};
</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="mqttCardDataList.length > 0" class="overflow-y-auto h-96 mt-4">
        <ul>
          <li
            v-for="(item, index) in mqttCardDataList"
            :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 flex justify-between items-center"
            >
              <span>
                <FontAwesomeIcon :icon="['fas', 'clock']" class="me-1" />
                {{ dayjs(item.time).format("YYYY-MM-DD HH:mm:ss") }}
              </span>

              <!-- 只在第一筆資料加上「最新」標籤 -->
              <span
                v-if="index === 0"
                class="text-xs text-white bg-green-600 px-2 py-1 rounded"
              >
                New
              </span>
            </strong>

            <!-- 動態顯示除了 time 以外的所有欄位 -->
            <template v-for="[key, value] in Object.entries(item)" :key="key">
              <p v-if="key !== 'time'" class="text-sm break-words">
                <strong>{{ key }}：</strong>{{ value }}
              </p>
            </template>
          </li>
        </ul>
      </div>

      <!-- 顯示 loading 和倒計時（只有沒資料才顯示） -->
      <p v-if="mqttCardDataList.length === 0" class="text-center mt-20">
        <Loading />
        <br />
        <span class="text-base">Loading...</span>
      </p>
    </template>
    <template #modalAction>
      <div class="relative w-full flex justify-end items-center gap-12">
        <!-- 資料出現後才顯示倒數計時，置中顯示 -->
        <div
          v-if="mqttCardDataList.length > 0"
          class="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 flex items-center gap-2 text-sm"
        >
          <span>Auto close in</span>
          <span>{{ countdown }}s</span>
        </div>

        <button
          type="reset"
          class="btn btn-outline-success"
          @click.prevent="onCancel"
        >
          {{ t("button.cancel") }}
        </button>
      </div>
    </template>
  </Modal>
</template>

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