<template>
  <view class="count-down">
    <text class="time" v-if="d !== '00'">{{ d }}天</text>
    <text class="time">{{ h }}</text>
    <text class="partition">:</text>
    <text class="time">{{ m }}</text>
    <text class="partition">:</text>
    <text class="time">{{ s }}</text>
  </view>
</template>

<script>
import dayjs from 'dayjs';
export default {
  name: 'count-down',
  props: {
    endDate: String,
  },
  data() {
    return {
      d: '',
      h: '',
      m: '',
      s: '',
    };
  },
  created() {
    this.countTime();
  },
  methods: {
    countTime() {
      let leftTime = dayjs(this.endDate).diff(dayjs(), 'millisecond');
      if (leftTime < 0) {
        this.d = '00';
        this.h = '00';
        this.m = '00';
        this.s = '00';
        return;
      }
      //定义变量 d,h,m,s保存倒计时的时间
      if (leftTime >= 0) {
        this.d = Math.floor(leftTime / 1000 / 60 / 60 / 24);
        this.h = Math.floor((leftTime / 1000 / 60 / 60) % 24);
        this.m = Math.floor((leftTime / 1000 / 60) % 60);
        this.s = Math.floor((leftTime / 1000) % 60);
        this.d = this.d < 10 ? '0' + this.d : this.d;
        this.h = this.h < 10 ? '0' + this.h : this.h;
        this.m = this.m < 10 ? '0' + this.m : this.m;
        this.s = this.s < 10 ? '0' + this.s : this.s;
      }
      setTimeout(this.countTime, 1000);
    },
  },
};
</script>

<style lang="scss">
.count-down {
  display: flex;
  flex-direction: row;
  .time {
    padding: 2upx;
    background-color: $color-white;
    color: #ff5257;
    border-radius: 10upx;
    font-size: $font-md * 0.9;
  }
  .partition {
    margin: 2upx;
    color: #ff5257;
    font-size: $font-md * 0.9;
  }
}
</style>
