<script setup>
import { onLaunch } from '@dcloudio/uni-app'
import { refreshToken, getUserInfo } from '@/api/apis'
import { getAgentInfo } from '@/apis/agent'

onLaunch(() => {
  refreshTokenIfNeeded()
  getUser()
  getAgentInformation()
})


const refreshTokenIfNeeded = async () => {
  const token = uni.getStorageSync("token")
  const refreshAfter = uni.getStorageSync("refreshAfter")
  const accessExpire = uni.getStorageSync("accessExpire")
  const currentTime = new Date().getTime()

  // 如果 token 已过期，直接返回
  if (accessExpire) {
    const accessExpireInMilliseconds = parseInt(accessExpire) * 1000  // 转换为毫秒级
    if (currentTime > accessExpireInMilliseconds) {
      return
    }
  }

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

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

  // 如果没有 refreshAfter 或者时间超过 refreshAfter，执行刷新 token 的请求
  try {
    const res = await refreshToken()
    if (res.code === 200) {
      uni.setStorageSync("token", res.data.accessToken)
      uni.setStorageSync("refreshAfter", res.data.refreshAfter)
      uni.setStorageSync("accessExpire", res.data.accessExpire)
    }
  } catch (error) {
    console.error('刷新token失败', error)
  }
}
const getAgentInformation = async () => {
  const token = uni.getStorageSync("token")
  if (!token) {
    return
  }

  try {
    const res = await getAgentInfo()
    if (res.code === 200 && res.data) {
      // 将代理信息存入缓存
      uni.setStorageSync("agentInfo", {
        level: res.data.level,
        isAgent: res.data.is_agent, // 判断是否是代理
        status: res.data.status, // 获取代理状态 0=待审核，1=审核通过，2=审核未通过，3=未申请
        agentID: res.data.agent_id,
        mobile: res.data.mobile
      })

      console.log('代理信息已获取并存入缓存')
    }
  } catch (error) {
    console.error('获取代理信息失败', error)
  }
}

const getUser = async () => {
  const token = uni.getStorageSync("token")
  if (!token) {
    return
  }
  const res = await getUserInfo()
  if (res.code === 200) {
    console.log(res.data)
    uni.setStorageSync("userInfo", res.data.userInfo)
  }
}
</script>
