<template>
  <!-- 步骤进度加载遮罩组件 — 居中面板 + 半透明遮罩 -->
  <div class="step-progress-overlay">
    <!-- 半透明遮罩背景 -->
    <div class="step-progress-overlay__mask"></div>
    <!-- 内容面板 -->
    <div class="step-progress-overlay__panel">
      <!-- 顶部标题行 -->
      <div class="step-progress-overlay__header">
        <div class="step-progress-overlay__titles">
          <h2 class="step-progress-overlay__title">{{ title }}</h2>
          <p class="step-progress-overlay__subtitle">{{ subtitle }}</p>
        </div>
        <!-- 关闭按钮 -->
        <button class="step-progress-overlay__close" @click="handleClose" aria-label="关闭">
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M1 1L13 13M13 1L1 13" stroke="#6A7282" stroke-width="1.6" stroke-linecap="round"/>
          </svg>
        </button>
      </div>

      <!-- 进度面板 -->
      <div class="step-progress-overlay__progress-box">
        <!-- 进度条头部 -->
        <div class="step-progress-overlay__progress-header">
          <span class="step-progress-overlay__progress-label">处理进度</span>
          <span class="step-progress-overlay__progress-percent">{{ percent }}%</span>
        </div>
        <!-- 进度轨道 -->
        <div class="step-progress-overlay__progress-rail">
          <div class="step-progress-overlay__progress-fill" :style="{ width: percent + '%' }"></div>
        </div>

        <!-- 步骤列表 -->
        <div class="step-progress-overlay__steps">
          <div v-for="(item, idx) in stepList" :key="idx" class="step-progress-overlay__step-item">
            <!-- 左侧圆点 + 连接线 -->
            <div class="step-progress-overlay__step-left">
              <!-- 完成状态：对勾圆 -->
              <div v-if="item.status === 'done'" class="step-progress-overlay__dot step-progress-overlay__dot--done">
                <svg width="10" height="10" viewBox="0 0 10 10" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M2.5 5.2L4.2 6.8L7.5 3.5" stroke="#fff" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
              </div>
              <!-- 进行中：光晕 + 呼吸内圆 -->
              <div v-else-if="item.status === 'active'" class="step-progress-overlay__dot step-progress-overlay__dot--active">
                <div class="step-progress-overlay__dot-pulse"></div>
              </div>
              <!-- 等待状态：浅色圆 -->
              <div v-else class="step-progress-overlay__dot step-progress-overlay__dot--pending"></div>
              <!-- 连接线（最后一项不显示） -->
              <div v-if="idx < stepList.length - 1" class="step-progress-overlay__connector"></div>
            </div>
            <!-- 步骤名称 -->
            <span class="step-progress-overlay__step-text" :class="{ 'step-progress-overlay__step-text--pending': item.status === 'pending' }">{{ item.label }}</span>
            <!-- 步骤状态文字 -->
            <span class="step-progress-overlay__step-state" :class="{
              'step-progress-overlay__step-state--done': item.status === 'done',
              'step-progress-overlay__step-state--active': item.status === 'active',
              'step-progress-overlay__step-state--pending': item.status === 'pending'
            }">{{ item.stateText }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

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

// ==================== Props ====================

interface Props {
  /** 大标题 */
  title: string
  /** 副标题 */
  subtitle: string
  /** 4个步骤名称 */
  steps: string[]
  /** 4个步骤对应的模拟时长（毫秒） */
  durations: number[]
  /** 接口是否已完成，父组件设为 true 后走完剩余进度 */
  done: boolean
}

const props = withDefaults(defineProps<Props>(), {
  done: false,
})

// ==================== Emits ====================

const emit = defineEmits<{
  /** 进度走完100%后通知父组件 */
  (e: 'finished'): void
  /** 点击关闭按钮 */
  (e: 'close'): void
}>()

// ==================== 内部状态 ====================

/** 步骤项接口 */
interface StepItem {
  label: string
  status: 'pending' | 'active' | 'done'
  stateText: string
}

/** 当前进度百分比 */
const percent = ref(0)

/** 步骤列表 */
const stepList = ref<StepItem[]>(
  props.steps.map((label) => ({ label, status: 'pending' as const, stateText: '等待' }))
)

/** 进度动画定时器 */
let progressTimer: ReturnType<typeof setInterval> | null = null
/** 标记接口是否已返回 */
let uploadDone = false
/** 标记动画是否已完成（防止重复 emit） */
let hasFinished = false

// ==================== 核心动画逻辑 ====================

/** 每个步骤对应的进度百分比段 */
function getStepPercents(): number[] {
  const total = props.steps.length
  // 均分到95%，如4步则为 [23, 47, 71, 95]
  return props.steps.map((_, i) => Math.floor(((i + 1) / total) * 95))
}

/** 开始步骤动画 */
function startAnimation() {
  const totalSteps = stepList.value.length
  const stepPercents = getStepPercents()
  let currentStep = 0

  // 第一个步骤立即进入进行中
  stepList.value[0].status = 'active'
  stepList.value[0].stateText = '进行中'

  let targetPercent = stepPercents[0]
  let lastStepTime = Date.now()

  progressTimer = setInterval(() => {
    const elapsed = Date.now() - lastStepTime
    const stepDuration = props.durations[currentStep] || 2000

    if (elapsed >= stepDuration && currentStep < totalSteps - 1) {
      // 当前步骤完成
      stepList.value[currentStep].status = 'done'
      stepList.value[currentStep].stateText = '完成'
      currentStep++
      // 下一个步骤进入进行中
      stepList.value[currentStep].status = 'active'
      stepList.value[currentStep].stateText = '进行中'
      targetPercent = stepPercents[currentStep]
      lastStepTime = Date.now()
    } else if (currentStep >= totalSteps - 1 && elapsed >= stepDuration) {
      // 最后一个步骤时间到
      if (uploadDone) {
        // 接口已返回，完成最后一步
        stepList.value[currentStep].status = 'done'
        stepList.value[currentStep].stateText = '完成'
        if (progressTimer) { clearInterval(progressTimer); progressTimer = null }
        // 进度条跳到95-99再走完到100
        const finalPercent = Math.floor(95 + Math.random() * 4)
        percent.value = finalPercent
        setTimeout(() => {
          percent.value = 100
          setTimeout(() => {
            if (!hasFinished) { hasFinished = true; emit('finished') }
          }, 600)
        }, 1000)
        return
      }
      // 接口未返回，缓慢爬进度，上限94%
      percent.value = Math.min(percent.value + 0.1, 94)
      return
    }

    // 平滑增长进度
    const progress = Math.min(elapsed / stepDuration, 1)
    const prevPercent = currentStep > 0 ? stepPercents[currentStep - 1] : 0
    percent.value = Math.floor(prevPercent + (targetPercent - prevPercent) * progress)
  }, 50)
}

/** 接口返回后完成动画（定时器已停时手动触发） */
function finishAnimation() {
  if (!progressTimer) {
    const lastIdx = stepList.value.length - 1
    stepList.value[lastIdx].status = 'done'
    stepList.value[lastIdx].stateText = '完成'
    const finalPercent = Math.floor(95 + Math.random() * 4)
    percent.value = finalPercent
    setTimeout(() => {
      percent.value = 100
      setTimeout(() => {
        if (!hasFinished) { hasFinished = true; emit('finished') }
      }, 600)
    }, 1000)
  }
}

/** 点击关闭按钮 */
function handleClose() {
  emit('close')
}

// ==================== 监听 done prop ====================

watch(() => props.done, (val) => {
  if (val) {
    uploadDone = true
    finishAnimation()
  }
})

// ==================== 生命周期 ====================

// 组件挂载后立即开始动画
startAnimation()

onBeforeUnmount(() => {
  if (progressTimer) { clearInterval(progressTimer); progressTimer = null }
})
</script>
