countdown.js 2.76 KB
// pages/tab/shopMall/pages/discover/components/crowdfunding/components/countdown.js
import {
  iosTimeFormat
} from '~/utils/format'
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    itemId: Number,
    status: Number,
    time: {
      type: Array,
      observer(n) {
        n.length && n.length == 2 ? this.countDown(n) : this.setData({
          timeFlag: true
        })
      }
    }
  },

  /**
   * 组件的初始数据
   */
  data: {},
  lifetimes: {
    ready() { }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    countDown(params) {
      const {
        status,
        itemId,
        timeFlag
      } = this.data
      if (status == 3) return this.setData({
        timeFlag: true
      })
      // status 1:未开始,2进行中,3已结束
      const addZero = i => i < 10 ? `0${i}` : `${i}`,
        [activityStartTime, activityEndTime] = params
      if (!activityStartTime && !activityEndTime) return
      const start = iosTimeFormat(activityStartTime),
        end = iosTimeFormat(activityEndTime)
      if ((new Date().getTime() > new Date(end).getTime())) {
        return this.changeCountdownActivity({
          currentStatus: status,
          targetStatus: 3,
          itemId
        })
      }
      if (new Date().getTime() >= new Date(start).getTime() && status != 2) {
        return this.changeCountdownActivity({
          currentStatus: status,
          targetStatus: 2,
          itemId
        })
      }
      let starTime = new Date(),
        endTime = new Date(status == 2 ? end : start),
        lefttime = parseInt((endTime.getTime() - starTime.getTime()) / 1000),
        d = parseInt(lefttime / (24 * 60 * 60)),
        h = addZero(parseInt(lefttime / (60 * 60) % 24)),
        m = addZero(parseInt(lefttime / 60 % 60)),
        s = addZero(parseInt(lefttime % 60)),
        activityTime = {
          dayList: [{
            text: h,
            unit: '时'
          }, {
            text: m,
            unit: '分'
          }, {
            text: s,
            unit: '秒'
          }],
          type: {
            1: '距开始',
            2: '距结束'
          }[status]
        }
      if (d > 0) activityTime.day = addZero(d)
      if (this.time) clearTimeout(this.time)
      if (!timeFlag) wx.nextTick(() => {
        this.setData({
          activityTime,
          timeFlag: true
        }, () => {
          this.countDown(params)
        })
      })
      else this.time = setTimeout(() => {
        this.setData({
          activityTime,
          timeFlag: true
        })
        this.countDown(params)
      }, 1e3)

    },
    changeCountdownActivity(params) {
      this.setData({
        timeFlag: true
      })
      clearTimeout(this.time)
      wx.$eventbus.emit('changeCountdownActivity', params)
    }
  }
})