<template>
    <div>
    </div>
</template>
<script setup lang="ts">
import { onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const route = useRoute();
const router = useRouter();

const loginType = ['csdn', 'gitee', 'github'];
const login = () => {
  // 携带redirect参数，已登录跳转该项目，未登录唤起第三方授权
  if (route?.query?.redirect !== undefined) {
    let redirectUrl = '';
    if (route?.query?.redirect) {
      redirectUrl = route?.query?.redirect.charAt(0) === '/' ? `${decodeURIComponent(route?.query?.redirect)}` : `/${decodeURIComponent(route?.query?.redirect)}`;
    }

    if (localStorage.getItem('access_token')) {
      router.replace(redirectUrl || '/');
      return;
    } else {
      const type = loginType.includes(route?.query?.type) ? route?.query?.type : 'csdn';
      const returnUrl = `${(import.meta as any).env.VITE_HOST}${redirectUrl}`;
      // 保存登录前页面地址
      localStorage.setItem('loginReturnUrl', returnUrl || '');
      const url = `${(import.meta as any).env.VITE_API_HOST}${(import.meta as any).env.VITE_PASSPORT_PREFIX || ''}/api/v1/oauth/login/${type}`;
      window.location.href = url;
      return;
    }
  } else {
    router.push('/');
  }
};

onMounted(() => {
  login();
});
</script>
