<script setup>
import { RouterLink, RouterView } from 'vue-router'
import WechatOverlay from './components/WechatOverlay.vue';
onMounted(() => {
  RefreshToken()
})
const RefreshToken = async () => {
  const token = localStorage.getItem("token")
  const refreshAfter = localStorage.getItem("refreshAfter")
  const currentTime = new Date().getTime();

  // 1. 如果没有 token，直接返回
  if (!token) {
    return;
  }

  // 2. 如果有 refreshAfter，检查当前时间是否超过 refreshAfter（refreshAfter 是秒级，需要转换为毫秒级）
  if (refreshAfter) {
    const refreshAfterInMilliseconds = parseInt(refreshAfter) * 1000;  // 转换为毫秒级
    if (currentTime < refreshAfterInMilliseconds) {
      return;
    }
  }

  // 3. 如果没有 refreshAfter 或者时间超过 refreshAfter，执行刷新 token 的请求
  const { data, error } = await useApiFetch("/user/getToken")
    .post()
    .json();

  if (data.value && !error.value) {
    if (data.value !== 200) {
      localStorage.setItem("token", data.value.data.accessToken);
      localStorage.setItem("refreshAfter", data.value.data.refreshAfter);
    }
  }
}
</script>

<template>
  <WechatOverlay />
  <RouterView />
</template>

<style scoped></style>
