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

onMounted(async () => {
    // 获取query参数
    const queryParams = route.query;
    console.log('Received query parameters:', queryParams);
    let code = queryParams.code;
    if (code) {
        let req = {
            code: code,
        };
        await getTokenByCode(req).then((res: any) => {
            if (res.code === 0) {
                console.log('获取Token成功:', res);
                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);
                getMyUserInfo(userTokenInfo.user_id);
            } else {
                console.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);
    if (result["code"] === 0) {
        localStorage.setItem("ms_username", result["data"]["Name"]);
        const keys =
            permiss.defaultList[result["data"]["Role"] == "admin" ? "admin" : "user"];
            localStorage.setItem("ms_imgurl", result["data"]["Avatar"]);
        permiss.handleSet(keys);
        localStorage.setItem("ms_keys", JSON.stringify(keys));
        localStorage.setItem("ms_role", result["data"]["Role"]);
        router.push("/");
    }
  } catch (e) {
    console.log(e);
  }
};
</script>