<template>
  <span ref="aosButton" class="aos-count-time" @click="handleClick" :style="{width: countWidth}" :class="{counted:showCountTime,disabledClass:disabled}">
    <span v-show="!showCountTime">
      {{defaultName}}
    </span>
    <span v-show="showCountTime">
      {{countName}}{{countTime}}s
    </span>
  </span>
</template>
<script>
export default {
  name: 'AosCountTime',
  props: {
    type: {
      type: String,
      default: 'default'
    },
    time: {
      type: Number,
      default: 0
    },
    countName: {
      type: String,
      default: ''
    },
    defaultName: {
      type: String,
      default: ''
    },
    // 初始化文字是否可点击
    disabled: {
      type: Boolean,
      default: false
    },
    // 是否自动触发倒计时
    autoCount: {
      type: Boolean,
      default: true
    }
  },
  data(){
    return {
      copyTime: this.time,
      countTime: 0,
      showCountTime: false,
      countWidth: '',
      func: ''
    }
  },
  mounted(){
    this.countWidth = this.$refs.aosButton.offsetWidth + 'px';
  },
  methods: {
    handleClick(){
      this.$emit('click');
      if(this.autoCount){
        this.startCount()
      }
    },
    startCount(){
      if(this.disabled || this.showCountTime){
        return;
      }
      let self = this;
      this.showCountTime = true;
      this.countTime = this.copyTime;
      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>
