<script setup lang="ts">
/*
   * 组件名: CountDown
   * 组件用途: 倒计时组件
   * 创建日期: 2024/8/16
   * 编写者: JutarryWu
   */
const props = defineProps({
  time: {
    type: Number,
    default: 0,
  },
  text: {
    type: String,
    default: '测试训练即将开始！',
  },
  color: {
    type: String,
    default: 'black',
  },
  size: {
    type: Number,
    default: 36,
  },
})
const emit = defineEmits(['endCountDown'])
const countTimer = ref<ReturnType<typeof setInterval> | null>(null)

const secondNum = ref(0)
const countDownStr = ref('')
const showSpan = ref(false)

async function exec() {
  secondNum.value = props.time
  countDownStr.value = props.text

  countTimer.value = setInterval(() => {
    countDownStr.value = `${secondNum.value}`
    showSpan.value = true
    secondNum.value--
    if (secondNum.value < 0) {
      clearInterval(Number(countTimer.value))
      countTimer.value = null
      showSpan.value = false

      emit('endCountDown')
    }
  }, 1000)
}

onMounted(() => {
  exec()
})

onBeforeUnmount(() => {
  clearInterval(Number(countTimer.value))
  countTimer.value = null
  showSpan.value = false
})
</script>

<template>
  <section
    class="van-count-down-container absolute-center h-[45px] w-[90%] translate-[-50%] text-center align-bottom"
    :style="{ color, fontSize: `${size}px` }"
  >
    {{ countDownStr }}<span v-if="showSpan" class="ml-[4px] mt-[8px] text-[28px]">s</span>
  </section>
</template>

<style scoped lang="scss"></style>
