<template>
    <div>
        <p>回调页面，加载授权信息中...</p>
    </div>
</template>
<script lang="ts" setup>
//获取query参数
import { useRouter, useRoute } from 'vue-router';
import { onMounted } from 'vue';
import { getTokenByCode } from '@/api/user.js';
import { GetUserInfoService } from "@/api/user.js";
import { ElMessage } from 'element-plus';
const route = useRoute();

const router = useRouter();

interface UserToken {
    access_token: string; // 访问令牌
    refresh_token: string; // 刷新令牌
    user_id: number; // 用户ID
    username: string; // 用户名
    email: string; // 用户邮箱
}

onMounted(async () => {
    // 获取query参数
    const queryParams = route.query;
    console.log('Received query parameters:', queryParams);
    let code = queryParams.code;
    //alert('Received code: ' + code);
    if (code) {
        let req = {
            code: code,
        };
        await getTokenByCode(req).then(async (res: any) => {
            if (res.code === 0) {
                ElMessage.success('获取Token成功');
                let userTokenInfo: UserToken = res.data;
                localStorage.setItem("token", userTokenInfo.access_token);
                localStorage.setItem("refresh_token", userTokenInfo.refresh_token);
                localStorage.setItem("userId", userTokenInfo.user_id.toString());
                localStorage.setItem("username", userTokenInfo.username);
                await getMyUserInfo(userTokenInfo.user_id);
            } else {
                console.error('获取Token失败:', res.message);
                ElMessage.error('获取Token失败: ' + res.message);
            }
        }).catch((error: any) => {
            console.error('请求错误:', error);
        });
    } 
    
});

const getMyUserInfo = async (id) => {
  let result = {};
  try {
    let tokenData = {
      token: localStorage.getItem("token"),
      id: id,
    };
    result = await GetUserInfoService(tokenData);
    //alert("get_user_info:" + JSON.stringify(result));
    if (result['code'] === 0) {
      //console.log("token data:",this.tokenData)
        localStorage.setItem("video_func", result['data']['VideoFunc']);
        localStorage.setItem("device_func", result['data']['DeviceFunc']);
        localStorage.setItem("cid_func", result['data']['CIDFunc']);
        localStorage.setItem("role", result['data']['Role']);
        router.push("/user");
    }
  } catch (e) {
    console.log(e);
  }
};
</script>