<template>
  <Teleport to="body">
    <div v-if="visible" class="top-loading-bar">
      <div class="loading-progress" :style="{ width: progress + '%' }"></div>
    </div>
  </Teleport>
</template>

<script setup lang="ts">
import { ref } from 'vue'

const visible = ref(false)
const progress = ref(0)
let timer: ReturnType<typeof setInterval> | null = null

const start = () => {
  visible.value = true
  progress.value = 0
  // 模拟进度条动画，最多到 90%
  timer = setInterval(() => {
    if (progress.value < 90) {
      progress.value += Math.random() * 15 + 5
    }
  }, 150)
}

const complete = () => {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
  progress.value = 100
  setTimeout(() => {
    visible.value = false
    progress.value = 0
  }, 200)
}

// 暴露方法给外部调用
defineExpose({
  start,
  complete,
})
</script>

<style scoped lang="scss">
.top-loading-bar {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 3px;
  z-index: 9999;
  background: transparent;
}

.loading-progress {
  height: 100%;
  background: #409eff; // Element Plus 主色调
  transition: width 0.15s linear;
}
</style>