// 直接把变量写在js文件里面 可以在组件中 或者 其他js文件使用
/** 是否显示顶栏 */
export const pageProgressVisible = ref(false)
/** 0 ~ 100 */
export const pageProgressPercent = ref(0)

let fakeTimer: ReturnType<typeof setInterval> | undefined
let hideTimer: ReturnType<typeof setTimeout> | undefined

function clearTimers() {
  if (fakeTimer != null) {
    clearInterval(fakeTimer)
    fakeTimer = undefined
  }
  if (hideTimer != null) {
    clearTimeout(hideTimer)
    hideTimer = undefined
  }
}

/** 路由开始时调用：显示并开始「假进度」到 ~88% */
export async function startPageProgress() {
  clearTimers()
  pageProgressVisible.value = true
  pageProgressPercent.value = 0

  await nextTick()
  pageProgressPercent.value = 12

  fakeTimer = setInterval(() => {
    if (pageProgressPercent.value < 88) {
      pageProgressPercent.value += Math.random() * 12 + 3
      if (pageProgressPercent.value > 88) pageProgressPercent.value = 88
    }
  }, 300)
}

/** 路由结束后调用：拉满并淡出 */
export function finishPageProgress() {
  clearTimers()
  if (!pageProgressVisible.value) return
  pageProgressPercent.value = 100

  hideTimer = setTimeout(() => {
    pageProgressVisible.value = false
    pageProgressPercent.value = 0
  }, 450)
}
