<template>
  <div class="contactInfo xl:tw-max-w-[1246px] xl:tw-mx-auto">
    <div class="xl:tw-flex xl:tw-justify-between xl:tw-items-start">
      <userSidebar :userData="userData" :firstName="firstName" :lastName="lastName" class="tw-hidden xl:tw-block">
      </userSidebar>
      <!-- <div class="xl:tw-hidden"></div> -->
      <div class="tw-bg-white xl:tw-p-[30px] xl:tw-rounded-[20px] xl:tw-min-w-[900px] xl:tw-max-w-[900px]">
        <div class="tw-text-[20px] tw-font-bold tw-text-base-primary md:t24 xl:tw-mb-[30px]">
          <two-dots class="tw-mr-[30px]"></two-dots>{{ $t('Contact Info')}}
        </div>
        <div v-if="userContact.length < 1"
          class="tw-flex tw-justify-center tw-mt-[80px] tw-mb-[50px] md:tw-mb-[30px] md:tw-mt-[90px]">
          <div>
            <img :src="contactImg" alt="" class="tw-h-[142px] tw-w-[160px]" />
            <div class="tw-text-center tw-t16">
              {{ $t("No Contact yet ...") }}
            </div>
          </div>
        </div>
        <div v-else class="tw-w-full xl:tw-mb-[40px]">
          <ContactInfoContent :contacts="userContact" @refetch-contact-info="successUpdate"></ContactInfoContent>
        </div>
        <div :class="
          userContact.length < 1
            ? 'tw-flex tw-justify-center tw-mt-[50px] tw-mb-[36px] md:tw-mt-[60px] md:tw-mb-0'
            : 'tw-flex tw-justify-center tw-mt-[20px] tw-mb-[30px] md:tw-mt-[30px] md:tw-mb-0 xl:tw-mt-0'
        ">
          <button @click="$modal.show('add-contact-modal')" type="button"
            class="tw-bg-complementary-1 tw-bg-opacity-10 tw-px-6 tw-rounded-2xl tw-h-[40px] tw-w-[169px]">
            <div class="tw-flex tw-items-center">
              <img :src="plusImg" alt="" class="tw-h-[18px] tw-w-[18px] tw-mr-2" />
              <span class="tw-t16 tw-text-complementary-1">{{
              $t("Add Contact")
              }}</span>
            </div>
          </button>
        </div>
        <AddContactModal @update="successUpdate"></AddContactModal>
      </div>
    </div>
  </div>
</template>
<script>
import TwoDots from "@/components/TwoDots";
import AddContactModal from "@/components/newComponent/modal/UserAddContactModal.vue";
import ContactInfoContent from "@/components/user/contactInfoContent.vue";
import Swal from "sweetalert2";
import userSidebar from "@/components/user/userSidebar.vue";
export default {
  name: "contactInfo",
  layout: "profile",

  components: {
    TwoDots,
    AddContactModal,
    ContactInfoContent,
    userSidebar,
  },
  data() {
    return {
      firstName: "",
      lastName: "",
      userData: {},
      userCompanyId: [],
      userCompanyList: [],
      userAddNewCompanyList: [],
      userSavedExhibitionList: [],
      userVisibleSavedExhibitionList: [],
      yearOptions: [],
      monthOptions: [],
      dayOptions: [],
      yearSelect: "",
      monthSelect: "",
      daySelect: "",
      languageSelect: {
        en: "",
        zhtw: "",
      },
      phoneValid: false,
      contactImg: require("../../assets/img/noContact.png"),
      plusImg: require("~/assets/svg/addCompany.svg"),
      userContact: [],
    };
  },
  created() {
    this.fetchUserData();
    this.fetchContactInfo();
  },
  mounted() {
    this.yearOptions = Array.from(new Array(103), (val, index) =>
      (index + 1920).toString()
    );
    this.monthOptions = Array.from(new Array(13), (val, index) => {
      if (index < 10 && index > 0) {
        return "0" + index.toString();
      }
      if (index >= 10) {
        return index.toString();
      }
    });
    this.dayOptions = Array.from(new Array(32), (val, index) => {
      if (index < 10 && index > 0) {
        return "0" + index.toString();
      }
      if (index >= 10) {
        return index.toString();
      }
    });
    this.$nextTick(() => {
      window.addEventListener("resize", this.onResize);
    });
  },

  methods: {
    patchUserData() {
      if (this.width < 1366) {
        this.isEditInfoDialogActive = !this.isEditInfoDialogActive;
      }
      this.userData.prefer_country = JSON.stringify(this.languageSelect);
      if (this.$vuetify.breakpoint.name !== "xs") {
        this.userData.birth_date =
          this.yearSelect + "-" + this.monthSelect + "-" + this.daySelect;
        if (this.userData.birth_date.length < 10) {
          this.userData.birth_date = null;
        }
      }
      const patchData = JSON.parse(JSON.stringify(this.userData));
      delete patchData.LoginLog;
      delete patchData.UserCompany;
      delete patchData.UserSocialRelation;
      delete patchData.UserExhibition;
      this.$axios
        .put(
          `/member/users/${this.$route.params.id}?jwt=${this.$auth.$storage.getUniversal("jwt").token || ""
          }`,
          patchData
        )
        .then((res) => {
          this.successUpdate = !this.successUpdate;
          setTimeout(() => {
            this.successUpdate = !this.successUpdate;
          }, 1000);
          this.fetchUserData();
          this.$auth.$storage.setUniversal("userPicture", patchData.picture);
          this.$auth.$storage.setUniversal("userLastName", patchData.last_name);
          this.$store.dispatch("updatePicture");
        })
        .catch((err) => {
          console.log(err);
        });
    },
    fetchUserData() {
      this.$axios
        .get(
          `/trending/api/Members/Info`
        )
        .then((response) => {
          //console.log(JSON.stringify(response));
          if(response && response.data && response.data.DATA && response.data.DATA.rel){
            let data = response.data.DATA.rel
            if(data){
              this.userData = data;
              this.firstName = this.userData.FirstName;
              this.lastName = this.userData.LastName;
              this.userData.Phone ? (this.phoneValid = true): (this.phoneValid = false);
              
              this.userData.phone
            ? (this.phoneValid = true)
            : (this.phoneValid = false);

              if(this.userData.ArgumentID == "en-US"){
                this.languageSelect.en = true;

              }else if(this.userData.ArgumentID == "zh-TW"){
                this.languageSelect.zhtw = true;

              }else{
                this.languageSelect.en = "";
                this.languageSelect.zhtw = "";

              }

              if (
                this.userData.BirthDate && typeof this.userData.BirthDate === "object"

              ){
                this.yearSelect = "";
                this.monthSelect = "";
                this.daySelect = "";

              }else{
                const space = this.userData.BirthDate.split("T");
                const date = space[0].split("-");
                this.yearSelect = date[0];
                this.monthSelect = date[1];
                this.daySelect = date[2];

              }
            }
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    handleImageUpdate(pictureURL) {
      this.userData.picture = pictureURL;
      //this.patchUserData();
      this.closeCropDialog();
    },

    showCode(object) {
      this.userData.country_code = object.dialCode;
    },
    logout() {
      this.$auth.$storage.removeUniversal("jwt");
      this.$auth.$storage.removeUniversal("userPicture");
      this.$auth.$storage.removeUniversal("userLastName");
      this.$auth.$storage.removeUniversal("userBeforePath");

      if (window.innerWidth < 1024) {
        console.log(window.innerWidth);
        this.$router.push(this.localePath("/"));
      } else {
        this.$router.push(this.localePath("/user"));
      }
      this.$auth.logout();
    },
    fetchContactInfo() {
      this.$axios
      .get(
          `/trending/api/Members/Contacts`
        )
        .then((response) => {
          console.log(JSON.stringify(response));
          if(response && response.data && response.data.DATA && response.data.DATA.rel){
            let data = response.data.DATA.rel
            if(data){
              this.userContact = data;
            }
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    successUpdate() {
      this.$notify({
        type: "success",
        text: "更新成功",
      });
      this.fetchContactInfo();
    },
  },
};
</script>

<style scoped lang="scss">

</style>
