import { defineStore } from 'pinia';
import { KankanMetaDataType } from '/#/sdk';
import { getApp } from '/@/hooks/userApp';
import { useMiniApp } from '/@/hooks/useMiniApp';
// useApp,
export interface FloorsType {
  id: string;
  subgroup?: string;
  name: string;
  segment?: any[];
  tagging?: any[];
  ['vertex-xy']?: any[];
}
interface sourceType {
  src: string;
}
interface vector3Type {
  x: number;
  y: number;
  z: number;
}
export interface tagType {
  sid: string;
  x: number;
  y: number;
  type: string;
  visible: boolean;
  content: string;
  createTime: number;
  floorIndex: number;
  icon: string;
  media: {
    image?: sourceType[];
  };
  panoId: number;
  position: vector3Type;
  visiblePanos: any[];
}
interface SceneState {
  tags: tagType[];
  floors: FloorsType[];
  metadata: KankanMetaDataType;
  currentTag: null | tagType;
}

export const getStaticURL = (path: string) => {
  return import.meta.env.BASE_URL + import.meta.env.VITE_APP_STATIC_DIR + '/' + path;
};

export const useSceneStore = defineStore({
  id: 'scene',
  state: (): SceneState => ({
    tags: [],
    currentTag: {} as tagType,
    floors: [],
    metadata: {} as KankanMetaDataType,
  }),
  getters: {
    musicURL(): Nullable<string> {
      const musicURl = this.metadata.music;
      if (musicURl) {
        if (/^0\d$/.test(musicURl)) {
          return getStaticURL(`static/music/${musicURl}.mp3`);
        } else {
          const app = getApp();
          return app.resource.getUserResourceURL(
            this.metadata.musicFile.replace(/(.+)\.(.+)/, 'music-user.$2'),
          );
        }
      }
      return null;
    },
    loadingLogoFile(): Nullable<string> {
      if (this.metadata.loadingLogo == 'user') {
        const app = getApp();
        return app.resource.getUserResourceURL(this.metadata.loadingLogoFile);
      }
      return null;
    },
  },
  actions: {
    load(metadata: KankanMetaDataType): void {
      this.metadata = metadata;
      document.title = metadata.title;
    },
    loadFloorData(floors: FloorsType[]) {
      if (floors?.length) {
        this.floors = floors.map((item) => {
          return { id: item.subgroup, name: item.name };
        }) as FloorsType[];
      }
    },
    loadTags(tags: tagType[]): void {
      if (tags?.length) {
        const { isUsingMiniApp } = useMiniApp();
        if (isUsingMiniApp.value) {
          this.tags = tags.filter((item) => item.type !== 'link');
        } else {
          this.tags = tags;
        }
      }
    },
    setCurrentTag(tag: null | tagType): void {
      this.currentTag = tag;
    },
  },
});
