<template>
  <div class="authorize-container">
    <el-alert
        v-if="errorMessage"
        :title="errorMessage"
        type="error"
        show-icon
        closable
        @close="errorMessage = ''"
    />
    <div v-else class="loading">
      <el-icon class="is-loading">
        <Loading />
      </el-icon>
      <span>正在授权验证中...</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { authorize } from '@/api/login'
import { Loading } from '@element-plus/icons-vue'
import type { AxiosResponse } from 'axios'

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

const handleAuthorize = async () => {
  try {
    // 提取查询参数部分（去掉路径）
    const queryParams = route.fullPath.replace(route.path+'?', '')

    const response: AxiosResponse = await authorize(queryParams)

    // 根据实际业务处理响应
    if (response.data &&  response.data.redirect_url) {
      // 授权成功，跳转到首页或其他目标页面
      const redirectUrl = response.data.redirect_url
      location.href = redirectUrl
    } else {
      errorMessage.value = response.data.message || '授权失败'
    }
  } catch (error: any) {
    console.error('授权异常:', error)
    errorMessage.value = error.message || '网络错误，请稍后重试'
    const redirectParam = encodeURIComponent(route.fullPath)
    router.push(`/login?redirect=${redirectParam}`)

    // 可选的：失败后重试逻辑
    // setTimeout(() => {
    //   errorMessage.value = ''
    //   handleAuthorize()
    // }, 3000)
  }
}

onMounted(() => {
  handleAuthorize()
})
</script>

<style scoped>
.authorize-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 300px;
  padding: 20px;
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  color: #666;
}

.loading .el-icon {
  font-size: 36px;
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>