import { computed, ref, toRefs } from 'vue';
import useSceneInfos from '@/hooks/useSceneInfos';
import { CameraItem, getWorkshopMiniMapLayoutApi } from '@/api/scene/scene';
import { defineStore } from 'pinia';
import safeParse from '@/utils/safeParse';
import { ElMessage } from 'element-plus';

type ShopMapCamera = CameraItem & {
  /** 相机是否已经设置 0-false 1-true */
  isSet: number;
  /** 工位名称 */
  workSpaceName: string;
  integrationState?: number;
};

export const useMiniMap = defineStore('mini-map', () => {
  const sceneInfos = useSceneInfos();
  const { scenesTree, flattenedWorkshops } = toRefs(sceneInfos);
  const { getScenesTree, getCameraList } = sceneInfos;

  const selectedShopCode = ref<string>();
  const selectedShopDetail = computed(() =>
    flattenedWorkshops.value.find((space) => space.code === selectedShopCode.value),
  );

  const getShopDetailByCode = (code: string) => {
    return flattenedWorkshops.value.find((space) => space.code === code);
  };
  const bgImgUrl = ref('');

  const shopCameraList = ref<ShopMapCamera[]>([]);

  const getShowCameras = (code: string) => {
    shopCameraList.value = [];
    const id = getShopDetailByCode(code)?.id;

    if (!id) {
      ElMessage.error('摄像头code未找到对应信息');
      return Promise.resolve();
    }
    return getCameraList(id).then((res) => {
      res.forEach((space) => {
        if (space.cameraList && space.cameraList.length > 0) {
          space.cameraList.forEach((camera) => {
            shopCameraList.value.push({ ...camera, isSet: 0, workSpaceName: space.name });
          });
        }
      });
    });
  };

  const getMapLayout = (code: string) => {
    const shopId = getShopDetailByCode(code)?.id || '';
    if (!shopId) {
      ElMessage.error('摄像头code未找到对应信息');
      return Promise.reject();
    }
    return getWorkshopMiniMapLayoutApi(String(shopId)).then((res) => {
      const layoutJSON = res?.layout ? safeParse(res.layout) : null;
      return layoutJSON;
    });
  };

  return {
    selectedShopDetail,
    bgImgUrl,
    scenesTree,
    shopCameraList,
    getScenesTree,
    getShowCameras,
    getMapLayout,
    selectedShopCode,
  };
});

export default useMiniMap;
