<template>
  <client-only>
    <!-- 狀態1 -->
    <div
      class="purchaser-info tw-p-5 tw-mb-[20px] tw-bg-white tw-rounded-xl"
    >
      <div class="tw-flex tw-flex-row tw-justify-between tw-items-center">
        <!-- <template> -->
          <h3
            v-if="show == true"
            :class="[
              'collapse',
              't16',
              'tw-relative',
              'tw-cursor-pointer',
              'xl:tw-text-[18px]',
              show ? 'show' : 'hide',
              disabled ? 'disabled' : '',
              disabled ? 'tw-text-neutrals-300' : 'tw-text-black',
            ]"
            @click="show = !show"
          >
            {{ $t("Ordering person") }}
          </h3>
        <!-- </template> -->

        <div v-else>
          <h3
            :class="[
              'collapse',
              't16',
              'tw-relative',
              'tw-cursor-pointer',
              'xl:tw-text-[18px]',
              show ? 'show' : 'hide',
              disabled ? 'disabled' : '',
              disabled ? 'tw-text-neutrals-300' : 'tw-text-black',
            ]"
            @click="show = !show"
          >{{ userData.first_name }} {{ userData.last_name }}</h3>
        
          <div style="margin-left: 55px;">
            <div>{{ '電子信箱 : ' + userData.email }}</div>
            <div>{{ '聯絡電話 : '  + userData.phone_code + " " + userData.phone_number }}</div>
          </div>
        </div>
        <div class="element content-status xl:tw-ml-[20px]">
          <span
            v-if="orderingPersonValidation == true"
            class="status-check-icon tw-inline-block tw-w-[30px] tw-h-[30px]"
          ></span>
        </div>
      </div>


      <Transition name="bounce">
        <div v-show="show">
          <div class="tw-mt-[32px] md:tw-ml-[60px]">
            <div class="element element-tabs tw-mb-[20px]">
              
              <div
              class="element element-form tw-grid tw-grid-cols-1 tw-gap-[10px] md:tw-grid-cols-2 md:tw-gap-x-[60px] md:tw-gap-y-[20px] md:tw-max-w-[580px]"
              >

                <!-- first name -->
                <div class="element">
                  <elementInput
                    :input="{
                      id: 'FirstName',
                      label: 'First Name',
                      required: true,
                      type: 'text',
                    }"
                    :default="userData.first_name"
                    :validation="validation.first_name"
                    @change="userData.first_name = $event"
                  ></elementInput>
                </div>

                <!-- last name -->
                <div class="element">
                  <elementInput
                    :input="{
                      id: 'LastName',
                      label: 'Last Name',
                      required: true,
                      type: 'text',
                    }"
                    :default="userData.last_name"
                    :validation="validation.last_name"
                    @change="userData.last_name = $event"
                  ></elementInput>
                </div>

                <!-- Email -->
                <div class="element">
                  <elementInput
                    :input="{
                      id: 'ContactEmail',
                      label: 'Contact Email',
                      required: true,
                      type: 'email',
                    }"
                    :default="userData.email"
                    :validation="validation.email"
                    @change="userData.email = $event"
                  >
                  </elementInput>
                </div>

                <!-- phoneNumber -->
                <div class="element">
                  <label class="tw-block tw-mb-[10px]"
                    ><span
                      >{{ $t("Phone") }}<span class="required">*</span></span
                    ></label
                >
                  <div class="tw-grid tw-grid-cols-[120px_auto] tw-gap-[5px]">
                    <elementCountryCodeSelect :select="{
                      required: true,
                      }" :userCodeSelect="userData.phone_code" :validation="validation.phone_code" @returnCode = "getReturnCode"
                    >
                    </elementCountryCodeSelect>
                    <vue-phone-number-input v-model="userData.phone_number" :validation="validation.phone_number" color="#E5e5e5" error-color="#ef5a5a"
                        valid-color="#e5e5e5"
                        :error="error" :border-radius="5"
                      no-flags :no-country-selector="true" no-example @update="getPhoneData" :translations="translateOption">
                    </vue-phone-number-input>
                    <!-- <vue-phone-number-input v-model="userData.phone_number" :validation="validation.phone_number" color="#E5e5e5" error-color="#ef5a5a"
                      valid-color="#e5e5e5"
                      :error="error" :border-radius="5"
                      no-flags :no-country-selector="true" no-example @update="getPhoneData" :translations="translateOption">
                    </vue-phone-number-input> -->
                  </div>
                </div>

                <!-- country -->
                <div class="element">
                  <elementSelect
                    :select="{
                      id: 'Country',
                      label: 'Country/Region',
                      required: true,
                    }"
                    :selectList="countryOptions"
                    :default="userData.country"
                    :validation="validation.country"
                    @change="userData.country = $event"
                  ></elementSelect>
                </div>

              </div>

            </div>

            <div class="element tw-mt-[40px] tw-text-right">
              <button
                class="tw-transition tw-btn-md tw-bg-primary-1 tw-px-[30px] tw-py-[9.5px] tw-rounded-2xl hover:tw-bg-primary-2"
                @click="OrderingPersonInfo()"
              >
                {{ $t("Next") }}
              </button>
            </div>
          </div>
        </div>
      </Transition>
    </div>
  </client-only>

</template>

<script>
import elementInput from "@/components/newComponent/form/ElementInput";
import elementSelect from "@/components/newComponent/form/ElementSelect";
import elementCountryCodeSelect from "@/components/newComponent/form/ElementCountryCodeSelect.vue";
import { IsNumber } from "~/utils/common";
import is from "is_js";

export default {
  name: "OrderingPersonInfo",
  props: {
    countryOptions: {
      type: Array,
    },
    infoType: {
      type: String,
    },
  },
  components: {
    elementInput,
    elementSelect,
    elementCountryCodeSelect,
    IsNumber,
    is
  },
  data() {
    return {
      show: true,
      disabled: false,
      updatePersonalInfo: false,
      orderingPersonValidation: false,
      userData: {
        first_name: "",
        last_name: "",
        email: "",
        phone_number: "",
        country: "0",
        phone_code: "0",
        UserCompany: [],
      },
      validation: {
        first_name: true,
        last_name: true,
        email: true,
        phone_code: true,
        phone_number: true,
        country: true,
      },
      translateOption: {
        countrySelectorLabel: this.$t("country code"),
        phoneNumberLabel: this.$t("phone number"),
      },
      error: false,
      value: "0",
    }
  },
  created() {
    this.getUser()
  },
  watch: {
    orderingPersonValidation: {
      handler: function () {
        if(this.show){
          this.orderingPersonValidation = false
        } else {
          this.orderingPersonValidation = true
        }
      }
    }
  },
  methods: {
    async getUser() {
      await this.$axios
      .get(`/trending/api/Onsite/MemberInfo`)
      .then((res) => {

        if(res && res.data && res.data.DATA && res.data.DATA.rel){
          const data = res.data.DATA.rel
          if(data){
            //console.log(JSON.stringify(data));
            this.userData.first_name = data.FirstName;
            this.userData.last_name = data.LastName;
            this.userData.email = data.Email;
            this.userData.phone_number = data.Phone;
            if(data.CountryID == null){
              this.userData.country = "0";
            }else{
              this.userData.country = data.CountryID;
            }
            if(data.PhoneCode == null){
              this.userData.phone_code = "0";
            }else{
              this.userData.phone_code = data.PhoneCode;
            }
          }
        }

      })
    },
    getReturnCode(code){
      this.userData.phone_code = code;
      
    },
    getPhoneData(phoneData) {
      this.validation.phone_number = phoneData.isValid;
    },
    //post 訂購人資料
    postOrderingPerson() {
      const patchData = JSON.parse(JSON.stringify(this.userData));
      let params = {
        FirstName: patchData.first_name,
        LastName: patchData.last_name,
        Email: patchData.email,
        Phone: patchData.phone_number,
        CountryID: patchData.country,
        PhoneCode: patchData.phone_code,
      }
      this.$axios
        .post(
          `/trending/api/Onsite/Member`,
          params
        )
        .then((result) => {
          //console.log(result);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    OrderingPersonInfo() {
      
      if(this.validators()) {
        this.show = false;
        this.orderingPersonValidation = true
        this.$emit('orderingPerson_Validation', this.orderingPersonValidation)
        const personInfo = JSON.parse(JSON.stringify(this.userData));
        //訂購人資訊
        let orderingPersonInfo = {
          FirstName: personInfo.first_name,
          LastName: personInfo.last_name,
          Email: personInfo.email,
          Phone: personInfo.phone_number,
          CountryID: personInfo.country,
          PhoneCode: personInfo.phone_code,
        }
        this.$emit('orderingPersonInfo', orderingPersonInfo);   
      }
    },
    validators() {
      if (is.empty(this.userData.first_name)) {
        this.validation.first_name = false;
      } else {
        this.validation.first_name = true;
      }
      if (is.empty(this.userData.last_name)) {
        this.validation.last_name = false;
      } else {
        this.validation.last_name = true;
      }
      if (is.empty(this.userData.email) || is.not.email(this.userData.email)) {
        this.validation.email = false;
      } else {
        this.validation.email = true;
      }
      if (
        is.empty(this.userData.phone_number) ||
        IsNumber(this.userData.phone_number) == false
      ) {
        this.validation.phone_number = false;
        this.error = true;
      } else {
        this.validation.phone_number = true;
        this.error = false;
      }
      if (
        is.empty(this.userData.phone_code) ||
        this.userData.phone_code == '0'
      ) {
        this.validation.phone_code = false;
      } else {
        this.validation.phone_code = true;
      }
      if (is.empty(this.userData.country) || this.userData.country == "0") {
        this.validation.country = false;
      } else {
        this.validation.country = true;
      }
      this.errors = Object.entries(this.validation).filter(
        (e) => e[1] == false
      );
      if (this.errors.length > 0) {
        this.purchaserValidation = false;
        return false;
      } else {
        return true;
      }
    },
  }
}
</script>

<style lang="scss" scoped>
.collapse {
  &::before {
    content: "";
    display: inline-block;
    position: relative;
    left: 0;
    top: 0;
    background-image: url("~/assets/svg/down-arrow.svg");
    background-repeat: no-repeat;
    background-position: center;
    background-size: 100%;
    width: 16px;
    height: 10px;
    margin-right: 40px;
    transform: rotate(-90deg);
    transition: all 0.2s linear;
  }

  &.disabled {
    pointer-events: none;

    &::before {
      background-image: url("~/assets/svg/down-arrow-disabled.svg");
    }
  }

  &.show {
    &::before {
      transform: rotate(0);
      transition: all 0.2s linear;
    }
  }
}

.btn-add-icon {
  background-image: url("~/assets/svg/plus-blue.svg");
  background-repeat: no-repeat;
  background-position: left 12px center;
  background-size: 16px 16px;
}

.btn-edit-icon {
  background-image: url("~/assets/svg/edit-info.svg");
  background-repeat: no-repeat;
  background-position: center;
  background-size: 100%;
}

.bounce-enter-active {
  animation: bounce-in 0.3s ease-out;
}

.bounce-leave-active {
  animation: bounce-in 0.3s cubic-bezier(1, 0.5, 0.8, 1) reverse;
}

@keyframes bounce-in {
  0% {
    opacity: 0;
    transform: translateY(-10px);
  }

  50% {
    opacity: 0.5;
    transform: translateY(-5px);
  }

  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

.status-check-icon {
  background-image: url("~/assets/svg/status-check.svg");
  background-size: 100%;
  background-repeat: no-repeat;
  background-position: center;
}

:deep(.input-tel__input) {
    height: 44px !important;
    padding-left: 13px !important; 
}

</style>
