<template>
  <div>
    <div
      class="order-section"
      :style="{ marginBottom: !hasUserInfo || showUserInfo ? '' : '0px' }"
    >
      <div
        style="
          display: flex;
          justify-content: space-between;
          align-items: center;
        "
      >
        <h1 class="order-title-text">주문자</h1>
        <div
          v-if="hasUserInfo"
          style="margin-bottom: 18px"
          @click="onShowUserInfo"
        >
          <span class="order-input-label">{{ name }} {{ phoneNumber }}</span>
          <img
            src="https://nosearch.com/static/images/arrow_dark_grey_right.png"
            style="width: 8px; margin-left: 15px"
            :style="{
              transform: showUserInfo ? 'rotate(270deg)' : 'rotate(90deg)',
            }"
          />
        </div>
      </div>
      <div
        v-if="!hasUserInfo || showUserInfo"
        class="order-grid"
        style="grid-template-rows: 1fr auto 1fr"
      >
        <label
          class="order-input-label"
          :style="{ color: showNameError ? '#FF6861' : '#404040' }"
          for="userName"
          >이름</label
        >
        <div>
          <input
            class="order-input-form"
            :style="{
              border: showNameError ? '1px solid #FF6861' : '1px solid #e5e5e5',
            }"
            id="userName"
            type="text"
            placeholder="이름"
            maxlength="20"
            v-model="name"
          />
          <div v-if="showNameError" class="order-warning-text">
            이름을 입력해주세요
          </div>
        </div>
        <label
          style="margin-top: 20px"
          :style="{ color: showEmailError ? '#FF6861' : '#404040' }"
          class="order-input-label"
          for="userEmail"
          >이메일</label
        >
        <div style="margin: 10px 0">
          <div class="order-input-wrapper" style="margin-bottom: 7px">
            <input
              class="order-input-form"
              :style="{
                border: showEmailError
                  ? '1px solid #FF6861'
                  : '1px solid #e5e5e5',
              }"
              id="userEmail"
              type="text"
              placeholder="이메일"
              v-model="email"
            />
            <span
              class="order-input-label"
              style="font-weight: 700; margin: 0 15px; width: 15px"
              >@</span
            >
          </div>
          <div
            class="order-select"
            :class="{ active: openEmailOption }"
            :style="{ marginBottom: openEmailOption ? '350px' : '0px' }"
            @click="onClickEmailSelect"
          >
            <button
              class="order-select-label"
              :style="{
                border: showEmailError
                  ? '1px solid #FF6861'
                  : '1px solid #e5e5e5',
              }"
            >
              {{ emailLabelText }}
            </button>
            <ul
              class="order-select-option-list"
              :style="{ maxHeight: openEmailOption ? '500px' : '0px' }"
            >
              <li
                class="order-select-option-item"
                v-for="(option, index) in emailOptions"
                :key="option.index"
                @click="onClickEmailOption(option)"
                :style="{ paddingTop: index === 0 ? '32px' : '' }"
              >
                {{ option }}
              </li>
            </ul>
          </div>
          <input
            v-if="emailLabelText === '직접입력'"
            class="order-input-form"
            :style="{
              border: showEmailError
                ? '1px solid #FF6861'
                : '1px solid #e5e5e5',
            }"
            style="margin-top: 8px"
            type="text"
            placeholder="이메일을 직접 입력해주세요"
            v-model="emailSelfText"
          />
          <div v-if="showEmailError" class="order-warning-text">
            이메일을 입력해주세요
          </div>
        </div>
        <label
          style="margin-top: 10px"
          :style="{ color: showPhoneNumberError ? '#FF6861' : '#404040' }"
          class="order-input-label"
          for="userPhoneNumber"
          >연락처</label
        >
        <div>
          <input
            class="order-input-form"
            :style="{
              border: showPhoneNumberError
                ? '1px solid #FF6861'
                : '1px solid #e5e5e5',
            }"
            id="userPhoneNumber"
            type="text"
            placeholder="연락처"
            maxlength="20"
            v-model="phoneNumber"
          />
          <div v-if="showPhoneNumberError" class="order-warning-text">
            연락처를 입력해주세요
          </div>
        </div>
      </div>
    </div>
    <div class="r-bar"></div>
    <div class="order-section">
      <div
        style="
          display: flex;
          justify-content: space-between;
          align-items: center;
        "
      >
        <h1 class="order-title-text">배송지</h1>
        <div
          v-if="!hasUserInfo"
          class="order-checkbox"
          style="margin: 0 0 18px 0; width: 140px"
        >
          <input
            type="checkbox"
            v-model="checkSameInfo"
            id="orderInfoCheckbox"
            @click="onSameUserInfo"
          />
          <label
            for="orderInfoCheckbox"
            class="order-input-label"
            style="margin: 0"
          >
            <div class="order-checkbox-img">주문자 정보와 동일</div>
          </label>
        </div>
        <div
          v-else
          class="order-blue-text"
          style="margin-bottom: 18px"
          @click="onShowDeliveryPage"
        >
          변경
        </div>
      </div>
      <div class="order-grid" style="grid-template-rows: 1fr 1fr auto">
        <label
          style="margin-bottom: 10px"
          :style="{ color: showDeliveryUserNameError ? '#FF6861' : '#404040' }"
          class="order-input-label"
          for="deliveryUserName"
          >받는 사람</label
        >
        <div>
          <input
            :style="{
              border: showDeliveryUserNameError
                ? '1px solid #FF6861'
                : '1px solid #e5e5e5',
              marginBottom: showDeliveryUserNameError ? '0px' : '10px',
            }"
            class="order-input-form"
            id="deliveryUserName"
            type="text"
            placeholder="이름"
            maxlength="20"
            v-model="deliveryUserName"
          />
          <div v-if="showDeliveryUserNameError" class="order-warning-text">
            받는 사람을 입력해주세요
          </div>
        </div>
        <label
          style="margin-top: 10px"
          :style="{
            color: showDeliveryPhoneNumberError ? '#FF6861' : '#404040',
          }"
          class="order-input-label"
          for="deliveryPhoneNumber"
          >연락처</label
        >
        <div>
          <input
            class="order-input-form"
            :style="{
              border: showDeliveryPhoneNumberError
                ? '1px solid #FF6861'
                : '1px solid #e5e5e5',
            }"
            id="deliveryPhoneNumber"
            type="text"
            placeholder="연락처"
            maxlength="20"
            v-model="deliveryPhoneNumber"
          />
          <div v-if="showDeliveryPhoneNumberError" class="order-warning-text">
            연락처를 입력해주세요
          </div>
        </div>
        <label
          class="order-input-label"
          :style="{
            color: showAddressError ? '#FF6861' : '#404040',
          }"
          for="userAddress"
          >주소</label
        >
        <div>
          <div style="display: flex; align-items: center">
            <button class="order-address-button" @click="onOpenDaumPostcode">
              주소 찾기
            </button>
            <input
              type="text"
              id="postCode"
              :style="{
                border: showAddressError
                  ? '1px solid #FF6861'
                  : '1px solid #e5e5e5',
              }"
              style="background-color: #f5f6f9"
              class="order-input-form order-search-post-code"
              v-model="postalCode"
              disabled
            />
          </div>
          <input
            type="text"
            id="address"
            class="order-input-form order-search-address"
            :style="{
              border: showAddressError
                ? '1px solid #FF6861'
                : '1px solid #e5e5e5',
            }"
            style="background-color: #f5f6f9; margin: 8px 0"
            v-model="mainAddress"
            disabled
          />
          <input
            type="text"
            id="detailAddress"
            class="order-input-form order-search-detail-address"
            :style="{
              border: showAddressError
                ? '1px solid #FF6861'
                : '1px solid #e5e5e5',
            }"
            placeholder="상세 주소 입력"
            v-model="detailAddress"
          />
          <div
            ref="wrap"
            class="order-search-address-wrap"
            style="padding-top: 40px"
          >
            <img
              src="//t1.daumcdn.net/postcode/resource/images/close.png"
              id="btnFoldWrap"
              class="order-search-address-close-img"
              @click="onFoldDaumPostcode"
              alt="접기 버튼"
            />
          </div>
          <div>
            <div v-if="showAddressError" class="order-warning-text">
              주소를 입력해주세요
            </div>
          </div>
          <div
            v-if="!addNewDeliveryInfo"
            class="order-checkbox"
            style="justify-content: flex-start"
          >
            <input
              v-if="hasUserInfo"
              type="checkbox"
              v-model="checkDefaultDeliveryInfo"
              id="orderDeliveryCheckbox"
            />
            <input
              v-else
              type="checkbox"
              v-model="checkAddDeliveryInfo"
              id="orderDeliveryCheckbox"
            />
            <label
              for="orderDeliveryCheckbox"
              class="order-input-label"
              style="margin: 0; justify-content: flex-start"
              ><div class="order-checkbox-img">기본 배송지로 저장</div></label
            >
          </div>
        </div>
      </div>
      <div
        class="order-select"
        :class="{ active: openDeliveryOption }"
        style="margin-top: 18px"
        :style="{ marginBottom: openDeliveryOption ? '250px' : '0px' }"
        @click="onClickDeliverySelect"
      >
        <button class="order-select-label">
          {{ deliveryLabelText }}
        </button>
        <ul class="order-select-option-list">
          <li
            class="order-select-option-item"
            v-for="(option, index) in deliveryOptions"
            :key="option.index"
            @click="onClickDeliveryOption(option)"
            :style="{ paddingTop: index === 0 ? '32px' : '' }"
          >
            {{ option }}
          </li>
        </ul>
      </div>
      <input
        v-if="deliveryLabelText === '직접입력'"
        class="order-input-form"
        style="margin-top: 8px"
        type="text"
        placeholder="배송시 요청사항을 입력해주세요"
        v-model="deliverySelfMessage"
      />
    </div>
  </div>
</template>

<script>
export default {
  name: "orderUserInfo",
  props: {
    userInfo: Object,
    deliveryList: Array,
    onShowDeliveryPage: Function,
    onShowPhoneWarningPopup: Function,
  },
  data() {
    return {
      showUserInfo: false,
      checkSameInfo: false,
      openEmailOption: false,
      emailOptions: [
        "naver.com",
        "gmail.com",
        "hanmail.net",
        "daum.net",
        "nate.com",
        "hotmail.com",
        "icloud.com",
        "직접입력",
      ],
      openDeliveryOption: false,
      deliveryOptions: [
        "부재시 문 앞에 놓아주세요",
        "배송 전에 미리 연락주세요",
        "부재시 경비실에 맡겨주세요",
        "부재시 연락주세요",
        "직접입력",
      ],
    };
  },
  created: function () {
    // 주문자 정보가 있는 경우
    if (!this.userInfo) return;
    if (
      this.userInfo.name !== "" &&
      this.userInfo.phoneNumber !== "" &&
      this.userInfo.email !== ""
    )
      this.hasUserInfo = true;
    if (this.hasUserInfo) {
      this.name = this.userInfo.name;
      this.phoneNumber = this.userInfo.phoneNumber
        .replaceAll("-", "")
        .replace(/[^0-9]/, "")
        .replace(/^(\d{2,3})(\d{3,4})(\d{4})$/, `$1-$2-$3`);

      const _email = this.userInfo.email.split("@");
      this.email = _email[0];
      if (this.emailOptions.indexOf(_email[1]) > 0) {
        this.emailLabelText = _email[1];
      } else {
        this.emailSelfText = _email[1];
        this.emailLabelText = "직접입력";
      }
    }
  },
  watch: {
    name: function () {
      this.$store.commit("validateName");
    },
    phoneNumber: function () {
      this.$store.commit("validatePhone");
      if (this.phoneNumber !== "") this.onShowPhoneWarningPopup();
    },
    email: function () {
      this.$store.commit("validateEmail");
    },
    emailLabelText: function () {
      this.$store.commit("validateEmail");
    },
    emailSelfText: function () {
      this.$store.commit("validateEmail");
    },
    deliveryName: function () {
      this.$store.commit("validateDeliveryName");
    },
    deliveryUserName: function () {
      this.$store.commit("validateDeliveryUserName");
    },
    deliveryPhoneNumber: function () {
      this.$store.commit("validateDeliveryPhoneNumber");
    },
    postalCode: function () {
      this.$store.commit("validateAddress");
    },
    mainAddress: function () {
      this.$store.commit("validateAddress");
    },
    detailAddress: function () {
      this.$store.commit("validateAddress");
    },
  },
  methods: {
    onShowUserInfo() {
      this.showUserInfo = !this.showUserInfo;
    },
    onSameUserInfo() {
      this.checkSameInfo = !this.checkSameInfo;
      if (this.checkSameInfo) {
        this.$store.commit("updateUseDefaultDeliveryInfo", false);
        this.deliveryUserName = this.name;
        this.deliveryPhoneNumber = this.phoneNumber;
      } else {
        this.deliveryUserName = "";
        this.deliveryPhoneNumber = "";
      }
    },
    onClickEmailOption(option) {
      this.emailLabelText = option;
    },
    onClickEmailSelect() {
      this.openEmailOption = !this.openEmailOption;
    },

    onClickDeliveryOption(option) {
      this.deliveryLabelText = option;
    },
    onClickDeliverySelect() {
      this.openDeliveryOption = !this.openDeliveryOption;
    },

    // 주소 찾기
    onOpenDaumPostcode() {
      const elementWrap = this.$refs.wrap;
      const currentScroll = Math.max(
        document.body.scrollTop,
        document.documentElement.scrollTop
      );
      new window.daum.Postcode({
        oncomplete: (data) => {
          let addr = ""; //
          if (data.userSelectedType === "R") {
            addr = data.roadAddress;
          } else {
            addr = data.jibunAddress;
          }

          this.$store.commit("updateUseDefaultDeliveryInfo", false);
          this.postalCode = data.zonecode;
          this.mainAddress = addr;

          document.getElementById("detailAddress").focus();

          elementWrap.style.display = "none";
          document.body.scrollTop = currentScroll;
        },
        width: "100%",
        height: "100vh",
      }).embed(elementWrap);
      elementWrap.style.display = "block";
    },
    onFoldDaumPostcode() {
      const elementWrap = this.$refs.wrap;
      elementWrap.style.display = "none";
    },
  },
  computed: {
    getDefaultDeliveryData: function () {
      let _data = {};
      if (this.deliveryList && this.deliveryList.length) {
        this.deliveryList.forEach((_deliveryList) => {
          if (_deliveryList.defaultFl !== "y") return;

          this.$store.commit("updateCheckDefaultDeliveryInfo", true);
          this.$store.commit("updateHasDeliveryInfo", true);
          this.$store.commit("updateDeliverySno", _deliveryList.sno);
          _data = {
            hasDeliveryInfo: true,
            defaultAddress: true,
            postalCode: _deliveryList.shippingZonecode,
            mainAddress: _deliveryList.shippingAddress,
            detailAddress: _deliveryList.shippingAddressSub,
            deliveryName: _deliveryList.shippingTitle,
            deliveryUserName: _deliveryList.shippingName,
            deliveryPhoneNumber: _deliveryList.shippingCellPhone.replaceAll(
              "-",
              ""
            ),
          };
        });
      }
      return _data;
    },
    name: {
      get() {
        return this.$store.state.name;
      },
      set(value) {
        this.$store.commit("updateName", value);
      },
    },
    phoneNumber: {
      get() {
        return this.$store.state.phoneNumber;
      },
      set(value) {
        this.$store.commit("updatePhoneNumber", value);
      },
    },
    email: {
      get() {
        return this.$store.state.email;
      },
      set(value) {
        this.$store.commit("updateEmail", value);
      },
    },
    emailSelfText: {
      get() {
        return this.$store.state.emailSelfText;
      },
      set(value) {
        this.$store.commit("updateEmailSelfText", value);
      },
    },
    emailLabelText: {
      get() {
        return this.$store.state.emailLabelText;
      },
      set(value) {
        this.$store.commit("updateEmailLabelText", value);
      },
    },
    hasUserInfo: {
      get() {
        return this.$store.state.hasUserInfo;
      },
      set(value) {
        this.$store.commit("updateHasUserInfo", value);
      },
    },
    hasDeliveryInfo: {
      get() {
        return this.$store.state.hasDeliveryInfo;
      },
      set(value) {
        this.$store.commit("updateHasDeliveryInfo", value);
      },
    },
    checkAddDeliveryInfo: {
      get() {
        return this.$store.state.checkAddDeliveryInfo;
      },
      set(value) {
        this.$store.commit("updateCheckAddDeliveryInfo", value);
      },
    },
    checkDefaultDeliveryInfo: {
      get() {
        return this.$store.state.checkDefaultDeliveryInfo;
      },
      set(value) {
        this.$store.commit("updateCheckDefaultDeliveryInfo", value);
      },
    },
    addNewDeliveryInfo: {
      get() {
        return this.$store.state.addNewDeliveryInfo;
      },
    },

    defaultAddress: {
      get() {
        if (
          Object.keys(this.getDefaultDeliveryData).length &&
          this.$store.state.useDefaultDeliveryInfo
        ) {
          const _data = this.getDefaultDeliveryData.defaultAddress;
          this.$store.commit("updateDefaultAddress", _data);
          return _data;
        } else return this.$store.state.defaultAddress;
      },
      set(value) {
        this.$store.commit("updateDefaultAddress", value);
      },
    },
    deliveryName: {
      get() {
        if (
          Object.keys(this.getDefaultDeliveryData).length &&
          this.$store.state.useDefaultDeliveryInfo
        ) {
          const _data = this.getDefaultDeliveryData.deliveryName;
          this.$store.commit("updateDeliveryName", _data);
          return _data;
        } else return this.$store.state.deliveryName;
      },
      set(value) {
        this.$store.commit("updateDeliveryName", value);
      },
    },
    deliveryUserName: {
      get() {
        if (
          Object.keys(this.getDefaultDeliveryData).length &&
          this.$store.state.useDefaultDeliveryInfo
        ) {
          const _data = this.getDefaultDeliveryData.deliveryUserName;
          this.$store.commit("updateDeliveryUserName", _data);
          return _data;
        } else return this.$store.state.deliveryUserName;
      },
      set(value) {
        this.$store.commit("updateDeliveryUserName", value);
      },
    },
    deliveryPhoneNumber: {
      get() {
        if (
          Object.keys(this.getDefaultDeliveryData).length &&
          this.$store.state.useDefaultDeliveryInfo
        ) {
          const __data = this.getDefaultDeliveryData.deliveryPhoneNumber;
          const _data = __data
            .replaceAll("-", "")
            .replace(/[^0-9]/, "")
            .replace(/^(\d{2,3})(\d{3,4})(\d{4})$/, `$1-$2-$3`);

          this.$store.commit("updateDeliveryPhoneNumber", _data);
          return _data;
        } else return this.$store.state.deliveryPhoneNumber;
      },
      set(value) {
        this.$store.commit("updateDeliveryPhoneNumber", value);
      },
    },
    postalCode: {
      get() {
        if (
          Object.keys(this.getDefaultDeliveryData).length &&
          this.$store.state.useDefaultDeliveryInfo
        ) {
          const _data = this.getDefaultDeliveryData.postalCode;
          this.$store.commit("updatePostalCode", _data);
          return _data;
        } else return this.$store.state.postalCode;
      },
      set(value) {
        this.$store.commit("updatePostalCode", value);
      },
    },
    mainAddress: {
      get() {
        if (
          Object.keys(this.getDefaultDeliveryData).length &&
          this.$store.state.useDefaultDeliveryInfo
        ) {
          const _data = this.getDefaultDeliveryData.mainAddress;
          this.$store.commit("updateMainAddress", _data);
          return _data;
        } else return this.$store.state.mainAddress;
      },
      set(value) {
        this.$store.commit("updateMainAddress", value);
      },
    },
    detailAddress: {
      get() {
        if (
          Object.keys(this.getDefaultDeliveryData).length &&
          this.$store.state.useDefaultDeliveryInfo
        ) {
          const _data = this.getDefaultDeliveryData.detailAddress;
          this.$store.commit("updateDetailAddress", _data);
          return _data;
        } else return this.$store.state.detailAddress;
      },
      set(value) {
        this.$store.commit("updateDetailAddress", value);
      },
    },
    deliveryLabelText: {
      get() {
        return this.$store.state.deliveryLabelText;
      },
      set(value) {
        this.$store.commit("updateDeliveryLabelText", value);
      },
    },
    deliverySelfMessage: {
      get() {
        return this.$store.state.deliverySelfMessage;
      },
      set(value) {
        this.$store.commit("updateDeliverySelfMessage", value);
      },
    },
    // 에러
    showNameError: {
      get() {
        return this.$store.state.showNameError;
      },
    },
    showPhoneNumberError: {
      get() {
        return this.$store.state.showPhoneNumberError;
      },
    },
    showEmailError: {
      get() {
        return this.$store.state.showEmailError;
      },
    },
    showDeliveryNameError: {
      get() {
        return this.$store.state.showDeliveryNameError;
      },
    },
    showDeliveryUserNameError: {
      get() {
        return this.$store.state.showDeliveryUserNameError;
      },
    },
    showDeliveryPhoneNumberError: {
      get() {
        return this.$store.state.showDeliveryPhoneNumberError;
      },
    },
    showAddressError: {
      get() {
        return this.$store.state.showAddressError;
      },
    },
  },
};
</script>

<style></style>
