<script setup>
import { RouterLink, RouterView } from 'vue-router'
const { isWeChat } = useEnv()

onMounted(() => {
  RefreshToken()
})
const RefreshToken = async () => {
  const token = localStorage.getItem("token")
  const refreshAfter = localStorage.getItem("refreshAfter")
  const accessExpire = localStorage.getItem("accessExpire")
  const currentTime = new Date().getTime();

  if (accessExpire) {
    const accessExpireInMilliseconds = parseInt(accessExpire) * 1000;  // 转换为毫秒级
    if (currentTime > accessExpireInMilliseconds) {
      // if (isWeChat.value) {
      //   h5WeixinLogin()
      // }
      return
    }
  }
  // 1. 如果没有 token，直接返回
  if (!token) {
    // if (isWeChat.value) {
    //   h5WeixinLogin()
    // }
    return;
  }

  // 2. 如果有 refreshAfter，检查当前时间是否超过 refreshAfter（refreshAfter 是秒级，需要转换为毫秒级）
  if (refreshAfter) {
    const refreshAfterInMilliseconds = parseInt(refreshAfter) * 1000;  // 转换为毫秒级
    if (currentTime < refreshAfterInMilliseconds) {
      return;
    }
  }
  // 3. 如果没有 refreshAfter 或者时间超过 refreshAfter，执行刷新 token 的请求
  refreshToken()

}


const mpWeixinLogin = () => {

}

const refreshToken = async () => {
  const { data, error } = await useApiFetch("/user/getToken")
    .post()
    .json();

  if (data.value && !error.value) {
    if (data.value.code === 200) {
      localStorage.setItem("token", data.value.data.accessToken);
      localStorage.setItem("refreshAfter", data.value.data.refreshAfter);
      localStorage.setItem("accessExpire", data.value.data.accessExpire);
    }
  }
}

const h5WeixinLogin = async () => {
  // 获取当前URL
  const url = new URL(window.location.href);
  // 获取参数
  const params = new URLSearchParams(url.search);
  // 获取特定参数值
  const code = params.get('code');
  const state = params.get('state')
  if (code && state) {
    const { data, error } = await useApiFetch("/user/wxh5Auth")
      .post({ code })
      .json();

    if (data.value && !error.value) {
      if (data.value.code === 200) {
        localStorage.setItem("token", data.value.data.accessToken);
        localStorage.setItem("refreshAfter", data.value.data.refreshAfter);
        localStorage.setItem("accessExpire", data.value.data.accessExpire);

        params.delete('code');
        params.delete('state');

        // 更新 URL（不刷新页面）
        const newUrl = `${url.origin}${url.pathname}?${params.toString()}`;
        window.history.replaceState({}, '', newUrl);
      }
    }
  } else {
    h5WeixinGetCode()
  }
}

const h5WeixinGetCode = () => {
  const currentUrl = window.location.origin;
  let redirectUri = encodeURIComponent(currentUrl);
  // let redirectUri = "https://www.quannengcha.com"
  let appId = 'wxa581992dc74d860e';
  let state = "snsapi_base"
  let scope = "snsapi_base";
  let authUrl =
    `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`;
  // 跳转到授权URL
  window.location.href = authUrl;
}
</script>

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

<style scoped></style>
