<template>
  <div class="order-section" v-if="!isRentalPage">
    <div class="order-point-header">
      <h1 class="order-point-h1">포인트</h1>
      <div>
        <span
          class="order-point-text"
          style="font-weight: 700; margin-right: 5px"
          >보유 포인트</span
        >
        <span class="order-point-text"
          >{{ numberWithCommas(holdingPoints) }}원</span
        >
      </div>
    </div>
    <div class="order-point-input-wrapper">
      <span class="order-point-span">사용</span>
      <input
        class="order-point-input"
        @input="bindNumber"
        :value="usingPoint"
        :style="{ color: usingPoint === 0 ? '#AAAAAA' : '#404040' }"
      />
    </div>
    <div class="order-checkbox">
      <input
        type="checkbox"
        v-model="checked"
        id="orderPointCheckbox"
        @click="onUsingAllPoints"
      />
      <label for="orderPointCheckbox" class="order-point-span">
        <div class="order-checkbox-img">전액 사용</div></label
      >
    </div>
  </div>
</template>

<script>
export default {
  name: "orderPoint",
  props: {
    isRentalPage: Boolean,
    holdingPoints: Number,
  },
  data() {
    return {
      checked: false,
    };
  },
  computed: {
    usingPoint: {
      get() {
        return this.$store.state.usingPoint;
      },
      set(value) {
        this.$store.commit("updateUsingPoint", value);
      },
    },
  },
  methods: {
    numberWithCommas(num) {
      return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    },
    onUsingAllPoints() {
      this.checked = !this.checked;
      if (this.checked) this.usingPoint = this.holdingPoints;
      else this.usingPoint = 0;
    },
    bindNumber(event) {
      this.usingPoint = event.target.value;
    },
  },
  watch: {
    usingPoint(val) {
      const reg = /[ㄱ-ㅎ|ㅏ-ㅣ|가-힣|a-z]/;
      if (reg.exec(val) !== null) this.usingPoint = val.replace(/[^0-9]/g, "");
      if (val % 1 !== 0) this.usingPoint = 0;

      if (val > this.holdingPoints) this.usingPoint = this.holdingPoints;

      if (val !== this.holdingPoints) this.checked = false;
    },
  },
};
</script>

<style></style>
