<template>
  <div class="subsidy-container">
    <div class="subsidy-label">发放补贴</div>
    <div class="number-container">
      <div class="number-item" v-for="(digit, index) in displayDigits" :key="index">
        {{ digit }}
      </div>
    </div>
    <div class="subsidy-unit">{{ unit }}</div>
  </div>
</template>

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

const props = defineProps<{
  amount: number
}>()

const displayAmount = ref(0)
const animationDuration = 2000
const animationSteps = 60

const unit = computed(() => {
  if (displayAmount.value >= 10000) {
    return '亿元'
  }
  return '万元'
})

const displayDigits = computed(() => {
  let value = displayAmount.value

  if (value >= 10000) {
    value = value / 10000
    const integerPart = Math.floor(value)
    const decimalPart = Math.round((value - integerPart) * 100)
      .toString()
      .padStart(2, '0')
    return [integerPart.toString(), '.', ...decimalPart]
  } else if (value < 1) {
    const decimalStr = value.toFixed(2).replace('0.', '')
    return ['0', '.', ...decimalStr.padEnd(2, '0')]
  } else {
    const integerStr = Math.floor(value).toString().padStart(4, '0').slice(-4)
    return integerStr.split('')
  }
})

const animateValue = (start: number, end: number, duration: number) => {
  const startTime = performance.now()

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

    const easeOutQuad = (t: number) => t * (2 - t)
    const easedProgress = easeOutQuad(progress)

    displayAmount.value = start + (end - start) * easedProgress

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

  requestAnimationFrame(animate)
}

watch(
  () => props.amount,
  (newAmount) => {
    animateValue(displayAmount.value, newAmount, animationDuration)
  },
  { immediate: true }
)
</script>

<style lang="scss" scoped>
.subsidy-container {
  display: flex;
  align-items: center;
  margin: 30px 0;
  padding: 0 24px;

  .subsidy-label {
    color: #06baad;
    font-size: 36px;
    line-height: 56px;
    letter-spacing: 1px;
    margin-right: 20px;
  }

  .number-container {
    display: flex;
    gap: 10px;
  }

  .number-item {
    width: 80px;
    height: 100px;
    background: url('@/assets/images/number_bg.png');
    background-size: 100% 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 64px;
    font-weight: bold;
    color: #01ffe6;
    transition: transform 0.1s ease;
  }

  .subsidy-unit {
    color: #06baad;
    font-size: 36px;
    line-height: 56px;
    letter-spacing: 1px;
    margin-left: 20px;
  }
}
</style>
