import {
  GetFenceParams,
  getFenceApi,
  saveFenceApi,
  SaveFenceParams,
  editFenceApi,
} from '@/api/camera/camera-preview';
import { defineStore } from 'pinia';
import { ref } from 'vue';
import { ServerLines } from '../components/FenceEditor/constants';
import { ElMessage } from 'element-plus';

/** 当前电子围栏的store */
export const useFenceStore = defineStore('electronicFencePolygonStore', () => {
  /** 后端返回的电子围栏点 */
  const serverFencePoints = ref<ServerLines>([]);
  /** 当前编辑的电子围栏的点 */
  const currentFencePoints = ref([]);
  const currentFenceId = ref<number>();
  const loading = ref(false);

  /** 获取电子围栏 */
  const getFence = (param: GetFenceParams) => {
    loading.value = true;
    if (!param.algoId || !param.cameraId || !param.presetToken) return;
    return getFenceApi(param)
      .then((res) => {
        currentFenceId.value = res.id;
        const points = res.electronicFencePolygon
          ? (JSON.parse(res.electronicFencePolygon) as [])
          : [];
        currentFencePoints.value = points;
        serverFencePoints.value = points;
      })
      .catch(() => {
        currentFenceId.value = undefined;
        currentFencePoints.value = [];
        serverFencePoints.value = [];
      })
      .finally(() => {
        loading.value = false;
      });
  };

  const saveFence = (param: SaveFenceParams) => {
    if (!param.cameraId) {
      ElMessage.error('未选中相机');
      return;
    }
    if (!param.algoId) {
      ElMessage.error('未选中算法');
      return;
    }
    if (!param.presetToken) {
      ElMessage.error('未选中预置位');
      return;
    }
    if (currentFenceId.value) {
      return editFenceApi({ ...param, id: currentFenceId.value });
    }
    return saveFenceApi(param).then((res) => {
      console.log('save success', res);
      currentFenceId.value = res;
    });
  };

  const clear = () => {
    serverFencePoints.value = [];
    currentFencePoints.value = [];
    currentFenceId.value = undefined;
  };

  return { serverFencePoints, currentFencePoints, currentFenceId, getFence, saveFence, clear };
});

export default useFenceStore;
