<template>
  <button :class="disabled?'active_phone time-btn':'time-btn'"
          type="button"
          :disabled="disabled"
          @click="run">{{ text }}
  </button>
</template>

<script>
export default {
  name: 'mk-timer-btn',
  props: {
    second: {
      type: Number,
      default: 60
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data: function() {
    return {
      time: 0
    };
  },
  watch: {
    disabled: function(val, oldval) {
      let interid;
      if (val) {
        interid = setInterval(this.timer, 1000);
      } else {
        window.clearInterval(interid);
      }
    }
  },
  methods: {
    run: function() {
      this.time = this.second;
      this.$emit('callback');
    },
    timer: function() {
      if (this.time > 0) {
        this.time--;
      } else {
        this.$emit('countfinish');
      }
    }
  },
  computed: {
    text: function() {
      return this.disabled ? this.time + '秒 后重新获取' : '获取验证码';
    }
  }
};
</script>

