<template>
  <section class="min-h-[600px] h-screen">
    <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 h-[70%] gap-4">
      <!-- 左側：即時監控 -->
      <div class="relative w-full flex-1 rounded border overflow-hidden">
        <iframe
          :src="monitorUrl"
          class="absolute inset-0 w-full h-full"
          allow="autoplay; fullscreen; picture-in-picture"
          referrerpolicy="no-referrer"
        ></iframe>
      </div>

      <!-- 右側：開始/結束偵測（已移除選擇資料夾相關 UI） -->
      <aside class="w-1/2 flex flex-col gap-6 p-4">
        <div class="flex gap-3">
          <button
            class="btn btn-add w-40"
            @click="startDetection"
            :disabled="isStarting || !selectedMainId"
            :title="!selectedMainId ? $t('rtsp.pleaseSelectDevice') : ''"
          >
            {{ $t("rtsp.start") }}
          </button>
          <button
            class="btn btn-error text-white w-40"
            @click="stopDetection"
            :disabled="isStopping || !selectedMainId"
            :title="!selectedMainId ? $t('rtsp.pleaseSelectDevice') : ''"
          >
            {{ $t("rtsp.stop") }}
          </button>
        </div>

        <p v-if="message" class="text-sm text-info">{{ message }}</p>
      </aside>
    </div>
  </section>
</template>

<script>
import { getSystemDevices } from "@/apis/system";
import { setRtspEnable } from "@/apis/rtsp"; // 已移除 setSambaDirectory
import useActiveBtn from "@/hooks/useActiveBtn";

const FILE_BASEURL = import.meta.env.VITE_FILE_API_BASEURL;
const DEFAULT_MONITOR_URL =
  "http://192.168.0.219:8026/?url=rtsp://admin02:mjmAdmin_99@192.168.0.200:554/stream1?tcp";

export default {
  name: "Rtsp",
  setup() {
    const { items, changeActiveBtn, setItems, selectedBtn } = useActiveBtn();
    return { items, changeActiveBtn, setItems, selectedBtn };
  },
  data() {
    return {
      monitorUrl: DEFAULT_MONITOR_URL,

      // 偵測控制
      isStarting: false,
      isStopping: false,

      // UI 狀態
      message: "",

      // 資料整理
      deviceData: {},
      rtspDevices: [], // { main_id, full_name, rtsp_url, ... }
      selectedMainId: null, // 目前選中的設備 main_id
    };
  },
  async mounted() {
    await this.getData();
  },
  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: {
    async getData() {
      try {
        const useBuildingStore = (await import("@/stores/useBuildingStore"))
          .default;
        const buildingStore = useBuildingStore();
        const building_guid =
          buildingStore?.selectedBuilding?.building_guid || "";

        const res = await getSystemDevices({ building_guid });
        const transformedData = {};

        (res?.data || []).forEach((floor) => {
          if (floor?.device_list?.length > 0) {
            const fullUrl = floor.floor_map_name;
            const uuid = fullUrl ? fullUrl.replace(/\.svg$/, "") : "";
            transformedData[uuid] = floor.device_list.map((device) => {
              let x = 0,
                y = 0;
              try {
                const coordinates = JSON.parse(
                  device?.device_coordinate || "[0,0]"
                );
                x = Number(coordinates?.[0] ?? 0);
                y = Number(coordinates?.[1] ?? 0);
              } catch (_) {}

              let state = "Online";
              let bgColor = device?.device_normal_color;
              if (
                device?.device_status === "Offline" ||
                device?.device_status == null
              ) {
                state = "Offline";
                bgColor = device?.device_close_color;
              }
              if (device?.device_status === "Error") {
                state = "Error";
                bgColor = device?.device_error_color;
              }

              return [
                x,
                y,
                {
                  device_number: device?.device_number || "",
                  device_coordinate: device?.device_coordinate || "",
                  device_image_url: device?.device_image_url,
                  full_name: device?.full_name,
                  main_id: device?.main_id,
                  points: device?.points || [],
                  floor: floor?.full_name,
                  state,
                  icon: device?.device_image
                    ? `${FILE_BASEURL}/upload/device_icon/${device.device_image}`
                    : "",
                  bgColor,
                  Online_color: device?.device_normal_color,
                  Offline_color: device?.device_close_color,
                  Error_color: device?.device_error_color,
                  brand: device?.brand || "",
                  device_model: device?.device_model,
                  operation_name: device?.operation_name,
                  operation_contact_person: device?.operation_contact_person,
                  buying_date: device?.buying_date,
                  created_at: device?.created_at,
                  bgSize: 50,
                  is_rtsp: device?.is_rtsp === true,
                  rtsp_url: device?.rtsp_url || "",
                },
              ];
            });
          }
        });

        this.deviceData = transformedData;

        const allRows = Object.values(transformedData).flat();
        this.rtspDevices = allRows
          .map((row) => row?.[2])
          .filter((p) => p && p.is_rtsp && p.rtsp_url)
          .reduce((acc, cur) => {
            if (!acc.find((x) => x.main_id === cur.main_id)) acc.push(cur);
            return acc;
          }, [])
          .sort((a, b) => (a.full_name || "").localeCompare(b.full_name || ""));

        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,
          ...d,
        }));
        this.setItems(cate);

        if (this.rtspDevices.length > 0) {
          const first = this.rtspDevices[0];
          this.selectedMainId = first.main_id;
          this.monitorUrl = first.rtsp_url;
        } else {
          this.selectedMainId = null;
          this.monitorUrl = DEFAULT_MONITOR_URL;
        }
      } catch (err) {
        console.error("getData() 失敗", err);
        this.setItems([]);
        this.rtspDevices = [];
        this.selectedMainId = null;
        this.monitorUrl = DEFAULT_MONITOR_URL;
      }
    },

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

    // 開始偵測：setRtspEnable(true)
    async startDetection() {
      if (!this.selectedMainId) {
        this.message = this.$t("rtsp.pleaseSelectDevice");
        return;
      }
      this.isStarting = true;
      try {
        await setRtspEnable({
          main_id: this.selectedMainId,
          enable: true,
        });
        this.message = this.$t("rtsp.startSuccess");
      } catch (e) {
        console.error(e);
        this.message = this.$t("rtsp.startFail");
      } finally {
        this.isStarting = false;
      }
    },

    // 結束偵測：setRtspEnable(false)
    async stopDetection() {
      if (!this.selectedMainId) {
        this.message = this.$t("rtsp.pleaseSelectDevice");
        return;
      }
      this.isStopping = true;
      try {
        await setRtspEnable({
          main_id: this.selectedMainId,
          enable: false,
        });
        this.message = this.$t("rtsp.stopSuccess");
      } catch (e) {
        console.error(e);
        this.message = this.$t("rtsp.stopFail");
      } finally {
        this.isStopping = false;
      }
    },
  },
};
</script>
