<template>
  <van-button native-type="button" :disabled="currentDisabled" :loading="loading">{{ curretnValue }}</van-button>
</template>

<script>
export default {
  name: 'CountdownButton',
  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,
      loading: false,
      timer: null
    }
  },
  computed: {
    curretnValue() {
      const longTime = this.seconds - this.currentSeconds
      return longTime < this.seconds ? `${longTime}秒后重发` : this.defaultValue
    }
  },
  methods: {
    genTimer() {
      this.timer && clearInterval(this.timer)
      this.timer = setInterval(() => {
        this.currentSeconds++
        if (this.currentSeconds === this.seconds) {
          this.stop()
        }
      }, this.step)
    },
    start() {
      this.loading = false
      this.currentDisabled = true
      this.genTimer()
    },
    stop() {
      this.timer && clearInterval(this.timer)
      this.currentSeconds = 0
      this.currentDisabled = false
    }
  }
}
</script>

<style lang="scss" scoped>
.van-button {
  height: 40px;
  line-height: 38px;
}
.van-button--default {
  border-color: #ccc;
}
</style>
