<template>
  <div class="callback-container">
    <div v-if="loading" class="loading">
      <i class="el-icon-loading"></i>
      <span>正在处理 TRS IDS 登录...</span>
    </div>
    <div v-else-if="error" class="error">
      <el-alert :title="error" type="error" show-icon />
      <el-button type="primary" @click="handleRetry">重试</el-button>
      <el-button @click="handleBackToLogin">返回登录页</el-button>
    </div>
  </div>
</template>

<script>
import { idsAuthRedirect } from "@/api/login";
import { setToken } from "@/utils/auth";

export default {
  name: "TRSidsCallback",
  data() {
    return {
      loading: true,
      error: "",
      redirect: ""
    };
  },
  created() {
    this.redirect = this.$route.query.redirect || "/";
    this.handleCallback();
  },
  methods: {
    async handleCallback() {
      try {
        const code = this.$route.query.code;
        if (!code) throw new Error("授权码缺失");

        // 1. 调用TRS认证接口
        const response = await idsAuthRedirect(code);
        if (!response?.data?.accessToken) {
          throw new Error(response?.msg || "认证失败");
        }

        // 2. 手动存储Token（因为现有Login action需要用户名密码）
        setToken({
          accessToken: response.data.accessToken,
          refreshToken: response.data.refreshToken,
          expiresTime: response.data.expiresTime
        });

        // 3. 获取用户信息
        await this.$store.dispatch("user/GetInfo");

        // 4. 跳转页面
        this.$router.push(this.redirect).catch(() => {
          this.$router.push("/");
        });

      } catch (err) {
        this.handleError(err);
      }
    },

    handleError(err) {
      console.error("TRS IDS 认证错误:", err);
      this.error = err.message || "TRS IDS 登录失败，请重试";
      this.loading = false;
    },

    handleRetry() {
      this.loading = true;
      this.error = "";
      this.handleCallback();
    },

    handleBackToLogin() {
      this.$router.push("/login");
    }
  }
};
</script>

<style scoped>
.callback-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  flex-direction: column;
  gap: 20px;
}

.loading {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 18px;
  color: #409EFF;
}

.error {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
  max-width: 500px;
}
</style>
