<template>
  <section class="van-count-down-container absolute top-[50%] left-[50%] translate-[-50%] w-[90%] h-[120px] flex-center text-[68px]">
    {{ countDownStr }}<span v-if="showSpan" class="text-[42px] ml-[4px] mt-[20px]">s</span>
  </section>
</template>

<script setup lang="ts">
  /*
   * 组件名: CountDown
   * 组件用途: 倒计时组件
   * 创建日期: 2024/8/16
   * 编写者: JutarryWu
   */
  const props = defineProps({
    time: {
      type: Number,
      default: 0
    },
    text: {
      type: String,
      default: '测试训练即将开始！'
    }
  })
  const emit = defineEmits(['endCountDown'])
  let 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>

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