// 查询相机的在线或者离线状态

import { getCameraState } from '@/api/camera/camera';
import useCameraGroupList from '@/store/modules/useCameraGroupList';
import { onMounted, onUnmounted, watch } from 'vue';

export const useCameraStatus = () => {
  const cameraGroupStore = useCameraGroupList();
  let timer = 0;

  const queryCameraState = () => {
    const cameraList = cameraGroupStore.playingGroup?.children || [];
    if (cameraList.length === 0) return;
    const cameraCodes = cameraList.map((x) => x.code);
    getCameraState({ cameraCodeList: cameraCodes }).then((res) => {
      if (res?.length !== cameraCodes.length) return;
      cameraGroupStore.updateCameraStatus(res);
    });
  };

  watch(
    () => cameraGroupStore.playingGroup?.children || [],
    (cameraList) => {
      if (cameraList.length > 0) {
        queryCameraState();
      }
    },
    {
      immediate: true,
      deep: true,
    },
  );

  onMounted(() => {
    timer = window.setInterval(() => {
      queryCameraState();
    }, 1000 * 10);
  });

  onUnmounted(() => {
    window.clearInterval(timer);
  });
};
