import { ref } from 'vue'
import { defineStore } from 'pinia'
import { nanoid } from 'nanoid'
import type {
  FurnitureItem,
  LocalFurnitureItem,
  SubRegionItem,
  LocalSubRegionItem,
} from '@/api/room/types'
import { convert_region_c2r, type RadarPosition } from '@/utils/coordTransform'

export const useRoomStore = defineStore(
  'room',
  () => {
    /* ========== 接口元数据 ========== */
    const furnitureItems = ref<FurnitureItem[]>([]) // 家具列表
    const subRegionItems = ref<SubRegionItem[]>([]) // 子区域列表

    /* ========== 本地元数据 ========== */
    const localFurnitureItems = ref<LocalFurnitureItem[]>([]) // 家具列表
    const localSubRegions = ref<LocalSubRegionItem[]>([]) // 子区域列表

    /* ========== 缓存元数据 ========== */
    /**
     * 缓存接口中的家具列表
     * @param items - 家具列表
     */
    function cacheFurniture(items: FurnitureItem & LocalFurnitureItem[]) {
      // 过滤掉雷达家具
      const furniture = items.filter((item) => item.type !== 'radar')
      furnitureItems.value = furniture
      localFurnitureItems.value = furniture.map((item) => ({
        ...item,
        nanoid: nanoid(),
      }))
    }

    /**
     * 缓存接口中的子区域列表
     * @param items - 子区域列表
     */
    function cacheSubRegion(items: SubRegionItem & LocalSubRegionItem[]) {
      subRegionItems.value = items
      localSubRegions.value = items.map((item) => ({
        ...item,
        nanoid: nanoid(),
        isDraging: false,
        isResizing: false,
        isActice: false,
        isTracking: item.trackPresence === 1,
        isFalling: item.excludeFalling === 1,
        isBed: item.isLowSnr === 1,
      }))
    }

    /* ========== 坐标转换 ========== */

    // 家具列表坐标转换    雷达坐标系 --> 画布坐标系
    // 家具列表坐标转换    画布坐标系 --> 雷达坐标系

    // 子区域列表坐标转换    雷达坐标系 --> 画布坐标系
    // 子区域列表坐标转换    画布坐标系 --> 雷达坐标系
    function convertSubRegionC2R(item: LocalSubRegionItem, pRadar: RadarPosition) {
      const p_radar = {
        x_radar: pRadar.x_radar,
        y_radar: pRadar.y_radar,
      }
      const dst_rect = {
        left: item.pixelX,
        top: item.pixelY,
        width: item.pixelWidth,
        height: item.pixelHeight,
      }
      return convert_region_c2r(dst_rect, p_radar)
    }

    return {
      furnitureItems,
      subRegionItems,
      localFurnitureItems,
      localSubRegions,
      cacheFurniture,
      cacheSubRegion,
      convertSubRegionC2R,
    }
  },
  {
    persist: {
      key: `${import.meta.env.VITE_STORE_NAME}_ROOM_INFO`,
      storage: localStorage,
    },
  }
)
