<template>
  <div class="cas-callback">
    <div class="loading-container">
      <el-loading v-loading="loading" text="正在验证登录信息...">
        <div class="loading-content">
          <el-icon class="loading-icon">
            <Loading />
          </el-icon>
          <p>正在处理CAS登录...</p>
        </div>
      </el-loading>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElLoading } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import useUserStore from '@/store/modules/user'
import settings from '@/settings'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const loading = ref(true)

onMounted(() => {
  handleCasCallback()
})

async function handleCasCallback() {
  try {
    const ticket = route.query.ticket

    if (!ticket) {
      // 没有ticket参数,说明是直接访问此页面,根据设备类型进行跳转
      const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
      if (isMobile) {
        // 移动端跳转到移动端页面
        window.location.href = `${window.location.origin}/app-cas/`;
      } else {
        // PC端跳转到PC端页面
        router.push('/');
      }
      return;
    }

    // 有ticket参数,处理CAS登录回调
    // 构建服务URL(与登录页保持一致,包含构建时的 base 前缀)
    const base = import.meta.env?.BASE_URL || '/'
    const serviceUrl = window.location.origin + base + 'cas-callback'

    // 交由后端进行CAS票据验证与登录(更安全、与后端接口一致)
    await userStore.casLogin({ ticket, service: serviceUrl })

    // 获取用户信息
    await userStore.getInfo()

    ElMessage.success('CAS登录成功')

    // 登录成功后,根据设备类型跳转到相应页面
    const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
    if (isMobile) {
      // 移动端跳转到移动端页面
      window.location.href = `${window.location.origin}/app-cas/`;
    } else {
      // PC端跳转到PC端页面
      const redirect = route.query.state || '/';
      router.push(redirect);
    }
  } catch (error) {
    console.error('CAS登录失败:', error)
    ElMessage.error('CAS登录失败: ' + error.message)
    // 跳转回登录页面
    router.push('/login')
  } finally {
    loading.value = false
  }
}
</script>

<style lang="scss" scoped>
.cas-callback {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.loading-container {
  background: white;
  padding: 40px;
  border-radius: 10px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  text-align: center;
  min-width: 300px;
}

.loading-content {
  .loading-icon {
    font-size: 40px;
    color: #409eff;
    margin-bottom: 20px;
  }

  p {
    margin: 0;
    color: #666;
    font-size: 16px;
  }
}
</style>
