<script setup lang="ts">
  import { onMounted, ref, computed, unref, watchEffect, onUnmounted } from 'vue';
  import { createApp } from '/@/hooks/userApp';
  // import tagView from '/@/components/custom/tagView.vue';
  // import tag from '/@/components/custom/tag.vue';
  import LoadingLogo from '/@/components/basic/loading.vue';
  import MiniMap from '/@/components/basic/miniMap.vue';
  import FloorplanView from '/@/components/basic/floorplan.vue';
  import { useSceneStore } from '/@/store/modules/scene';
  import type { FloorsType } from '/@/store/modules/scene';
  import { useAppStore } from './store/modules/app';
  import Guideline from '/@/components/basic/guide.vue';
  import ChatRoom from '/@/components/chatRoom/index.vue';
  import Title from '/@/components/basic/title.vue';
  import FloorSwitch from '/@/components/basic/FloorSwitch.vue';
  import GuidePanel from '/@/components/custom/panel.vue';
  import browser from '/@/utils/browser';
  // import { useRtcStore } from './store/modules/rtc';
  import { useTourPlayer } from './hooks/userTourPlayer';
  import { KankanMetaDataType } from '/#/sdk';
  // import Dialog from '/@/components/basic/dialog';
  import { useRtcStore } from './store/modules/rtc';
  import { useLocale } from '/@/locales/useLocale';
  import { LocaleType } from '/#/config';
  import { useI18n } from '/@/hooks/useI18n';
  import BaseDialog from '/@/components/chatRoom/dialog/base.vue';

  const { createTourPlayer } = useTourPlayer();
  const showDebug = ref(Number(import.meta.env.VITE_SHOW_DEBUGPANEL) === 1);
  const { t } = useI18n();

  const { changeLocale } = useLocale();
  // 设置语言
  const defaultLang = ['zh', 'en'];
  const lang = browser.getURLParam('lang');
  if (lang && defaultLang.includes(browser.getURLParam('lang'))) {
    changeLocale(lang as LocaleType);
  } else {
    changeLocale('zh');
  }
  // const maxNumber = import.meta.env.VITE_ROOM_MEMBER || 10;
  // const test_version = computed(() => import.meta.env.VITE_TEST_VERSION || '');
  const sceneStore = useSceneStore();
  const appStore = useAppStore();
  const rtcStore = useRtcStore();
  // const rtcStore = useRtcStore();
  const dataLoaded = ref(false);
  const scene$ = ref<Nullable<HTMLElement>>(null);
  const refMiniMap = ref<Nullable<string>>(null);
  const flying = computed(() => appStore.flying);
  const player = computed(() => appStore.player);
  const metadata = computed(() => sceneStore.metadata);
  const mode = computed(() => appStore.mode);
  // const isJoined = computed(() => rtcStore.isJoined);
  const isLoaded = computed(() => appStore.isLoaded);
  const controls = computed(() => {
    return metadata.value.controls;
  });
  const floorplanViewShow = computed(() => {
    return (
      Boolean(controls.value.showDollhouse) &&
      Boolean(controls.value.showFloorplan) &&
      mode.value !== 'panorama'
    );
  });
  const show = ref(false);
  const isTourMode = computed(() => appStore.isTourMode);

  watchEffect(() => {
    console.warn('mode', mode);
  });
  // 强制开https
  console.log('当前protocol', location.protocol);
  if (location.protocol !== 'https:') {
    location.protocol = 'https:';
    console.log('强制开https');
  }
  onMounted(async () => {
    const app = await createApp({
      dom: scene$.value as HTMLElement,
      num: browser.getURLParam('m'),
      mobile: true,
    });
    // SDK初始化

    app.use('MinMap', { theme: { camera_fillStyle: '#ED5D18' } }).then(() => {
      // refMiniMap.value = '[xui_min_map]';
      console.log('小地图SDK');
    });
    app.use('Tag');

    createTourPlayer();
    app
      .use('TagView', {
        render(data) {
          // console.log('tagView', data);
          if (data.media['image'] && data.media['image'].length) {
            // console.log('tagView-1', data);
            // return h(tagView, {
            //   sid: data.sid,
            //   url: app.resource.getUserResourceURL(data.media['image'][0].src),
            //   content: data.content,
            //   title: data.title,
            // });
          }
          // console.log('render', render);
          // return `<span class="tag-icon animate" style="background-image:url({{icon}})"></span>`;
          // return
          return `<span class="tag-icon animate" style="display:none"></span>`;
        },
      })
      .then(() => {
        // const openTags = (tag) => {
        // let item = tags.value.find((item) => item.sid == el.data.sid);
        // guideclicktag(item);
        // store.commit('tag/setTagClickType', {
        //   type: 'goodlist',
        //   data: item,
        // });
        // };
        // view.on('rendered', (_) => {
        //   view.on('click', async (e) => {
        // var tag = e.data;
        // 聚焦當前點擊的熱點
        // debugger;
        // await view.focus(tag.sid);
        // });
        // view.on('focus', (e) => {
        //   if (!e.data.media['image'] || !e.data.media['image'].length) {
        //     return;
        //   }
        //   document.querySelectorAll('[xui_tags_view] >div').forEach((el) => {
        //     el.querySelector('.tag-body').classList.remove('show');
        //     el.style.zIndex = 'auto';
        //   });
        //   e.target.style.zIndex = '999';
        //   e.target.querySelector('.tag-body').classList.add('show');
        // });
        // }); //dom渲染完成
      });

    // 暂时isTours url frag 做为 1自由观看模式与带看模式0

    if (Number(browser.getURLParam('isTour')) === 1) {
      appStore.setIsTourMode(true);
    } else {
      appStore.setIsTourMode(false);
    }
    // SDK global Event start
    app.Scene.on('ready', () => {
      show.value = true;
    });
    app.Scene.on('loaded', (pano) => {
      appStore.setFloorId(pano.floorIndex);
      refMiniMap.value = '[xui_min_map]';
      // store.commit("setFloorId", pano.floorIndex);
      // store.commit("rtc/setShowdaogou", true);

      // if (browser.getURLParam("roomId") && browser.getURLParam("vruserId") && browser.getURLParam("name")) {
      //   store.commit("showShoppingguide", true);
      // }
    });
    app.store.on('metadata', (metadata: KankanMetaDataType) => {
      sceneStore.load(metadata);
      if (!metadata.controls.showMap) {
        app.MinMap.hide(true);
      }
      dataLoaded.value = true;
      appStore.isLoad();
    });
    app.store.on('floorcad', ({ floors }: { floors: FloorsType[] }) => {
      if (floors?.length) {
        sceneStore.loadFloorData(floors);
      }
    });
    app.store.on('flooruser', ({ floors }: { floors: FloorsType[] }) => {
      if (floors?.length) {
        sceneStore.loadFloorData(floors);
      }
    });
    app.Camera.on('mode.beforeChange', ({ toMode, floorIndex, fromMode }) => {
      appStore.setMode(toMode);
      if (toMode != 'dollhouse') {
        appStore.setFloorId(floorIndex);
      }
      console.log('setFloorId-4', toMode, floorIndex);
      if (fromMode) {
        appStore.setFlying(true);
      }
    });
    app.Camera.on('mode.afterChange', () => {
      appStore.setFlying(false);
    });
    app.Camera.on('flying.started', () => {
      appStore.setFlying(true);
    });
    app.Camera.on('flying.ended', ({ targetPano }) => {
      appStore.setFlying(false);
      console.log('setFloorId-3', targetPano.floorIndex);
      if (unref(mode) !== 'dollhouse') {
        appStore.setFloorId(targetPano.floorIndex);
      }
    });
    app.Scene.on('error', (data) => {
      console.log('当前错误code', data.code);
      switch (data.code) {
        case 5033:
          // Dialog.alert('该场景正在计算中，请稍后再试');
          rtcStore.showBaseDialog(
            {
              title: t('base.tips'),
              desc: t('base.baseError1'),
              okTxt: t('base.confirm'),
              closeTxt: t('base.cancel'),
            },
            () => {},
          );
          break;
        case 5034:
          // Dialog.alert('服务端开小差，请稍后再试');
          rtcStore.showBaseDialog(
            {
              title: t('base.tips'),
              desc: t('base.baseError2'),
              okTxt: t('base.confirm'),
              closeTxt: t('base.cancel'),
              isSingle: true,
            },
            () => {},
          );
          break;
        case 5009:
          // Dialog.alert('服务端开小差，请稍后再试');
          rtcStore.showBaseDialog(
            {
              title: t('base.tips'),
              desc: t('base.baseError2'),
              okTxt: t('base.confirm'),
              closeTxt: t('base.cancel'),
              isSingle: true,
            },
            () => {},
          );
          break;
        case 5005:
          // Dialog.alert('服务端开小差，请稍后再试');
          rtcStore.showBaseDialog(
            {
              title: t('base.tips'),
              desc: t('base.baseError2'),
              okTxt: t('base.confirm'),
              closeTxt: t('base.cancel'),
              isSingle: true,
            },
            () => {},
          );
          break;
      }
    });
    app.render();
    // SDK初始化结束
  });
  // SDK global Event end
  onUnmounted(() => {
    appStore.unLoad();
  });

  // method
  const changeMode = (name: string) => {
    if (!unref(flying)) {
      appStore.setMode(name);
    } else {
      console.log('正在飞', unref(flying));
      // appStore.setMode(name);
    }
  };
</script>

<template>
  <div class="debug flex justify-between px-1" v-if="showDebug">
    <!-- <span>
      {{ t('base.debuginfo') }}：公告，当前测试最新: {{ test_version }}, 当前满员条件：
      {{ maxNumber }}
    </span> -->
    <span>
      {{ t('base.debuginfo') }}：公告，当前测试1.1.0正在开发测试中，如要1.0.0请联系开发！
    </span>
    <span class="close" @click.stop="showDebug = false">X</span>
  </div>
  <LoadingLogo :thumb="true" />
  <!-- 引导页 -->
  <Title v-if="isLoaded && !!unref(refMiniMap)" />
  <Guideline />
  <div class="ui-view-layout" :class="{ show: show }">
    <div class="scene" ref="scene$"></div>
    <template v-if="dataLoaded">
      <!-- 小地图 start -->
      <MiniMap
        :show="!!unref(refMiniMap) && player.showWidgets"
        :show-dollhouse="Boolean(controls.showDollhouse)"
        :to="refMiniMap"
        @change-mode="changeMode"
      />
      <!-- 小地图 end -->
      <!-- 平面图 start -->
      <FloorplanView :show="floorplanViewShow" :mode="mode" @change-mode="changeMode" />
      <!-- 平面图 end -->
      <!-- 聊天 start-->
      <ChatRoom v-if="!isTourMode" />
      <!-- 聊天 end -->
      <!-- 多楼层 start-->
      <FloorSwitch />
      <!-- 多楼层 end -->
      <!-- panel start-->
      <GuidePanel v-if="isTourMode" />
      <!-- panel end -->
    </template>
  </div>
  <BaseDialog />
</template>

<style lang="scss">
  @import './app.scss';
  .debug {
    color: white;
    background-color: rgba($color: #000000, $alpha: 0.3);
    position: fixed;
    top: 0;
    left: 0;
    z-index: 1000001;
    text-align: left;
    width: 100%;
    .close {
      // background-color: red;
      width: 30px;
      text-align: center;
      &:hover {
        cursor: pointer;
      }
    }
  }
  @media screen and (min-width: 768px) {
  }
</style>
