<script setup>
import { getToken } from '@/api/apis.js'

onLaunch(() => {
  initGetPlatform()
  RefreshToken()
})
function initGetPlatform() {
  uni.getSystemInfo().then((res) => {
    console.log('res', res)
    const platform = res.uniPlatform
    uni.setStorageSync('platform', platform)
  })
}
function RefreshToken() {
  const token = uni.getStorageSync('token')
  const refreshAfter = uni.getStorageSync('refreshAfter')
  const accessExpire = uni.getStorageSync('accessExpire')
  const currentTime = new Date().getTime()

  if (accessExpire) {
    const accessExpireInMilliseconds = Number.parseInt(accessExpire) * 1000 // 转换为毫秒级
    if (currentTime > accessExpireInMilliseconds) {
      uni.removeStorageSync('token')
      uni.removeStorageSync('refreshAfter')
      uni.removeStorageSync('accessExpire')
      return
    }
  }
  // 1. 如果没有 token，直接返回
  if (!token) {
    return
  }

  // 2. 如果有 refreshAfter，检查当前时间是否超过 refreshAfter（refreshAfter 是秒级，需要转换为毫秒级）
  if (refreshAfter) {
    const refreshAfterInMilliseconds = Number.parseInt(refreshAfter) * 1000 // 转换为毫秒级
    if (currentTime < refreshAfterInMilliseconds) {
      return
    }
  }
  // 3. 如果没有 refreshAfter 或者时间超过 refreshAfter，执行刷新 token 的请求
  refreshToken()
}
async function refreshToken() {
  getToken().then((res) => {
    if (res.code === 200) {
      uni.setStorageSync('token', res.data.accessToken)
      uni.setStorageSync('refreshAfter', res.data.refreshAfter)
      uni.setStorageSync('accessExpire', res.data.accessExpire)
    }
  })
}
</script>
