<template>
  <div class="progress-chart">
    <template v-for="(item, index) in data" :key="index">
      <div class="progress-item">
        <el-progress
          type="circle"
          :percentage="Number(displayValues[index])"
          :color="item.color"
          :width="159"
          :stroke-width="12"
        >
          <template #default>
            <div class="progress-text">{{ displayValues[index].toFixed(1) }}%</div>
          </template>
        </el-progress>
        <div class="progress-label">{{ item.label }}</div>
      </div>
      <div v-if="index < data.length - 1" class="vertical-line"></div>
    </template>
  </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 animationSteps = 60

// 动画函数
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] = start + (end - start) * easedProgress

    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: #68d0c6;
$track-color: #282c38;

.progress-chart {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 0;

  // 进度条项
  .progress-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    flex: 1;
    position: relative;

    // 进度条轨迹颜色
    :deep(.el-progress-circle__track) {
      stroke: $track-color;
    }

    // 进度条文字
    .progress-text {
      font-size: 30px;
      font-weight: bold;
      color: #fff;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }

    // 进度条标签
    .progress-label {
      margin-top: 17px;
      font-size: 26px;
      color: $text-color;
      text-align: center;
    }
  }

  // 垂直分割线
  .vertical-line {
    width: 2px;
    height: 212px;
    background: url('@/assets/images/vertical_line.png') center no-repeat;
    flex-shrink: 0;
  }
}
</style>
