<template>
  <el-config-provider :locale="locale">
    <router-view />
  </el-config-provider>
</template>

<script setup>
import { useRouter } from 'vue-router';
import { computed, watch } from 'vue';
import { ElConfigProvider } from 'element-plus';
import { useI18n } from 'vue-i18n';
import { useSystemStore } from '@/store/index';
import { useTheme } from '@/hooks/useTheme';
import { setWorkspace } from '@/router/permissions';

const router = useRouter();

const { messages } = useI18n();

// elmentui组件国际化
const systemStore = useSystemStore();
const locale = computed(() => {
  return systemStore.language === 'zh'
    ? messages.value['zh']
    : messages.value['en'];
});

// 初始化主题
const { themeSet } = useTheme();
themeSet(systemStore.theme);

// 当前workspace
const workspace = computed(() => {
  return systemStore.workspace;
});
// 所有权限
const permissions = computed(() => {
  return systemStore.permissions;
});

watch(
  () => router.currentRoute.value,
  (value) => {
    const paramsWorkspace = value.params.workspace;
    // 页面初始化时 若路由配置了workspace参数但不存在时为''
    if (paramsWorkspace == '') {
      router.replace({
        name: value.name,
        params: {
          workspace: workspace.value.name,
        },
      });
    } else if (paramsWorkspace && paramsWorkspace != workspace.value.name) {
      let data = permissions.value.find(
        (item) => item.workspace.name == paramsWorkspace
      );
      if (data) {
        setWorkspace(data);
      } else {
        router.replace({
          name: value.name,
          params: {
            workspace: workspace.value.name,
          },
        });
      }
    }
  },
  { immediate: true }
);
</script>
