<template>
  <div>
    <div
      v-bind:id="`timedeal_timer${index}`"
      class="timedeal-list-timer-wrapper"
    ></div>
  </div>
</template>

<script>
export default {
  name: "timedealListTimer",
  props: {
    index: Number,
    benefitUseType: String,
    periodDiscountEnd: String,
  },
  data() {
    return { hasTimedeal: false };
  },
  created: function () {
    this.checkTimedeal();
    if (this.hasTimedeal) this.timedealTimer();
  },
  methods: {
    checkTimedeal() {
      const endTime = new Date(
        this.periodDiscountEnd.replace(/-/gi, "/")
      ).getTime();
      const nowTime = new Date().getTime();
      if (this.benefitUseType === "periodDiscount" && nowTime < endTime) {
        this.hasTimedeal = true;
      }
    },
    timedealTimer() {
      const ddate = new Date(this.periodDiscountEnd.replace(/-/gi, "/"));
      let difference;
      const timer = () => {
        const now = new Date();
        difference = new Date(ddate - now);

        const secondsInMs = Math.floor(difference / 1000);
        const minutesInMs = Math.floor(secondsInMs / 60);
        const hoursInMs = Math.floor(minutesInMs / 60);
        const days = Math.floor(hoursInMs / 24);
        const seconds = secondsInMs % 60;
        const minutes = minutesInMs % 60;
        const hours = hoursInMs % 24;

        const daysStr = `${days}일 `;
        const hoursStr = `${hours < 10 ? `0${hours}` : hours}:`;
        const minutesStr = `${minutes < 10 ? `0${minutes}` : minutes}`;
        const secondsStr = `${seconds < 10 ? `0${seconds}` : seconds}`;

        if (days > 0) {
          document.getElementById(`timedeal_timer${this.index}`).innerHTML =
            daysStr + hoursStr + minutesStr;
        } else {
          document.getElementById(`timedeal_timer${this.index}`).innerHTML =
            hoursStr + minutesStr + ":" + secondsStr;
        }

        if (days < 0 && seconds < 0 && minutes < 0 && hours < 0) {
          stopTimer();
        }
      };
      const timedealTimer = setInterval(timer, 1000);
      const stopTimer = () => {
        clearInterval(timedealTimer);
        this.hasTimedeal = false;
      };
    },
  },
};
</script>

<style></style>
