<template>
  <div
    class="sk-verification-code sk-flex sk-center"
    :class="{
      'sk-left-radio': $attrs.rightRound,
      'sk-radio': $attrs.round,
      'sk-disabled': disabled
    }"
    @click="handlerClick"
  >
    <span v-show="!disabled" v-loading="loading">发送验证码</span>
    <span v-show="disabled">{{ countDown }}</span>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, PropType } from 'vue'
import { set, remove, judge } from './hooks/storage'
import { ElMessage } from 'element-plus'

export default defineComponent({
  name: 'SkVerificationCode',
  props: {
    time: {
      type: Number,
      default: 5,
    },
    sendCode: {
      type: Function as PropType<() => Promise<boolean>>,
      default: () => {
        return new Promise(resolve => {
          setTimeout(() => {
            resolve(true)
          }, 1000)
        })
      },
    },
  },
  setup(props) {
    const countDown = ref(props.time)
    const loading = ref(false)
    let disabled = ref(false)
    let timer = null
    const count = judge()
    if (count !== 0) {
      countDown.value = count
      startCount()
    }

    function startCount() {
      disabled.value = true
      countDown.value = countDown.value - 1
      set(countDown.value)
      timer = setInterval(() => {
        countDown.value = countDown.value - 1
        set(countDown.value)
        if (countDown.value <= 0) {
          stopCount()
        }
      }, 1000)
    }

    function stopCount() {
      countDown.value = props.time
      clearInterval(timer)
      remove()
      disabled.value = false
    }

    const handlerClick = async () => {
      if (!disabled.value) {
        loading.value = true
        const res = await props.sendCode()
        ElMessage.success('验证码已发送！')
        if (res) {
          loading.value = false
          startCount()
        }
      }
    }


    return {
      handlerClick,
      countDown,
      disabled,
      loading,
    }
  },
})
</script>

