<script setup lang="ts">
import { onMounted } from 'vue';
import { RouterView, useRouter } from 'vue-router';
import { VxeUI } from 'vxe-table';
import { useDark } from '@vueuse/core';
import i18n from '@/utils/i18n';
import emitter from '@/utils/eventBus';
import { setThemeColor } from '@/utils/theme';

const isDark = useDark();
const router = useRouter();
const w: any = window;
const $wujie: any = w.$wujie;

localStorage.setItem('TOKEN', $wujie?.props?.TOKEN || '');
localStorage.setItem('USER_ID', $wujie?.props?.USER_ID || '');
localStorage.setItem('TENANT_ID', $wujie?.props?.TENANT_ID || '');
localStorage.setItem('USER_INFO_DATA', $wujie?.props?.USER_INFO_DATA || '{}');

if ($wujie) {
  // 路径跳转
  $wujie.bus.$on('ROUTER_CHANGE', (data: any) => {
    router.replace({
      path: data.path.split('/spdm')[1],
      query: data.query,
    });
  });
  // 语言变化
  $wujie.bus.$on('LANGUAGE_CHANGE', (lang: string) => {
    langToggleFun(lang === 'zh-cn' ? 'ZH' : 'EN');
  });
  // 黑色主题变化
  $wujie.bus.$on('DARK_THEME_CHANGE', (darkMode: boolean) => {
    darkToggleFun(darkMode);
  });
  // primary颜色变化
  $wujie.bus.$on('PRIMARY_COLOR_CHANGE', (color: string) => {
    setThemeColor('--el-color-primary', color);
  });
}

onMounted(() => {
  if ($wujie) {
    $wujie.bus.$emit('SPMD_LOADED');
  }
});

const langToggleFun = (lang: string) => {
  if (lang === 'ZH') {
    i18n.global.locale = 'ZH';
  } else {
    i18n.global.locale = 'EN';
  }
  localStorage.setItem('LANG_LOCALE', i18n.global.locale);
};

const darkToggleFun = (darkMode: boolean) => {
  isDark.value = darkMode;
  VxeUI.setTheme(isDark.value ? 'dark' : 'light');
  emitter.emit('THEME_CHANGE', isDark.value);
};
</script>

<template>
  <RouterView />
</template>
