
<style lang="less">
@import './index.less';
</style>

<template>
  <van-count-down
    ref="countDown"
    :millisecond="millisecond"
    :time="newTime"
    :format="format"
    :auto-start="autoStart"
    @finish="onFihish"
    @change="onChange"
    :style="wrapStyle"
  >
    <!-- 自定slot -->
    <template v-slot="currentTime">
      <slot :days="currentTime.days" :hours="currentTime.hours" :minutes="currentTime.minutes" :seconds="currentTime.seconds" :milliseconds="currentTime.milliseconds" />
    </template>
  </van-count-down>
</template>

<script>
import { CountDown } from 'vant';
import { countDownProps } from './props';

export default {
  components: {
    VanCountDown: CountDown
  },

  props: {
    ...countDownProps
  },
  data() {
    return {
      newTime: this.time
    };
  },
  computed: {
    wrapStyle() {
      return `line-height: 20px;color:${this.color};font-size:${this.fontSize}px;`;
    }
  },
  watch: {

    /**
     * 扩展
     * 监听endDateTime将其转化为time
     */
    endDateTime: {
      immediate: true,
      handler(endDateTime) {
        if (endDateTime) {
        //  ios的日期格式需要将2019-11-17 00:00:00 转 化为2019/11/17 00:00:00
          endDateTime = endDateTime.replace(/-/g, '/');
          const endTime = new Date(Date.parse(endDateTime));
          const nowTime = new Date();
          const differTime = endTime.getTime() - nowTime.getTime();
          this.newTime = differTime;
        }
      }


    }
  },
  methods: {
    /**
     * 倒计时结束时触发
     */
    onFihish() {
      this.$emit('finish');
    },
    /**
     * 	倒计时变化时触发
     */
    onChange(timeData) {
      this.$emit('change', timeData);
    },
    /**
     * 开始倒计时
     */
    start() {
      if (this.$refs.countDown) {
        this.$refs.countDown.start();
      }
    },
    /**
     * 暂停倒计时
     */
    pause() {
      if (this.$refs.countDown) {
        this.$refs.countDown.pause();
      }
    },
    /**
     * 重设倒计时，若auto-start为true，重设后会自动开始倒计时
     */
    reset() {
      if (this.$refs.countDown) {
        this.$refs.countDown.reset();
      }
    },
  }
};
</script>
