<template>
  <ScreenToolbar
    v-model:currentGrid="currentGrid"
    v-model:playIntervalTime="playIntervalTime"
    :isPlaying="isPlaying"
    :isPaused="isPaused"
    :currentRound="currentRound"
    :totalRound="totalRound"
    @prev-round="playPreviousRound"
    @next-round="playNextRound"
    @toggle-pause="togglePause"
  />
  <CamerasGrid :cameraInPlay="cameraInPlayOfCurrentRound" :currentGrid="currentGrid" :sensorData="sensorData" />
</template>

<script setup lang="ts">
  import { computed, onBeforeUnmount, ref, watch } from 'vue';
  import { storeToRefs } from 'pinia';
  import ScreenToolbar from './ScreenToolbar.vue';
  import CamerasGrid from './CamerasGrid.vue';
  import type { LocalGridType } from './ScreenToolbar.vue';
  import { useSensorRealtime } from './useSensorRealtime';
  import { useCameraGroupList } from '@/store/modules/useCameraGroupList';
  import type { SensorGroupView } from '@/api/sensor-group/type';

  const currentGrid = ref<LocalGridType>(9);
  const playIntervalTime = ref<number>(60);
  const isPaused = ref<boolean>(false);
  const currentRound = ref<number>(1);
  let autoplayTimer: ReturnType<typeof setInterval> | null = null;

  const { sensorData, connect, close } = useSensorRealtime();
  const { playingGroup } = storeToRefs(useCameraGroupList());

  watch(
    () => playingGroup.value as unknown as SensorGroupView | undefined,
    (group) => {
      if (!group) {
        playIntervalTime.value = 60;
        isPaused.value = false;
        return;
      }

      // refreshIntervalSec 直接映射到播放间隔，接口缺省时默认 60 秒
      playIntervalTime.value = normalizePlayInterval(group.refreshIntervalSec ?? 60);
      // ：1=轮播，0=不轮播；前端 isPaused 语义：true=已暂停
      isPaused.value = !(group.isPaused ?? 1);
    },
    { immediate: true, deep: true },
  );

  // playingGroup.details 取 sensorId
  watch(
    () => (playingGroup.value as unknown as SensorGroupView)?.details,
    (details) => {
      const ids = (details || []).map((d) => d.id);
      if (ids.length > 0) {
        connect(ids);
      } else {
        close();
      }
    },
    { immediate: true, deep: true },
  );

  const currentGroupSensors = computed(() => {
    return ((playingGroup.value as unknown as SensorGroupView)?.details || []) as SensorGroupView['details'];
  });

  const totalRound = computed(() => {
    if (currentGroupSensors.value.length === 0) return 1;
    return Math.max(1, Math.ceil(currentGroupSensors.value.length / currentGrid.value));
  });

  const isPlaying = computed(() => totalRound.value > 1);

  const cameraInPlayOfCurrentRound = computed(() => {
    const startIndex = (currentRound.value - 1) * currentGrid.value;
    const endIndex = startIndex + currentGrid.value;
    return currentGroupSensors.value.slice(startIndex, endIndex);
  });

  function normalizePlayInterval(value: number) {
    const integerValue = Math.floor(Number(value));
    if (Number.isNaN(integerValue) || integerValue <= 0) return 60;
    return integerValue;
  }

  function stopAutoplay() {
    if (!autoplayTimer) return;
    clearInterval(autoplayTimer);
    autoplayTimer = null;
  }

  function playNextRound(withLoop = false) {
    if (totalRound.value <= 1) {
      currentRound.value = 1;
      return;
    }

    const nextRound = currentRound.value + 1;
    if (nextRound > totalRound.value) {
      currentRound.value = withLoop ? 1 : totalRound.value;
      return;
    }

    currentRound.value = nextRound;
  }

  function playPreviousRound() {
    if (totalRound.value <= 1) {
      currentRound.value = 1;
      return;
    }

    currentRound.value = Math.max(1, currentRound.value - 1);
  }

  function startAutoplayIfNeeded() {
    stopAutoplay();

    if (!isPlaying.value || isPaused.value) {
      return;
    }

    autoplayTimer = setInterval(() => {
      playNextRound(true);
    }, normalizePlayInterval(playIntervalTime.value) * 1000);
  }

  function togglePause() {
    if (!isPlaying.value) return;
    isPaused.value = !isPaused.value;
  }

  watch(
    () => currentGrid.value,
    () => {
      currentRound.value = 1;
    },
  );

  watch(
    () => currentGroupSensors.value.length,
    () => {
      if (currentRound.value > totalRound.value) {
        currentRound.value = totalRound.value;
      }
      if (currentRound.value <= 0) {
        currentRound.value = 1;
      }
    },
  );

  watch(
    () => playIntervalTime.value,
    (value) => {
      playIntervalTime.value = normalizePlayInterval(value);
      startAutoplayIfNeeded();
    },
  );

  watch([isPlaying, isPaused, totalRound], () => {
    if (currentRound.value > totalRound.value) {
      currentRound.value = totalRound.value;
    }
    startAutoplayIfNeeded();
  });

  onBeforeUnmount(() => {
    stopAutoplay();
    close();
  });
</script>

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