<template>
  <section class="sv-countdown-wrapper">
    <slot>
      {{countdownTime}}
    </slot>
  </section>
</template>

<script>
  export default {
    name: 'svCountdown',
    data () {
      return {
        intervalInstance: null,
        nowTimestamp: ''
      }
    },
    props: {
      endTime: {
        type: [Number, Date, String],
        default: '',
        required: true
      },
      format: {
        type: String,
        default: 'hh时mm分ss秒'
      },
      value: {
        type: [Array, String],
        default: ''
      }
    },
    methods: {
      formatValue (timestamp) {
        if (timestamp <= 0) {
          window.clearInterval(this.intervalInstance)
          return '0分钟'
        }
        let hours = window.parseInt(timestamp / 1000 / 60 / 60)
        let minutes = window.parseInt(timestamp / 1000 / 60 % 60)
        let seconds = window.parseInt(timestamp / 1000 % 60)
        if (hours) {
          hours = this.paddingLeftZero(hours)
        } else {
          this.format.substring(this.format.indexOf('m'))
        }
        if (minutes) {
          minutes = this.paddingLeftZero(minutes)
        } else {
          this.format.substring(this.format.indexOf('s'))
        }
        seconds = this.paddingLeftZero(seconds)

        let [hStr, mStr, sStr] = [hours + '', minutes + '', seconds + '']
        let timeStr = this.format.replace(/[hms]+/g, match => {
          switch (match.charAt(0)) {
            case 'h':
              return hStr.substring(0, match.length)
            case 'm':
              return mStr.substring(0, match.length)
            case 's':
              return sStr.substring(0, match.length)
          }
        })
        this.$emit('change', timeStr)
        return timeStr
      },
      paddingLeftZero (str) {
        str = str + ''
        return ('00' + str).substring(str.length)
      }
    },
    computed: {
      countdownTime () {
        if (!this.endTime) {
          return 0
        }
        let endTime = this.endTime.replace(/-/g, '/') // IOS中日期分隔符如果是"-"，则会报错
        let date = new Date(endTime)
        return this.formatValue(date.getTime() - this.nowTimestamp)
      }
    },
    created () {
      let date = new Date()
      this.nowTimestamp = date.getTime()
      this.intervalInstance = window.setInterval(() => {
        date = new Date()
        this.nowTimestamp = date.getTime()
      }, 1000)
    }
  }
</script>

<style lang="scss" rel="stylesheet/scss">
  @import "../../styles/base";
  .sv-countdown-wrapper{
    display: inline;
    color:#333;
    font-size: pxToRem(28);
  }
</style>
