<template>
  <div v-bind:style="{ display: hasNsDeal ? 'inherit' : 'none' }">
    <div :class="`nsDealTimer_wrapper nsDealTimer_wrapper${index}`">
      <div v-bind:class="`nsDeal_timer${index}`"></div>
      <div style="margin-left: 10px">남았어요!</div>
    </div>
  </div>
</template>

<script>
export default {
  name: "nosearchDealTimer",
  props: {
    index: Number,
    benefitUseType: String,
    periodDiscountStart: String,
    periodDiscountEnd: String,
  },
  data() {
    return { hasNsDeal: false };
  },
  created: function () {
    this.checkTimedeal();
    if (this.hasNsDeal) this.nsDealtimer();
  },
  methods: {
    checkTimedeal() {
      const startTime = new Date(
        this.periodDiscountStart.replace(/-/gi, "/")
      ).getTime();
      const endTime = new Date(
        this.periodDiscountEnd.replace(/-/gi, "/")
      ).getTime();
      const nowTime = new Date().getTime();
      if (
        this.benefitUseType === "periodDiscount" &&
        nowTime > startTime &&
        nowTime < endTime
      ) {
        this.hasNsDeal = true;
      }
    },
    nsDealtimer() {
      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.querySelectorAll(`.nsDeal_timer${this.index}`)].map(
            (i) => (i.innerHTML = daysStr + hoursStr + minutesStr)
          );
        } else {
          [...document.querySelectorAll(`.nsDeal_timer${this.index}`)].map(
            (i) => (i.innerHTML = hoursStr + minutesStr + ":" + secondsStr)
          );
        }

        if (days === 0 && secondsInMs > 0) {
          document.querySelector(
            `.nsDealTimer_wrapper${this.index}`
          ).className += " timesUp";
        }

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

<style></style>
