<template>
  <div class="horizontal-progress-chart">
    <div v-for="(item, index) in data" :key="index" class="progress-item">
      <span class="progress-label">{{ item.label }}</span>
      <el-progress :percentage="displayValues[index]" :color="item.color" :stroke-width="8">
      </el-progress>
    </div>
  </div>
</template>

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

// Props
const props = defineProps<{
  data: Array<{
    label: string
    value: number
    color: string
  }>
}>()

// 显示值，用于动画效果
const displayValues = ref<number[]>([])

// 动画配置
const animationDuration = 1200

// 动画函数
const animateValue = (start: number, end: number, index: number) => {
  const startTime = performance.now()

  const animate = (currentTime: number) => {
    const elapsed = currentTime - startTime
    const progress = Math.min(elapsed / animationDuration, 1)

    // 缓动函数：easeOutQuad
    const easeOutQuad = (t: number) => t * (2 - t)
    const easedProgress = easeOutQuad(progress)

    displayValues.value[index] = Number((start + (end - start) * easedProgress).toFixed(1))

    if (progress < 1) {
      requestAnimationFrame(animate)
    }
  }

  requestAnimationFrame(animate)
}

// 初始化和更新动画
const startAnimations = () => {
  displayValues.value = props.data.map(() => 0)

  // 为每个进度条启动动画
  props.data.forEach((item, index) => {
    setTimeout(() => {
      animateValue(0, item.value, index)
    }, index * 200) // 错开动画开始时间，增加视觉效果
  })
}

// 监听数据变化，重新启动动画
watch(
  () => props.data,
  () => {
    startAnimations()
  },
  { deep: true, immediate: true }
)

// 组件挂载时启动动画
onMounted(() => {
  startAnimations()
})
</script>

<style lang="scss" scoped>
// SCSS变量定义
$text-color: #00ffe6;
$track-color: #282c38;

.horizontal-progress-chart {
  width: 100%;

  .progress-item {
    margin-bottom: 26px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .progress-label {
      width: 176px;
      margin-right: 12px;
      font-size: 24px;
      color: $text-color;
    }

    :deep(.el-progress) {
      flex: 1;

      .el-progress__text {
        flex-shrink: 0;
        width: 100px;
        margin-left: 24px;
        color: #03a99d;
        font-size: 24px !important;
      }
    }

    :deep(.el-progress-bar__outer) {
      background-color: $track-color;
      background: linear-gradient(0deg, rgba(50, 125, 118, 0.31) 0%, rgba(0, 255, 230, 0.2) 100%);
      box-shadow: inset -2px 0px 2px 0px rgba(0, 255, 230, 0.46);
    }
  }
}
</style>
