<template>
  <el-button v-bind="$attrs" :disabled="currentDisabled" @click="start">{{ curretnValue }}</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() {
        return this.$t('loginCode.sendCodeText')
      }
    }
  },
  data() {
    return {
      currentDisabled: false,
      currentSeconds: 0,
      timer: null
    }
  },
  watch: {
    disabled: {
      immediate: true,
      handler(value) {
        this.currentDisabled = value
      }
    }
  },
  computed: {
    curretnValue() {
      const longTime = this.seconds - this.currentSeconds
      return longTime < this.seconds ? `${longTime}S` : 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>
