<template>
  <el-button ref="aosButton" :type="type" @click="handleClick" :disabled="disabled" :style="{width: countWidth}">
      <span v-show="!showCountTime">
        <slot></slot>
      </span>
      <span v-show="showCountTime">
        {{countName}}{{countTime}}s
      </span>
  </el-button>
</template>
<script>
export default {
  name: 'AosCountButton',
  props: {
    type: {
      type: String,
      default: 'default'
    },
    time: {
      type: Number,
      default: 0
    },
    countName: {
      type: String,
      default: ''
    },
    defaultName: {
      type: String,
      default: ''
    },
    // 自动倒计时
    autoCount: {
      type: Boolean,
      default: true
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data(){
    return {
      copyTime: this.time,
      countTime: 0,
      showCountTime: false,
      countWidth: '',
      func: ''
    }
  },
  mounted(){
    this.countWidth = this.$refs.aosButton.$el.offsetWidth + 'px';
  },
  methods: {
    handleClick(){
      this.$emit('click');
      if(this.autoCount){
        this.startCount()
      }
    },
    startCount(){
      this.showCountTime = true;
      this.countTime = this.copyTime;
      let self = this;
      this.func = setInterval(function(){
        self.countTime--;
        if(self.countTime === 0 || !self.countTime){
          self.stopCount();
        }
      },1000);
    },
    stopCount(){
      clearInterval(this.func);
      this.showCountTime = false;
      this.countTime = 0;
    }
  }
}
</script>