<template>
  <el-button v-bind="$attrs" :disabled="currentDisabled" @click="start">{{ currentValue }}</el-button>
</template>

<script>
export default {
  name: 'Countdown',
  props: {
    step: { type: Number, default: 1000 },
    disabled: { type: Boolean, default: false },
    seconds: { type: Number, default: 60 },
    defaultValue: { type: String, default: '获取验证码' },
  },
  data() {
    return {
      currentDisabled: false,
      currentSeconds: 0,
      timer: null,
    }
  },
  watch: {
    disabled: {
      immediate: true,
      handler(value) {
        this.currentDisabled = value
      },
    },
  },
  computed: {
    currentValue() {
      const longTime = this.seconds - this.currentSeconds
      return longTime < this.seconds ? `${longTime}秒后重发` : this.defaultValue
    },
  },
  methods: {
    genTimer() {
      this.clearTimer()
      this.timer = setInterval(() => {
        this.currentSeconds++
        if (this.currentSeconds === this.seconds) {
          this.stop()
        }
      }, this.step)
    },
    clearTimer() {
      this.timer && clearInterval(this.timer)
    },
    start() {
      this.currentDisabled = true
      this.genTimer()
      this.$emit('start')
    },
    stop() {
      this.clearTimer()
      this.currentSeconds = 0
      this.currentDisabled = false
      this.$emit('stop')
    },
  },
}
</script>
