<template>
  <span>
    <slot v-bind:timeData="timeData">{{content}}</slot>
  </span>
</template>
<script>
export default {
  name: "CountDown",
  data() {
    return {
      timer: null,
      date: null,
      timeData:{},
      day: null,
      hour: null,
      min: null,
      sec: null,
      content: this.endText //显示
    };
  },
  props: {
    // 倒计时时间 (分钟)
    time: {
      type: Number,
      default: ""
    },
    endText: {
      type: String,
      default: "00:00:00"
    }
  },
  mounted() {
    this.countdowm(this.time);
  },
  methods: {
    // 开始倒计时
    countdowm(timestamp) {
      let self = this;
      let endTime = timestamp < 1000000000000 ? timestamp * 1000 : timestamp;
      self.timer = setInterval(function() {
        let nowTime = new Date();
        let t = endTime - nowTime.getTime();
        // 判断剩余时间是否 >0
        if (t > 0) {
          self.day = Math.floor(t / (60 * 60 * 24 * 1000));
          self.hour = Math.floor((t / 3600000) % 24);
          self.min = Math.floor((t / 60000) % 60);
          self.sec = Math.floor((t / 1000) % 60);
          let day = self.day < 10 ? "0" + self.day : self.day;
          let hour = self.hour < 10 ? "0" + self.hour : self.hour;
          let min = self.min < 10 ? "0" + self.min : self.min;
          let sec = self.sec < 10 ? "0" + self.sec : self.sec;
          let format = `${day}:${hour}:${min}:${sec}`;

          self.content = format;

          self.$set(self.timeData,'day',day)
          self.$set(self.timeData,'hours',hour)
          self.$set(self.timeData,'minutes',min)
          self.$set(self.timeData,'seconds',sec)
        } else {
          // 倒计时结束
          self.$emit("finish", 0);
          clearInterval(self.timer);
          self.content = "00:00:00:00";
        }
      }, 1000);
    }
  }
};
</script>
