<template>
  <el-tooltip :content="fullTime" placement="top" :disabled="!fullTime || fullTime === '--'">
    <span class="relative-time">{{ displayText }}</span>
  </el-tooltip>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import { formatRelativeTime } from '@/utils/time'

const props = defineProps<{
  /** 时间字符串、Date对象或时间戳 */
  time: string | Date | number | null | undefined
}>()

const displayText = ref('--')
const fullTime = ref('--')
let refreshTimer: number | undefined

function updateTime() {
  if (!props.time) {
    displayText.value = '--'
    fullTime.value = '--'
    return
  }
  const result = formatRelativeTime(props.time)
  displayText.value = result.displayText
  fullTime.value = result.fullTime

  // 30秒自动刷新（如果需要）
  if (result.needRefresh) {
    clearTimer()
    refreshTimer = window.setTimeout(() => {
      updateTime()
    }, 30000)
  }
}

function clearTimer() {
  if (refreshTimer !== undefined) {
    clearTimeout(refreshTimer)
    refreshTimer = undefined
  }
}

watch(() => props.time, () => {
  updateTime()
})

onMounted(() => {
  updateTime()
})

onBeforeUnmount(() => {
  clearTimer()
})
</script>

<style scoped>
.relative-time {
  font-size: 13px;
  color: #909399;
  cursor: default;
}
</style>
