<script>
import { getRtspDevices } from "@/apis/rtsp";
import { postQueryAlarmLog } from "@/apis/alert";
import useActiveBtn from "@/hooks/useActiveBtn";
import useSearchParam from "@/hooks/useSearchParam";
import AlertSearchTimeRange from "@/views/alert/components/AlertQuery/AlertSearchTimeRange.vue";
import Table from "@/components/customUI/Table.vue";

const DEFAULT_MONITOR_URL =
  "http://192.168.0.219:8026/?url=rtsp://admin02:mjmAdmin_99@192.168.0.200:554/stream1";

export default {
  name: "Rtsp",
  components: { Table, AlertSearchTimeRange },
  setup() {
    const { items, changeActiveBtn, setItems, selectedBtn } = useActiveBtn();
    const { searchParams } = useSearchParam();
    return { items, changeActiveBtn, setItems, selectedBtn, searchParams };
  },
  data() {
    return {
      monitorUrl: DEFAULT_MONITOR_URL,
      rtspDevices: [],
      selectedMainId: null,
      tableLoading: false,
      dataSource: [],
    };
  },
  computed: {
    currentDevice() {
      if (!this.selectedMainId) return null;
      return (
        this.rtspDevices.find((d) => d.main_id === this.selectedMainId) || null
      );
    },
    columns() {
      return [
        { key: "id", title: this.$t("alert.uuid") || "UUID" },
        { key: "created_at", title: this.$t("alert.time") || "Time" },
        { key: "reason", title: this.$t("alert.error_msg") || "Reason" },
      ];
    },
  },
  async mounted() {
    await this.loadRtspDevices();
    // ★ 設定近 7 天並立即查一次
    this.setLast7Days();
    if (this.selectedMainId) {
      await this.searchLogs();
    }
  },
  watch: {
    selectedBtn: {
      handler(newVal) {
        if (!newVal) return;
        const found = this.rtspDevices.find((r) => r.main_id === newVal.key);
        if (found) this.selectDevice(found);
      },
      deep: true,
    },
  },
  methods: {
    // 工具：轉成 YYYY-MM-DD（考慮時區）
    toISO(d) {
      return new Date(d.getTime() - d.getTimezoneOffset() * 60000)
        .toISOString()
        .slice(0, 10);
    },
    // ★ 將查詢區間設為「近 7 天」
    setLast7Days() {
      const today = new Date();
      const start = new Date();
      // 與你在 AlertSearchTimeRange 的 7d 快捷一致：往回 7 天到今天
      start.setDate(start.getDate() - 7);
      this.searchParams.Start_date = this.toISO(start);
      this.searchParams.End_date = this.toISO(today);
    },

    async loadRtspDevices() {
      try {
        const res = await getRtspDevices({});
        const list = Array.isArray(res) ? res : res?.data || [];

        this.rtspDevices = list;

        // 建立 Tabs
        const cate = this.rtspDevices.map((d, index) => ({
          title: d.full_name || d.main_id,
          key: d.main_id,
          active: this.selectedMainId
            ? this.selectedMainId === d.main_id
            : index === 0,
        }));
        this.setItems(cate);

        // 預設選第一台
        if (this.rtspDevices.length > 0) {
          const chosenId = this.selectedMainId ?? this.rtspDevices[0].main_id;
          const chosen =
            this.rtspDevices.find((d) => d.main_id === chosenId) ||
            this.rtspDevices[0];
          this.selectDevice(chosen);
        } else {
          this.selectedMainId = null;
          this.monitorUrl = DEFAULT_MONITOR_URL;
        }
      } catch (err) {
        console.error("loadRtspDevices() 失敗", err);
        this.rtspDevices = [];
        this.setItems([]);
        this.selectedMainId = null;
        this.monitorUrl = DEFAULT_MONITOR_URL;
      }
    },

    // 切換設備 Tab
    selectDevice(d) {
      this.selectedMainId = d.main_id;
      this.monitorUrl = d.rtsp_url || DEFAULT_MONITOR_URL;
      this.dataSource = [];
    },

    // 查詢告警紀錄（讀共用的 searchParams）
    async searchLogs() {
      if (!this.selectedMainId) return;
      const start = this.searchParams?.Start_date;
      const end = this.searchParams?.End_date;
      if (!start || !end) return;

      try {
        this.tableLoading = true;
        const res = await postQueryAlarmLog({
          id: this.selectedMainId,
          start_date: start,
          end_date: end,
        });
        const rows = Array.isArray(res) ? res : res?.data || [];
        this.dataSource = rows.map((d) => ({
          ...d,
          key: d.id,
          // 後端目前未回傳 formId，保留欄位供未來擴充
          formId: d.formId,
        }));
      } catch (e) {
        console.error("searchLogs() 失敗", e);
        this.dataSource = [];
      } finally {
        this.tableLoading = false;
      }
    },

    onRepairOrder(record) {
      console.log("repair order click:", record);
    },
  },
};
</script>

<template>
  <section class="min-h-[600px]">
    <h1 class="text-2xl font-extrabold mb-2">{{ $t("rtsp.title") }}</h1>

    <!-- Tabs：選擇攝影機 -->
    <div class="flex items-center gap-4 mb-6">
      <h2 class="text-lg font-bold whitespace-nowrap">
        {{ $t("rtsp.selectDevice") }} :
      </h2>

      <ButtonConnectedGroup
        :items="items"
        :onclick="
          (e, item) => {
            changeActiveBtn(item);
            const found = rtspDevices.find((r) => r.main_id === item.key);
            if (found) selectDevice(found);
          }
        "
        :className="`flex flex-wrap`"
        size="sm"
        color="info"
      >
        <template #buttonContent="{ item }">
          <span class="text-base">{{ item.title }}</span>
        </template>
      </ButtonConnectedGroup>
    </div>

    <div class="flex gap-4 items-start">
      <!-- 左側：即時監控 -->
      <div
        class="relative w-full flex-1 rounded border overflow-hidden h-[420px] md:h-[520px]"
      >
        <iframe
          :src="monitorUrl"
          class="absolute inset-0 w-full h-full"
          allow="autoplay; fullscreen; picture-in-picture"
          referrerpolicy="no-referrer"
        ></iframe>
      </div>

      <!-- 右側：查詢告警紀錄（日期 + 表格） -->
      <aside class="w-1/2 flex flex-col gap-4 px-4">
        <div
          class="w-full flex flex-wrap items-end gap-3 custom-border px-4 pt-3 pb-4"
        >
          <div class="w-full flex flex-wrap items-center justify-start gap-4">
            <h2 class="text-lg font-bold">{{ $t("rtsp.normalQuery") }} :</h2>

            <!-- 選擇開始與結束時間 -->
            <AlertSearchTimeRange quickButtonType="7d" />
            <button
              class="btn btn-search"
              :disabled="
                !selectedMainId ||
                !searchParams?.Start_date ||
                !searchParams?.End_date ||
                tableLoading
              "
              :title="!selectedMainId ? $t('rtsp.pleaseSelectDevice') : ''"
              @click.stop.prevent="searchLogs"
            >
              <font-awesome-icon :icon="['fas', 'search']" class="text-lg" />
              {{ $t("button.search") || "Search" }}
            </button>
          </div>
        </div>

        <!-- 表格（交由 Table 內建分頁處理，給全量 dataSource） -->
        <Table
          :loading="tableLoading"
          :columns="columns"
          :dataSource="dataSource"
          rowKey="key"
        >
          <template #bodyCell="{ record, column }">
            <template v-if="column.key === 'repairOrder'">
              <button
                class="btn btn-sm btn-success text-white whitespace-nowrap"
                @click.stop.prevent="onRepairOrder(record)"
              >
                <span v-if="record.formId">{{ record.formId }}</span>
                <span v-else>
                  <font-awesome-icon :icon="['fas', 'plus']" />
                  {{ $t("alert.repair_order_number") || "Repair Order" }}
                </span>
              </button>
            </template>
          </template>
        </Table>
      </aside>
    </div>
  </section>
</template>
