<template>
  <client-only>
  <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">
      <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"
      >
        {{ $t("Purchaser Info") }}
      </h3>
      <div class="element content-status xl:tw-ml-[20px]">
        <span
          v-if="purchaserValidation == 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]">
            <button
              :class="[
                'tw-transition',
                'tw-btn-md',
                'tw-border',
                'tw-border-solid',
                'tw-border-neutrals-300',
                'tw-px-[30px]',
                ' tw-py-[9.5px]',
                ' tw-rounded-2xl',
                infoType == 'Company'
                  ? 'tw-bg-neutrals-800 tw-text-neutrals-0'
                  : 'tw-bg-neutrals-0 tw-text-neutrals-300',
              ]"
              @click="$emit('type', 'Company')"
            >
              {{ $t('Company')}}
            </button>
            <button
              :class="[
                'tw-transition',
                'tw-btn-md',
                'tw-border',
                'tw-border-solid',
                'tw-border-neutrals-300',
                'tw-px-[30px]',
                ' tw-py-[9.5px]',
                ' tw-rounded-2xl',
                infoType == 'Individual'
                  ? 'tw-bg-neutrals-800 tw-text-neutrals-0'
                  : 'tw-bg-neutrals-0 tw-text-neutrals-300',
              ]"
              @click="$emit('type', 'Individual')"
            >
            {{ $t('Individual')}}
            </button>
          </div>
          <div v-show="infoType == 'Individual'">
            <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]"
            >
              <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>
              <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>
              <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>
              <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]">
                <!-- <vue-country-code
                  class="d-none"
                  @onSelect="onSelect"
                  v-model="userData.country_code"
                  :countryCode.sync="userData.country_code"
                  enabldCountryCode
                  :enabledFlags="false"
                ></vue-country-code> -->
                <elementCountryCodeSelect :select="{
                  required: true,
                }" :userCodeSelect="userData.phone_code" :validation="validation.phone_code" @returnCode = "getReturnCode"></elementCountryCodeSelect>
                <!-- <vue-phone-number-input
                  color="#e5e5e5"
                  :border-radius="5"
                  error-color="#ef5a5a"
                  valid-color="#e5e5e5"
                  :error="error"
                  required
                  no-flags
                  no-example
                  :validation="validation.phone_number"
                  v-model="userData.phone_number"
                ></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>
              <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 class="element md:tw-col-span-2 tw-mt-[30px]">
                <elementCheckBox
                  :input="{
                    id: 'SaveInfo',
                    label: 'Update personal info in your account',
                  }"
                  @update="updatePersonalInfo = $event"
                ></elementCheckBox>
              </div> -->
            </div>
          </div>
          <div v-show="infoType == 'Company'">
            <div
              class="element element-form tw-grid tw-grid-cols-1 tw-gap-y-[20px]"
            >
              <div
                class="element element-button-group tw-flex-wrap tw-mx-[8px]"
              > 
                <Company ref="ref_company" :countryOptions="countryOptions"></Company>
                <!-- <button
                  v-for="(item, index) in userCompanyList"
                  :key="index"
                  :class="[
                    'tw-transition',
                    'tw-btn-md',
                    'tw-text-[14px]',
                    'tw-leading-[18px]',
                    'tw-text-complementary-1',
                    'tw-bg-neutrals-0',
                    'tw-px-[12px]',
                    'tw-py-[11px]',
                    'tw-mx-[8px]',
                    'tw-mb-[16px]',
                    'tw-rounded-2xl',
                    'tw-border tw-border-solid',
                    'tw-bg-complementary-3',
                    activeLabel == index + 1
                      ? 'tw-border-complementary-1 tw-bg-complementary-1/20'
                      : 'tw-border-transparent',
                  ]"
                  @click="onLabelClick(index + 1, item)"
                >
                  {{ item.company_name }}
                </button>
                <button
                  class="btn-add-icon tw-transition tw-btn-md tw-text-[14px] tw-leading-[18px] tw-text-complementary-1 tw-bg-complementary-3 tw-pr-[12px] tw-pl-[36px] tw-py-[11px] tw-mx-[8px] tw-mb-[16px] tw-rounded-[10px]"
                  @click="$modal.show('add-modal')"
                >
                  {{ $t("Add") }}
                </button> -->
              </div>
              <!-- <div class="company-info-list">
                <template v-for="(item, index) in userCompanyList">
                  <div
                    :key="index"
                    v-if="index + 1 === activeLabel"
                    class="tw-grid tw-grid-cols-1 tw-gap-y-[16px]"
                  >
                    <div
                      class="element tw-grid tw-grid-cols-[140px_auto] tw-gap-x-[12px]"
                    >
                      <div class="label t14 tw-font-bold">
                        {{ $t("Company Name") }}
                      </div>
                      <div class="content tw-body-4">
                        {{ item.company_name }}
                      </div>
                    </div>
                    <div
                      class="element tw-grid tw-grid-cols-[140px_auto] tw-gap-x-[12px]"
                    >
                      <div class="label t14 tw-font-bold">
                        {{ $t("Tax Number") }}
                      </div>
                      <div class="content tw-body-4">
                        {{ item.company_tax_no }}
                      </div>
                    </div>
                    <div
                      class="element tw-grid tw-grid-cols-[140px_auto] tw-gap-x-[12px]"
                    >
                      <div class="label t14 tw-font-bold">
                        {{ $t("Street Address") }}
                      </div>
                      <div class="content tw-body-4">
                        {{ item.company_address1 }}{{ item.company_address2 }}
                      </div>
                    </div>
                    <div
                      class="element tw-grid tw-grid-cols-[140px_auto] tw-gap-x-[12px]"
                    >
                      <div class="label t14 tw-font-bold">{{ $t("City") }}</div>
                      <div class="content tw-body-4">
                        {{ item.company_city }}
                      </div>
                    </div>
                    <div
                      class="element tw-grid tw-grid-cols-[140px_auto] tw-gap-x-[12px]"
                    >
                      <div class="label t14 tw-font-bold">
                        {{ $t("State/Province") }}
                      </div>
                      <div class="content tw-body-4">
                        {{ item.company_state }}
                      </div>
                    </div>
                    <div
                      class="element tw-grid tw-grid-cols-[140px_auto] tw-gap-x-[12px]"
                    >
                      <div class="label t14 tw-font-bold">
                        {{ $t("Country") }}
                      </div>
                      <div class="content tw-body-4">
                        {{ item.company_country_name }}
                      </div>
                    </div>
                    <div
                      class="element tw-grid tw-grid-cols-[140px_auto] tw-gap-x-[12px]"
                    >
                      <div class="label t14 tw-font-bold">
                        {{ $t("ZIP/Postal Code") }}
                      </div>
                      <div class="content tw-body-4">
                        {{ item.company_zipcode }}
                      </div>
                    </div>
                    <button
                      class="btn-edit-icon tw-w-[28px] tw-h-[28px]"
                      @click="$modal.show('edit-modal')"
                    ></button>
                  </div>
                </template>
              </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="updatePurchaserInfo(false)"
            >
              {{ $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 elementCheckBox from "@/components/newComponent/form/ElementCheckBox";
import Company from "@/components/service/Company";
import elementCountryCodeSelect from "@/components/newComponent/form/ElementCountryCodeSelect.vue";

import { IsNumber } from "~/utils/common";
import is from "is_js";
export default {
  name: "PurchaserInfo",
  props: {
    // userCompanyList: {
    //   type: Array,
    // },
    countryOptions: {
      type: Array,
    },
    infoType: {
      type: String,
    },
    bookingDetail_Validation: {
      type: Boolean,
    },
  },
  components: {
    elementInput,
    elementSelect,
    elementCheckBox,
    Company,
    elementCountryCodeSelect,
    is,
  },
  data() {
    return {
      show: false,
      disabled: false,
      completed: false,
      userData: {
        first_name: "",
        last_name: "",
        email: "",
        phone_number: "",
        country: "0",
        phone_code: "0",
        UserCompany: [],
      },
      updatePersonalInfo: false,
      userContactList: [],
      activeLabel: 0,
      Individual: {
        FirstName: "",
        LastName: "",
        Email: "",
        phone_code: "0",
        phone_number: "",
        Country: "",
      },
      Company: {
        company_name: "",
        unified_number: "",
        company_address: "",
        city_: "",
        state_or_province: "",
        country: "0",
        postal_code: "",
      },
      validation: {
        first_name: true,
        last_name: true,
        email: true,
        phone_code: true,
        phone_number: true,
        country: true,
      },
      errors: null,
      purchaserValidation: false,
      error: false,
      isValid: false,
      translateOption: {
        countrySelectorLabel: this.$t("country code"),
        phoneNumberLabel: this.$t("phone number"),
      },
    };
  },
  async created() {
    if (this.$auth.loggedIn) {
      await this.getUser();
    }
  },
  watch: {
    // userCompanyList: {
    //   handler: function () {
    //     if (this.userCompanyList) {
    //       this.activeLabel = this.userCompanyList.length > 0 ? 1 : 0;
    //       this.Company.company_name = this.userCompanyList[0].company_name;
    //       this.Company.company_tax_no = this.userCompanyList[0].company_tax_no;
    //       this.Company.company_address1 =
    //         this.userCompanyList[0].company_address1;
    //       this.Company.company_address2 =
    //         this.userCompanyList[0].company_address2;
    //       this.Company.company_city = this.userCompanyList[0].company_city;
    //       this.Company.company_state = this.userCompanyList[0].company_state;
    //       this.Company.company_country =
    //         this.userCompanyList[0].company_country_name;
    //       this.Company.company_zipcode =
    //         this.userCompanyList[0].company_zipcode;
    //     }
    //   },
    // },
    bookingDetail_Validation: {
      handler: function () {
        if (this.bookingDetail_Validation) {
          this.show = true;
        } else {
          this.show = false;
        }
      },
    },
    purchaserValidation: {
      handler: function () {
        if (this.purchaserValidation) {
          this.show = false;
        }
      },
    },
  },
  methods: {
    getReturnCode(code){
      this.userData.phone_code = code;
    },
    getPhoneData(phoneData) {
      // this.userData.phone_code = phoneData.countryCode;
      // //this.userData.PhoneCode = phoneData.countryCallingCode;
      // this.error = phoneData.isValid = true ? false : true;
      this.validation.phone_number = phoneData.isValid;
    },
    // onLabelClick(label, item) {
    //   this.activeLabel = label;
    //   this.$emit("active", this.activeLabel);
    //   this.Company.company_name = item.company_name;
    //   this.Company.company_tax_no = item.company_tax_no;
    //   this.Company.company_address1 = item.company_address1;
    //   this.Company.company_address2 = item.company_address2;
    //   this.Company.company_city = item.company_city;
    //   this.Company.company_state = item.company_state;
    //   this.Company.company_country = item.company_country_name;
    //   this.Company.company_zipcode = item.company_zipcode;
    // },
    async getUser() {
      await this.$axios
        .get(`/trending/api/Onsite/MemberInfo`)
        .then((response) => {
          if(response && response.data && response.data.DATA && response.data.DATA.rel){
            let data = response.data.DATA.rel
            if(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;
              }
            }
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    updateIndividual() {
      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);
        });
    },
    updateCompany() {
      let patchData = this.$refs.ref_company.getFormData();
      if(patchData.company_name=="" && patchData.unified_number=="" && patchData.city_ ==""
      && patchData.company_address =="" && patchData.state_or_province=="" && (patchData.country=="" || patchData.country=="0") && patchData.postal_code==""){
        return false;
      }
      let params = {
        CompanyName: patchData.company_name,
        TaxNumber: patchData.unified_number,
        CityName: patchData.city_,
        Street1: patchData.company_address,
        StateName: patchData.state_or_province,
        CountryID: patchData.country,
        ZipCode: patchData.postal_code,
      }
      this.$axios
        .post(
          `/trending/api/Onsite/Company`,
          params
        )
        .then((result) => {
          //console.log(result);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    updatePurchaserInfo(isUpdate) {
      switch (this.infoType) {
        case "Individual":
          this.$emit("type", "Individual");
          if(this.updatePersonalInfo){   //有勾要一併調整會員資訊
              this.validators();
              //console.log(this.validators());
              if (this.validators()) {
                // this.$emit("type", "Individual");
                this.$emit("individual", this.userData);
                this.purchaserValidation = true;
                this.$emit("purchaserInfo_validation", this.purchaserValidation); 
              } else {
                this.purchaserValidation = false;
                this.$emit("purchaserInfo_validation", this.purchaserValidation);
            }
          }else{   //沒勾要一併調整會員資訊
            this.validators();
            if(this.validators()){
              this.$emit("individual", this.userData);
              this.purchaserValidation = true;
              this.$emit("purchaserInfo_validation", this.purchaserValidation);
            }
          }
          break;
        case "Company":
          this.$emit("type", "Company");
          this.$refs.ref_company.validators();
          if(this.$refs.ref_company.validators()){
            this.Company = this.$refs.ref_company.getFormData();
            this.$emit("company", this.Company);
            this.purchaserValidation = true;
            this.$emit("purchaserInfo_validation", this.purchaserValidation);
          }
          break;
      }
      
      // if(isUpdate){
      //   if(this.updatePersonalInfo){
      //     if (this.validators()) {
      //       this.updateIndividual();
      //     }
      //   }
      //   if (this.$refs.ref_company.validators()) {
      //     this.updateCompany();
      //   }

      // }
      
    },
    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_code) ||
        this.userData.phone_code == '0'
      ) {
        this.validation.phone_code = false;
      } else {
        this.validation.phone_code = 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.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;
      }
    },
    onSelect(data){
      // debugger
      // this.userData.country_code = data.dialCode;
    }
  },
};
</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>