<script setup lang="tsx">
import { ref, watch } from 'vue';
import { loginSso, getMenuKeysByRole, getMenuTreeByRole } from '@/api/login';
import { useStorage } from '@/hooks/web/useStorage';
import { useAppStore } from '@/store/modules/app';
import { usePermissionStore } from '@/store/modules/permission';
import { useRouter } from 'vue-router';
import type { RouteLocationNormalizedLoaded, RouteRecordRaw } from 'vue-router';
import Cookies from 'js-cookie';
import { ACCESS_TOKEN } from '@/config/axios/config';
import { getQueryVariable } from '@/utils';
import { ElLoading } from 'element-plus'
import { useTagsViewStore } from '@/store/modules/tagsView'
import { resetRouter } from '@/router'

const { clear } = useStorage()

const tagsViewStore = useTagsViewStore()

const appStore = useAppStore();

const permissionStore = usePermissionStore();

const { currentRoute, addRoute, push, replace } = useRouter();

const { setStorage } = useStorage();

const loading = ref(false);

const redirect = ref<string>('');

watch(
  () => currentRoute.value,
  (route: RouteLocationNormalizedLoaded) => {
    redirect.value = route?.query?.redirect as string;
  },
  {
    immediate: true,
  },
);

// 登录
const signIn = async () => {
  loading.value = true;

  try {
    const ssoToken = getQueryVariable('ssoToken');
    let queryToken = ssoToken;
    if(ssoToken){
      queryToken = ssoToken.includes('#/') ? ssoToken.split('#/')[0] : ssoToken;
    }
    if (queryToken) {
      const Loading = ElLoading.service();
      const res = await loginSso(queryToken);
      Loading.close()
      if (res && res?.head?.code === '0') {
        // Cookie set
        Cookies.set(ACCESS_TOKEN, res?.body?.access_token);

        const data = res?.body?.permissions ? res?.body : { ...res?.body, permissions: ['*.*.*'] };
        setStorage(appStore.getUserInfo, data);

        // 是否使用动态路由
        if (appStore.getDynamicRouter) {
          getMenuByRole(data.session_userId);
        } else {
          await permissionStore.generateRoutes('static').catch(() => {});
          permissionStore.getAddRouters.forEach(route => {
            addRoute(route as RouteRecordRaw); // 动态添加可访问路由表
          });
          permissionStore.setIsAddRouters(true);
          push({ path: redirect.value || permissionStore.addRouters[0].path });
        }
        return;
      }
    } else {
      // 重定向到登录页面
      replace('/login');
    }

  } finally {
    loading.value = false;
  }
};

// 清除用户信息，否则不会重新请求接口
const clearInfo = () => {
  Cookies.remove(ACCESS_TOKEN);
  clear();
  tagsViewStore.delAllViews()
  resetRouter() // 重置静态路由表
  signIn();
}
clearInfo();

// 获取角色信息的路由
const getMenuByRole = async (userId: string = '') => {
  const params = {
    userId: userId,
  };
  const res = appStore.getDynamicRouter && appStore.getServerDynamicRouter ? await getMenuTreeByRole(params) : await getMenuKeysByRole(params);
  if (res) {
    const routers = res.body.menutree || [];
    setStorage('roleRouters', routers);
    appStore.getDynamicRouter && appStore.getServerDynamicRouter
      ? await permissionStore.generateRoutes('server', routers).catch(() => {})
      : await permissionStore.generateRoutes('frontEnd', routers).catch(() => {});

    permissionStore.getAddRouters.forEach(route => {
      addRoute(route as RouteRecordRaw); // 动态添加可访问路由表
    });
    permissionStore.setIsAddRouters(true);
    push({ path: redirect.value || permissionStore.addRouters[0].path });
  }
};

</script>

<template>
  <div></div>
</template>
