<template>
  <div style="max-width: 800px; margin: 0 auto" v-if="success">
    <user-info
      :userInfo="userInfo"
      :deliveryList="deliveryList"
      :onShowDeliveryPage="onShowDeliveryPage"
      :onShowPhoneWarningPopup="onShowPhoneWarningPopup"
    ></user-info>
    <div class="r-bar"></div>
    <oreder-item
      :isRentalPage="isRentalPage"
      :orderedItems="orderedItems"
    ></oreder-item>
    <div class="r-bar"></div>
    <order-point
      :isRentalPage="isRentalPage"
      :holdingPoints="holdingPoints"
    ></order-point>
    <div class="r-bar" v-if="!isRentalPage"></div>
    <payment-type :isRentalPage="isRentalPage"></payment-type>
    <div class="r-bar" v-if="!isRentalPage"></div>
    <order-price
      :isRentalPage="isRentalPage"
      :totalItemPrice="priceInfo.totalItemPrice"
      :totalDeliveryPrice="priceInfo.totalDeliveryPrice"
      :totalDiscountPrice="priceInfo.totalDiscountPrice"
      :totalPrice="priceInfo.totalPrice"
    ></order-price>
    <div class="r-bar" style="margin-bottom: 15px"></div>
    <order-term :isRentalPage="isRentalPage"></order-term>
    <div class="order-pay-button" @click="onPay">
      <span class="order-pay-button-text">{{
        isRentalPage
          ? "무료 상담 받기"
          : numberWithCommas(
              Number(priceInfo.totalPrice) - Number(usingPoint)
            ) + "원 결제하기"
      }}</span>
    </div>

    <delivery-page
      v-if="showDeliveryPage"
      :deliveryList="deliveryList"
      :onHideDeliveryPage="onHideDeliveryPage"
      :onSaveDeliveryInfo="onSaveDeliveryInfo"
    ></delivery-page>
    <warning-popup
      v-if="showPhoneWarningPopup"
      text1="휴대폰 번호가 정확하게 입력되었는지"
      text2="다시 한번 확인해주세요."
    ></warning-popup>
    <warning-popup
      v-if="showTermsWarningPopup"
      text1="결제정보확인 및 상품공급사"
      text2="개인정보 제공에 동의 체크를 해주세요."
    ></warning-popup>
    <warning-popup
      v-if="showBankWarningPopup"
      text1="무통장 입금 정보를 모두 다 입력하셨는지"
      text2="다시 한번 확인해주세요."
    ></warning-popup>
  </div>
</template>

<script>
import UserInfo from "./userInfo.vue";
import OrederItem from "./orderItem/orderItemComponent.vue";
import OrderPoint from "./orderPoint.vue";
import PaymentType from "./paymentType.vue";
import OrderPrice from "./orderPrice.vue";
import OrderTerm from "./orderTerm.vue";
import DeliveryPage from "./delivery/deliveryPage.vue";
import WarningPopup from "./warningPopup.vue";
import { store } from "./store.js";

let warningPopupTimer;

export default {
  name: "orderPage",
  store,
  components: {
    "oreder-item": OrederItem,
    "order-point": OrderPoint,
    "user-info": UserInfo,
    "payment-type": PaymentType,
    "order-price": OrderPrice,
    "order-term": OrderTerm,
    "delivery-page": DeliveryPage,
    "warning-popup": WarningPopup,
  },
  props: {
    isRentalPage: Boolean,
    userInfo: Object,
    holdingPoints: Number,
    priceInfo: Object,
    orderedItems: Array,
    deliveryList: Array,
    onPayItems: Function,
    onSaveDeliveryInfo: Function,
    onSuccessOrderPage: Function,
  },
  data() {
    return {
      success: false,
      showDeliveryPage: false,
      showPhoneWarningPopup: false,
      showTermsWarningPopup: false,
      showBankWarningPopup: false,
      warningCount: 0,
    };
  },
  created() {
    if (
      this.priceInfo &&
      this.holdingPoints >= 0 &&
      this.orderedItems &&
      this.onPayItems &&
      this.onSaveDeliveryInfo
    ) {
      this.success = true;
      if (this.onSuccessOrderPage) this.onSuccessOrderPage();
    }
  },
  computed: {
    usingPoint: {
      get() {
        return this.$store.state.usingPoint;
      },
    },
  },
  methods: {
    numberWithCommas(num) {
      return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    },
    onShowDeliveryPage() {
      this.showDeliveryPage = true;
      document.body.classList.add("not_scroll");
    },
    onHideDeliveryPage() {
      this.showDeliveryPage = false;
      document.body.classList.remove("not_scroll");
    },
    onShowPhoneWarningPopup() {
      if (this.warningCount === 0) {
        this.warningCount = 1;
        return;
      }

      if (warningPopupTimer) clearTimeout(warningPopupTimer);
      warningPopupTimer = setTimeout(() => {
        this.showPhoneWarningPopup = true;
        setTimeout(() => {
          this.showPhoneWarningPopup = false;
        }, 2000);
      }, 1000);
    },
    onShowTermsWarningPopup() {
      if (warningPopupTimer) clearTimeout(warningPopupTimer);
      warningPopupTimer = setTimeout(() => {
        this.showTermsWarningPopup = true;
        setTimeout(() => {
          this.showTermsWarningPopup = false;
        }, 2000);
      });
    },
    onShowBankWarningPopup() {
      if (warningPopupTimer) clearTimeout(warningPopupTimer);
      warningPopupTimer = setTimeout(() => {
        this.showBankWarningPopup = true;
        const bankLocation = document.getElementById("orderPaymentBank")
          .offsetTop;
        window.scrollTo({ top: bankLocation, behavior: "smooth" });
        setTimeout(() => {
          this.showBankWarningPopup = false;
        }, 2000);
      });
    },

    onValidate() {
      this.$store.commit("validateName");
      this.$store.commit("validatePhone");
      this.$store.commit("validateEmail");
      this.$store.commit("validateDeliveryName");
      this.$store.commit("validateDeliveryUserName");
      this.$store.commit("validateDeliveryPhoneNumber");
      this.$store.commit("validateAddress");

      if (!this.$store.state.agreeTerms) {
        this.$store.commit("updateAgreeTermsError", true);
        this.onShowTermsWarningPopup();
      } else this.$store.commit("updateAgreeTermsError", false);
    },

    onPay() {
      this.onValidate();

      if (this.$store.state.showNameError) {
        document.getElementById("userName").focus();
        return;
      } else if (this.$store.state.showEmailError) {
        document.getElementById("userEmail").focus();
        return;
      } else if (this.$store.state.showPhoneNumberError) {
        document.getElementById("userPhoneNumber").focus();
        return;
      } else if (this.$store.state.showDeliveryUserNameError) {
        document.getElementById("deliveryUserName").focus();
        return;
      } else if (this.$store.state.showDeliveryPhoneNumberError) {
        document.getElementById("deliveryPhoneNumber").focus();
        return;
      } else if (this.$store.state.showAddressError) {
        document.getElementById("detailAddress").focus();
        return;
      } else if (this.$store.state.showAgreeTermsError) {
        const termsLocation = document.getElementById("orderSectionTerms")
          .offsetTop;
        window.scrollTo({ top: termsLocation, behavior: "smooth" });
        return;
      }

      if (this.$store.state.paymentType === "bank") {
        const _bankInfo = this.$store.state.paymentBankInfo;
        if (_bankInfo.paymentUserName === "") {
          this.onShowBankWarningPopup();
          return;
        }

        // 현금영수증
        if (_bankInfo.paymentReceiptType === "cashReceipt") {
          if (
            _bankInfo.paymentCashReceiptType === "" ||
            _bankInfo.paymentCashNumber === ""
          ) {
            this.onShowBankWarningPopup();
            return;
          }
        }
        // 세금계산서
        if (_bankInfo.paymentReceiptType === "taxReceipt") {
          if (
            _bankInfo.paymentCompanyName === "" ||
            _bankInfo.paymentCompanyNumber === "" ||
            _bankInfo.paymentCompanyCEO === "" ||
            _bankInfo.paymentCompanyBusinessType === "" ||
            _bankInfo.paymentCompanyBusinessItem === "" ||
            _bankInfo.paymentCompanyPostalCode === "" ||
            _bankInfo.paymentCompanyMainAddress === "" ||
            _bankInfo.paymentCompanyDetailAddress === ""
          ) {
            this.onShowBankWarningPopup();
            return;
          }
        }
      }

      let email;
      if (this.$store.state.emailLabelText === "직접입력")
        email = this.$store.state.email + "@" + this.$store.state.emailSelfText;
      else
        email =
          this.$store.state.email + "@" + this.$store.state.emailLabelText;

      let deliveryMessage = this.$store.state.deliveryLabelText;
      if (this.$store.state.deliveryLabelText === "직접입력")
        deliveryMessage = this.$store.state.deliverySelfMessage;

      const _payData = {
        name: this.$store.state.name,
        phoneNumber: this.$store.state.phoneNumber,
        email,
        hasUserInfo: this.$store.state.hasUserInfo,
        hasDeliveryInfo: this.$store.state.hasDeliveryInfo,
        postalCode: this.$store.state.postalCode,
        mainAddress: this.$store.state.mainAddress,
        detailAddress: this.$store.state.detailAddress,
        deliverySno: this.$store.state.deliverySno,
        deliveryName: this.$store.state.deliveryName,
        deliveryUserName: this.$store.state.deliveryUserName,
        deliveryPhoneNumber: this.$store.state.deliveryPhoneNumber,
        deliveryMessage,
        checkAddDeliveryInfo: this.$store.state.checkAddDeliveryInfo,
        checkDefaultDeliveryInfo: this.$store.state.checkDefaultDeliveryInfo,
        usingPoint: Number(this.$store.state.usingPoint),
        paymentType: this.$store.state.paymentType,
        paymentBankInfo: this.$store.state.paymentBankInfo,
        agreeTerms: this.$store.state.agreeTerms,
        newDeliveryList: this.$store.state.newDeliveryList,
      };
      this.onPayItems(_payData);
    },
  },
};
</script>

<style></style>
