import { getAllAlgosApi, getCameraAlgoListApi, CameraAlgoItem } from '@/api/camera/camera-preview';
import { defineStore } from 'pinia';
import { ref } from 'vue';
import { useRequest } from 'vue-hooks-plus';
import { TimeRangeItem } from '../components/AlgorithmsSetting/types';
import { DetectionJSON } from '../components/AlgorithmsSetting/utils';

interface CameraAlgoItemInCard extends CameraAlgoItem {
  detectionJSON: DetectionJSON;
  enableCardBool: boolean;
  electronicFenceBool: boolean;
  timeRangeArr: TimeRangeItem[];
}

const defaultSelectedAlgoDetail = { detectionJSON: { detectionNum: 0, detectionUnit: 1 } };

const useCameraAlgoStore = defineStore('cameraAlgo', () => {
  const {
    data: cameraAlgoList,
    runAsync: getCameraAlgoList,
    mutate: mutateCameraAlgoList,
  } = useRequest(
    (cameraId: number) => {
      return getCameraAlgoListApi(cameraId);
    },
    { manual: true },
  );

  const {
    data: allAlgoList,
    runAsync: getAllAlgoList,
    mutate: mutateAllAlgoList,
  } = useRequest(getAllAlgosApi, {
    manual: true,
  });

  /** 所有算法列表中选定的算法id */
  const selectedAlgoId = ref<number | null | undefined>();

  const selectedAlgoDetail = ref<CameraAlgoItemInCard>({
    ...defaultSelectedAlgoDetail,
  } as CameraAlgoItemInCard);

  const getAlgoDetail = (algoId: number): null | CameraAlgoItem => {
    const detail = cameraAlgoList.value?.find((x) => x.algoId === algoId);
    if (!detail) return null;
    return detail;
  };

  /** 算法是否已经绑定到相机 */
  const isAlgoBind = (algoId: number) => {
    return cameraAlgoList.value?.find((x) => x.algoId === algoId);
  };

  const clear = () => {
    mutateCameraAlgoList();
    mutateAllAlgoList();
    selectedAlgoDetail.value = { ...defaultSelectedAlgoDetail } as CameraAlgoItemInCard;
  };

  return {
    cameraAlgoList,
    getCameraAlgoList,
    selectedAlgoId,
    allAlgoList,
    getAllAlgoList,
    getAlgoDetail,
    selectedAlgoDetail,
    isAlgoBind,
    clear,
  };
});

export default useCameraAlgoStore;
