<template>
    <span v-for="(digit, index) in digits" :key="index" class="digit">{{ digit }}</span>
</template>

<script>
import { ref, watch, onMounted } from 'vue';

export default {
    props: {
        number: {
            type: Number,
            required: true,
        },
        duration: {
            type: Number,
            default: 1000,
        },
    },
    setup(props) {
        const digits = ref(Array.from({ length: props.number.toString().length }, () => 0));

        const animateDigits = () => {
            const targetNumber = props.number;
            const { duration } = props;
            const totalFrames = 100;
            let increment;

            if (Number.isInteger(targetNumber)) {
                increment = Math.floor(targetNumber - Number(digits.value.join(''))) / totalFrames;
            } else {
                increment = (targetNumber - Number(digits.value.join(''))) / totalFrames;
            }

            let currentNumber = Number(digits.value.join(''));

            const interval = setInterval(() => {
                currentNumber += increment;
                if ((increment > 0 && currentNumber >= targetNumber) || (increment < 0 && currentNumber <= targetNumber)) {
                    currentNumber = targetNumber;
                    clearInterval(interval);
                }

                const roundedNumber = Math.round(currentNumber * 100) / 100; // 保留两位小数
                const splitNumber = roundedNumber.toString().split('.');
                const integerPart = splitNumber[0];
                const decimalPart = splitNumber[1] || '';

                const integerDigits = integerPart.split('').map(Number);
                const decimalDigits = decimalPart.split('').map(Number);

                digits.value = [];

                digits.value = digits.value.concat(integerDigits);
                if (decimalPart !== '') {
                    digits.value.push('.');
                    digits.value = digits.value.concat(decimalDigits);
                }
            }, duration / totalFrames);
        };

        onMounted(() => {
            animateDigits();
        });

        watch(
            () => props.number,
            () => {
                animateDigits();
            },
        );
        return { digits };
    },
};
</script>

<style>
.digit {
    display: inline-block;
    margin-right: 5px;
}
</style>
