<template>
  <view class="ml-countdown">
    <slot name="prefix">
      <view v-if="prefixText" class="ml-countdown-prefix">{{ prefixText || '' }}</view>
    </slot>
    <slot :secondVals="secondVals" :currVals="currVals" :timeDiffObj="timeDiffObj" :timeFormats="timeFormats" :timeLabels="timeLabels">
      <view class="ml-countdown-item" :class="[`time-${type}`]" v-for="(type) in timeFormats" :key="type">
        <text class="ml-countdown-time-num">{{ timeDiffObj[type] || 0 }}</text>
        <text class="ml-countdown-time-label">{{ timeLabels[type] || '' }}</text>
      </view>
    </slot>
    <slot name="suffix">
      <view v-if="suffixText" class="ml-countdown-suffix">{{ suffixText || '' }}</view>
    </slot>
  </view>
</template>

<script>
import XEUtils from 'xe-utils'

export default {
  name: 'MlCountdown',
  props: {
    value: [Number, String],
    formats: Array,
    prefixText: String,
    suffixText: String
  },
  data () {
    return {
      secondVals: 0,
      currVals: 0,
      timeLabels: {
        yyyy: '年',
        MM: '月',
        dd: '天',
        HH: '时',
        mm: '分',
        ss: '秒'
      },
      htime: null
    }
  },
  computed: {
    timeDiffObj () {
      return XEUtils.getDateDiff(Date.now(), Date.now() + this.currVals)
    },
    timeFormats () {
      if (this.formats && this.formats.length) {
        return this.formats
      }
      if (this.secondVals >= 31622400000) {
        return ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss']
      }
      if (this.secondVals >= 2678400000) {
        return ['MM', 'dd', 'HH', 'mm', 'ss']
      }
      if (this.secondVals >= 86400000) {
        return ['dd', 'HH', 'mm', 'ss']
      }
      return ['HH', 'mm', 'ss']
    }
  },
  watch: {
    value () {
      this.updateVal()
      this.stop()
      this.start()
    }
  },
  created () {
    this.updateVal()
    this.start()
  },
  beforeDestroy () {
    this.stop()
  },
  methods: {
    updateVal () {
      this.secondVals = XEUtils.toNumber(this.value || 0)
      this.currVals = this.secondVals
    },
    handleTime () {
      if (this.currVals > 1000) {
        this.currVals -= 1000
        this.htime = setTimeout(this.handleTime, 1000)
      } else {
        this.currVals = 0
        this.stop()
      }
    },
    start () {
      this.$emit('start', {})
      this.handleTime()
    },
    stop () {
      if (this.htime != null) {
        this.$emit('stop', {})
        clearTimeout(this.htime)
        this.htime = null
      }
    }
  }
}
</script>

<style lang="scss">
.ml-countdown {
  padding: 0 16rpx;
  .ml-countdown-prefix {
    display: inline-block;
    padding-right: 16rpx;
  }
  .ml-countdown-item {
    display: inline-block;
  }
  .ml-countdown-suffix {
    display: inline-block;
    padding-left: 16rpx;
  }
  .ml-countdown-time-num {
    color: $ml-theme-primary-color;
    padding: 0 8rpx;
    font-size: 1.6em;
  }
  .ml-countdown-time-label {
    padding: 0 8rpx;
  }
}
</style>
