<template>
    <div v-if="showTimestamp" class="message-timestamp-content">
        {{ timestampShowContent }}
    </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'

interface MessageTimestampProps {
    currTime: number
    prevTime: number
}

const props = defineProps<MessageTimestampProps>()

const { t } = useI18n()

const formatNum = (num: number): string => {
    return num < 10 ? `0${num}` : num.toString()
}

const calculateTimestamp = (timestamp: number) => {
    const todayZero = new Date().setHours(0, 0, 0, 0)
    const thisYear = new Date(new Date().getFullYear(), 0, 1, 0, 0, 0, 0).getTime()
    const target = new Date(timestamp)
    const oneDay = 24 * 60 * 60 * 1000
    const oneWeek = 7 * oneDay
    const diff = todayZero - target.getTime()

    if (diff <= 0) {
        return `${formatNum(target.getHours())}:${formatNum(target.getMinutes())}`
    }

    if (diff <= oneDay) {
        return `${t('昨天')} ${formatNum(target.getHours())}:${formatNum(target.getMinutes())}`
    }

    if (diff <= oneWeek - oneDay) {
        const weekdays = [t('星期日'), t('星期一'), t('星期二'), t('星期三'), t('星期四'), t('星期五'), t('星期六')]
        const weekday = weekdays[target.getDay()]
        return `${weekday} ${formatNum(target.getHours())}:${formatNum(target.getMinutes())}`
    }

    if (target.getTime() >= thisYear) {
        return `${target.getMonth() + 1}/${target.getDate()} ${formatNum(target.getHours())}:${formatNum(
            target.getMinutes(),
        )}`
    }

    return `${target.getFullYear()}/${target.getMonth() + 1}/${target.getDate()} ${formatNum(
        target.getHours(),
    )}:${formatNum(target.getMinutes())}`
}

const timestampShowContent = computed(() => {
    if (props.currTime <= 0) {
        return ''
    }

    if (!props.prevTime || props.prevTime <= 0) {
        return calculateTimestamp(props.currTime * 1000)
    }

    const minDiffToShow = 10 * 60
    const diff = props.currTime - props.prevTime

    if (diff >= minDiffToShow) {
        return calculateTimestamp(props.currTime * 1000)
    }

    return ''
})

const showTimestamp = computed(() => timestampShowContent.value !== '')
</script>

<style scoped>
.message-timestamp-content {
    margin: 0 auto;
    color: #999;
    font-size: 12px;
    overflow-wrap: anywhere;
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    padding: 0 20px 30px;
}
</style>