<template>
  <div class="auto-login-container">
    <el-card class="auto-login-card">
      <div v-if="error" class="error-state">
        <el-icon class="icon-error"><CircleCloseFilled /></el-icon>
        <h3>登录检测失败</h3>
        <p>{{ error }}</p>
        <el-button type="primary" @click="goToLogin" style="margin-top: 15px;">前往登录</el-button>
      </div>
      <div v-else class="loading-state">
        <el-icon class="is-loading"><Loading /></el-icon>
        <p>正在检查 SSO 登录状态...</p>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getLoginRequest } from '../api/oidc'
import { Loading, CircleCloseFilled } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const error = ref('')

onMounted(async () => {
  const challenge = route.query.login_challenge as string
  if (!challenge) {
    error.value = "缺少 login_challenge 参数"
    return
  }

  try {
    const res = await getLoginRequest(challenge)
    // 如果后台判断会话有效（skip=true），会直接返回 redirect_to
    if (res.data?.redirect_to) {
      window.location.href = res.data.redirect_to
    } else {
      // 否则说明没有平台登录态，重定向到真实的登录页面，并携带 challenge
      router.replace({ path: '/login', query: { login_challenge: challenge } })
    }
  } catch (e: any) {
    console.error(e)
    error.value = e.response?.data?.detail || "获取 OIDC 请求失败"
  }
})

const goToLogin = () => {
  const challenge = route.query.login_challenge as string
  if (challenge) {
    router.replace({ path: '/login', query: { login_challenge: challenge } })
  } else {
    router.replace('/login')
  }
}
</script>

<style scoped>
.auto-login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f0f2f5;
}
.auto-login-card {
  width: 400px;
  text-align: center;
  padding: 30px 20px;
}
.icon-error {
  font-size: 48px;
  color: #f56c6c;
}
.is-loading {
  font-size: 32px;
  color: #409eff;
}
.loading-state p {
  margin-top: 15px;
  color: #606266;
}
</style>
