Component({
  properties: {
    endTime: {
      type: String,
      value: ''
    },
    startTime:{
      type: String,
      value: ''
    }
  },
  data: {
    countdown: {
      days: "00",
      hours: "00",
      minutes: "00",
      seconds: "00"
    },
    isStart:false,
    showCountdown: true,
    timer: null
  },
  lifetimes: {
    attached() {
      if (this.properties.endTime && this.properties.startTime) {
        const target = new Date(this.properties.endTime).getTime();
        const start = new Date(this.properties.startTime).getTime();
        this.startCountdown(target,start);
      }
    },
    detached() {
      this.clearTimer();
    }
  },
  methods: {
    startCountdown(endTime,startTime) {
      this.clearTimer();
      this.data.timer = setInterval(() => {
        const now = Date.now();
        let diff = Math.floor((endTime - now) / 1000);
        if(startTime > now){
          diff = Math.floor((endTime - startTime) / 1000);
        }
        if (diff <= 0) {
          this.clearTimer();
          this.setData({ showCountdown: false,isStart:false });
          this.triggerEvent("finish"); // 通知父组件倒计时结束
          return;
        }
        if(startTime > now && this.data.isStart){
          return;
        }
        const days = Math.floor(diff / (60 * 60 * 24));
        const hours = Math.floor((diff % (60 * 60 * 24)) / 3600);
        const minutes = Math.floor((diff % 3600) / 60);
        const seconds = diff % 60;

        this.setData({
          isStart:true,
          countdown: {
            days: this.formatNum(days),
            hours: this.formatNum(hours),
            minutes: this.formatNum(minutes),
            seconds: this.formatNum(seconds)
          }
        });
      }, 1000);
    },
    formatNum(n) {
      return n < 10 ? "0" + n : n;
    },
    clearTimer() {
      if (this.data.timer) {
        clearInterval(this.data.timer);
        this.data.timer = null;
      }
    }
  }
});
