<template>
  <div class="auto-logout-container">
    <el-card class="auto-logout-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>正在安全退出...</p>
      </div>
    </el-card>
  </div>
</template>

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

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

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

  try {
    const res = await acceptLogout(challenge)
    
    // 清除本地登录状态
    localStorage.removeItem('token')
    authStore.token = ''
    authStore.user = null
    
    if (res.data?.redirect_to) {
      window.location.href = res.data.redirect_to
    } else {
      router.replace('/login')
    }
  } catch (e: any) {
    console.error(e)
    error.value = e.response?.data?.detail || "处理登出请求失败"
  }
})

const goToLogin = () => {
  router.replace('/login')
}
</script>

<style scoped>
.auto-logout-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f0f2f5;
}
.auto-logout-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>
