<template>
  <component :is="component" />
</template>

<script setup lang="ts">
  import { ref, onBeforeUnmount, onBeforeMount, watch, nextTick } from 'vue';
  import { useRoute } from 'vue-router';
  import { getActions } from '/@/qiankun/state';
  import { activeApps } from '/@/qiankun/index';

  const route = useRoute();

  const component = ref<any>(null);

  async function resetComponent() {
    component.value = null;

    return nextTick(() => {
      return setTimeout(async () => {
        const appType = route.path.split('/')[1];
        if (appType === 'micro-need-air') {
          component.value = (await import('./needAir.vue')).default;
        } else if (appType === 'micro-vent-doc') {
          component.value = (await import('./ventDoc.vue')).default;
        } else if (appType === 'micro-vent-3dModal' || appType === 'micro-vent-2dModal') {
          if (route.query['isNoReverse'] != '1') {
            if (VENT_PARAM['is2DModel']) {
              component.value = (await import('./ventModal2D.vue')).default;
            } else {
              component.value = (await import('./ventModal.vue')).default;
            }
          } else if (appType === 'micro-vent-3dModal') {
            component.value = (await import('./ventModal.vue')).default;
          } else if (appType === 'micro-vent-2dModal') {
            component.value = (await import('./ventModal2D.vue')).default;
          }
        }
      }, 0);
    });
  }

  watch(
    () => [route.query, route.path],
    async ([newQuery, newPath], [oldQuery, oldPath]) => {
      // 这里判断
      if (newPath !== oldPath) {
        await resetComponent();
      } else if (newQuery !== oldQuery) {
        const actions = getActions();
        const appType = route.path.split('/')[1];
        activeApps[appType].mountPromise.then(() => {
          actions.setGlobalState({ currentRouter: route });
        });
      }
    }
  );

  onBeforeMount(async () => {
    await resetComponent();
  });
  onBeforeUnmount(() => {
    component.value = null;
  });
</script>
