<template>
    <div class="countdown">
        <div v-show="days > 0" class="countdown-item days">{{ days }} 天</div>
        <div class="countdown-item hours">{{ doubleDigit(hours) }}</div>
        <div class="paddingB2">:</div>
        <div class="countdown-item minutes">{{ doubleDigit(minutes) }}</div>
        <div class="paddingB2">:</div>
        <div class="countdown-item seconds">{{ doubleDigit(seconds) }}</div>
    </div>
</template>

<script>
export default {
    props: {
        targetTime: {
            type: String,
            required: true
        }
    },
    data() {
        return {
            days: 0,
            hours: 0,
            minutes: 0,
            seconds: 0
        }
    },
    computed: {
        doubleDigit() {
            return n => (n < 10 ? `0${n}` : n)
        }
    },
    mounted() {
        this.starCountTime()
    },
    watch: {
        targetTime: {
            deep: true,
            handler(newVal, oldVal) {
                this.starCountTime()
            }
        }
    },
    methods: {
        starCountTime() {
            this.countDown()
            this.intervalId = setInterval(() => this.countDown(), 1000)
        },
        countDown() {
            const targetDate = new Date(this.targetTime)
            const nowDate = new Date()
            const diffSeconds = Math.round((targetDate - nowDate) / 1000)

            if (diffSeconds < 0) {
                clearInterval(this.intervalId)
                this.$emit('timeDone')
                return
            }

            this.days = Math.floor(diffSeconds / (3600 * 24))
            this.hours = Math.floor((diffSeconds % (3600 * 24)) / 3600)
            this.minutes = Math.floor((diffSeconds % 3600) / 60)
            this.seconds = diffSeconds % 60
        }
    },
    beforeDestroy() {
        clearInterval(this.intervalId)
    }
}
</script>

<style lang="scss">
.countdown {
    display: flex;
    align-items: center;
    justify-content: center;
}

.countdown-item {
    font-size: 22rpx;
    text-align: center;
    margin: 0 6rpx;
}

.countdown-item.days {
    font-size: 22rpx;
    margin-right: 8rpx;
}

.countdown-item.hours,
.countdown-item.minutes,
.countdown-item.seconds {
    color: white;
    width: 35rpx;
    height: 42rpx;
    line-height: 42rpx;
    background: $color-theme;
    border-radius: 8rpx;
}
</style>
