<script setup lang="ts">
import dayjs from 'dayjs'

const props = defineProps<{ startAt?: string | number; endAt?: string | number }>()
const emits = defineEmits<{ end: [] }>()
const currentDate = ref(new Date())
const interval = ref()
const status = computed(() => {
  if (dayjs(currentDate.value).isBefore(dayjs(props.startAt))) {
    return 'waiting'
  } else if (
    dayjs(currentDate.value).isAfter(dayjs(props.startAt)) &&
    dayjs(currentDate.value).isBefore(dayjs(props.endAt))
  ) {
    return 'running'
  } else {
    return 'overdue'
  }
})
const time = computed(() =>
  dayjs({ waiting: props.startAt, running: props.endAt }[status.value]).diff(
    new Date(),
    'millisecond',
  ),
)
onMounted(() => {
  interval.value = setInterval(() => {
    currentDate.value = new Date()
  }, 1000)
})
onUnmounted(() => {
  clearInterval(interval.value)
})
</script>
<template>
  <div>
    <wd-count-down v-if="status!=='running'" :time="time" @finish="emits('end')">
      <template #default="{ current }">
        <div
          class="flex items-center text-white text-xs font-normal font-['PingFang_SC'] leading-normal whitespace-nowrap"
        >
          <div v-if="current.days" class="text-[#ef4343]">
            {{ current.days }}
          </div>
          <span v-if="current.days">天</span>
          <div v-if="current.hours && !current.days" class="text-[#ef4343]">
            {{ current.hours }}
          </div>
          <span v-if="current.hours && !current.days">小时</span>
          <div v-if="current.minutes && !current.hours && !current.days" class="text-[#ef4343]">
            {{ current.minutes }}
          </div>
          <span v-if="current.minutes && !current.hours && !current.days">分钟</span>
          <div
            v-if="current.seconds && !current.minutes && !current.hours && !current.days"
            class="text-[#ef4343]"
          >
            {{ current.seconds }}
          </div>
          <span v-if="current.seconds && !current.minutes && !current.hours && !current.days">
            秒
          </span>
          <span v-if="current.days || current.hours || current.minutes || current.seconds">
            后 报名{{ { waiting: '开始', running: '截止' }[status] }}
          </span>
          <span v-else>加载中...</span>
        </div>
      </template>
    </wd-count-down>
  </div>
</template>
