<template>
  <div class="companyInfo 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-mb-[20px] tw-font-bold tw-text-base-primary md:t24 md:tw-mb-[30px]">
          <two-dots class="tw-mr-[30px]"></two-dots>{{ $t('userProfile.companyInfo')}}
        </div>
        <div v-if="userCompanyList.length < 1" class="tw-flex tw-flex-col tw-mb-[50px] tw-mt-[80px] md:tw-mb-[30px]">
          <img src="~/assets/svg/noCompanyInfo.svg" class="tw-max-w-[160px] tw-mx-auto md:tw-max-w-[210px]" alt="" />
          <div class="tw-text-[16px] tw-text-neutrals-800 tw-w-fit tw-mx-auto md:tw-text-[18px]">
            {{ $t("No Company info yet ...") }}
          </div>
        </div>
        <div v-else class="tw-mb-[20px] xl:tw-mb-[30px]">
          <!-- 手機版 -->
          <div v-for="(item, index) in userCompanyList" :key="`mobile-${index}`"
            class="tw-flex tw-justify-between tw-w-full tw-bg-white tw-border tw-border-solid tw-py-[15px] tw-px-[15px] tw-rounded-[10px] tw-border-neutrals-200 xl:tw-px-0 tw-mb-[20px] last:tw-mb-0 md:tw-mb-[30px] xl:tw-hidden">
            <div>
              <div class="tw-pb-[6px] tw-body-4 tw-text-base-primary tw-font-medium">
                {{ item.TaxNumber }}
              </div>
              <div class="tw-pb-[6px] tw-text-[14px] tw-font-medium tw-text-base-primary">
                {{ item.CompanyName }}
              </div>
              <div class="tw-pb-[6px] tw-body-4 tw-text-base-primary tw-font-medium">
                {{
                item.Country.CountryName +
                "．" +
                item.CityName
                }}
              </div>
              <div class="tw-text-[14px] tw-text-neutrals-700">
                {{ item.Street1 + item.Street2 }}
              </div>
            </div>
            <div class="tw-flex tw-flex-col md:tw-flex-row tw-my-auto xl:tw-hidden">
              <button @click="activeEditCompanyInfoDialog(item)" type="button">
                <img src="~/assets/svg/edit.svg" alt=""
                  class="tw-h-[28px] tw-w-[28px] tw-mb-[20px] md:tw-mb-0 md:tw-mr-[15px]" />
              </button>
              <button @click="deleteUserCompany(item)" type="button">
                <img src="~/assets/svg/delete.svg" alt="" class="tw-h-[28px] tw-w-[28px]" />
              </button>
            </div>
          </div>
          <!-- 電腦版 -->
          <div class="xl:tw-grid tw-gap-[15px] tw-grid-cols-[148px_116px_86px_110px_220px] tw-hidden tw-mb-[30px]">
            <div class="tw-text-neutrals-500 tw-body-4">
              {{ $t("userProfile.companyName") }}
            </div>
            <div class="tw-text-neutrals-500 tw-body-4">
              {{ $t("userProfile.taxNumber") }}
            </div>
            <div class="tw-text-neutrals-500 tw-body-4">
              {{ $t("userProfile.companyCountry") }}
            </div>
            <div class="tw-text-neutrals-500 tw-body-4">{{ $t("userProfile.companyCity") }}</div>
            <div class="tw-text-neutrals-500 tw-body-4">
              {{ $t("userProfile.companyAddress") }}
            </div>
          </div>
          <div v-for="(item, index) in userCompanyList" :key="index"
            class="tw-hidden tw-bg-white tw-mb-[20px] last:tw-mb-0 md:tw-mb-[30px] xl:tw-block">
            <div class="tw-flex tw-flex-row">
              <div class="xl:tw-grid tw-gap-[15px] tw-grid-cols-[148px_116px_86px_110px_220px] tw-mr-[15px]">
                <div>{{ item.CompanyName }}</div>
                <div>{{ item.TaxNumber }}</div>
                <div>{{ item.Country.CountryName }}</div>
                <div>{{ item.CityName }}</div>
                <div>{{ item.Street1 + item.Street2 }}</div>
              </div>
              <div>
                <button @click="activeEditCompanyInfoDialog(item)" type="button">
                  <img src="~/assets/svg/edit.svg" alt="" class="tw-h-[28px] tw-w-[28px] tw-mr-[20px]" />
                </button>
                <button @click="deleteUserCompany(item)" type="button">
                  <img src="~/assets/svg/delete.svg" alt="" class="tw-h-[28px] tw-w-[28px]" />
                </button>
              </div>
            </div>
          </div>
        </div>
        <button
          class="tw-grid tw-grid-cols-[18px_auto] tw-gap-[6px] tw-bg-complementary-1 tw-bg-opacity-10 tw-px-[12px] tw-py-[11px] tw-rounded-[10px] tw-mx-auto tw-mb-[30px] xl:tw-mb-0">
          <img src="~/assets/svg/addCompany.svg" alt="" />
          <div class="tw-text-[14px] tw-font-medium tw-text-complementary-1" @click="$modal.show('addCompany')">
            {{ $t("userProfile.addNewCompany") }}
          </div>
        </button>
        <CompanyEditInfoDialog :userCompany="propUserCompany"
          :countryOptions="countryOptions" :user_uuid="user_uuid" @refetch-company="getCompanyList"
          @refetch-user="getCompanyList" @close-edit-dialog="
            companyEditDialogActive = !companyEditDialogActive
          "></CompanyEditInfoDialog>
        <CompanyAddNewDialog :companyAddNewDialogActive="companyAddNewDialogActive" :countryOptions="countryOptions"
          :addNewCompanyList="userAddNewCompanyList" :user_uuid="user_uuid" @refetch-company="getCompanyList"
          @refetch-user="getCompanyList" @close-add-new-dialog="
            companyAddNewDialogActive = !companyAddNewDialogActive
          "></CompanyAddNewDialog>
        <CompanyDeleteDialog :deleteCompanyInfoDialogAcitve="companyDeleteDialogAcitve" :userCompany="propUserCompany"
          @refetch-company="getCompanyList" @closeCompanyDeleteDialog="
            companyDeleteDialogAcitve = !companyDeleteDialogAcitve
          "></CompanyDeleteDialog>
      </div>
    </div>
    <loading :isLoading="isPageLoading"></loading>
  </div>
</template>
<script>
import TwoDots from "@/components/TwoDots";
import CompanyDeleteDialog from "../../components/user/companyDeleteDialog.vue";
import CompanyEditInfoDialog from "../../components/user/companyEditInfoDialog.vue";
import CompanyAddNewDialog from "../../components/user/companyAddNewDialog.vue";
import jwt_decode from "jwt-decode";
import userSidebar from "@/components/user/userSidebar.vue";
import loading from "@/components/newComponent/loading/loading.vue";

export default {
  name: "companyInfo",
  layout: "profile",
  components: {
    TwoDots,
    CompanyDeleteDialog,
    CompanyEditInfoDialog,
    CompanyAddNewDialog,
    userSidebar,
    loading
  },
  data() {
    return {
      firstName: "",
      lastName: "",
      userData: {},
      userCompanyId: [],
      userCompanyList: [],
      userAddNewCompanyList: [],
      userSavedExhibitionList: [],
      userVisibleSavedExhibitionList: [],
      userSavedExhibitionPageLength: 0,
      countryOptions: [],
      countrySortOptions: [],
      yearSelect: "",
      monthSelect: "",
      daySelect: "",
      phoneValid: false,
      companyEditDialogActive: false,
      companyAddNewDialogActive: false,
      companyDeleteDialogAcitve: false,
      propUserCompany: {},
      countryOptions: [],
      user_uuid: "",
      emptyImage: require("~/assets/img/companyEmpty.png"),
      userAddNewCompanyList: [],
      regionList:[],
      countryList:[],
      cityList:[],
      location:[],
      companyTableColumns: [
        {
          text: "Company Name",
          value: "CompanyName",
          sortable: false,
          width: "16%",
        },
        {
          text: "Tax Number",
          value: "TaxNumber",
          sortable: false,
          width: "16%",
        },
        {
          text: "Country",
          value: "company_country",
          sortable: false,
          width: "10%",
        },
        {
          text: "City",
          value: "company_city",
          sortable: false,
          width: "12%",
        },
        {
          text: "Address",
          value: "Street1",
          sortable: false,
          width: "39%",
        },
        {
          text: "",
          value: "action",
          sortable: false,
          width: "7%",
        },
      ],
      isPageLoading: false,
    };
  },
  beforeCreate(){
    
  },
  created() {
    this.isPageLoading = true;
    this.fetchUserData();
    this.getCompanyList();
    this.fetchCountry();
    this.$nextTick(()=>{
      this.isPageLoading = false;
    });
  },
  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: {
    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);
        });
    },

    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) {
        this.$router.push(this.localePath("/"));
      } else {
        this.$router.push(this.localePath("/user"));
      }
      this.$auth.logout();
    },

    activeEditCompanyInfoDialog(item) {
      this.companyEditDialogActive = !this.companyEditDialogActive;

      this.propUserCompany = { ...item };
      this.$modal.show("edit-company-modal");
    },

    activeAddNewCompanyInfoDialog() {
      this.companyAddNewDialogActive = !this.companyAddNewDialogActive;
    },

    deleteUserCompany(item) {
      // this.companyDeleteDialogAcitve = !this.companyDeleteDialogAcitve;
      this.$modal.show("delete-company-modal");
      this.propUserCompany = { ...item };
    },

    getCompanyList() {
      this.$axios
        .get(
          `/trending/api/Members/Companies?Lang=${this.$i18n.localeProperties["langQuery"]}`
        )
        .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.userCompanyList = data;
            }
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },

    fetchCountry() {
      this.$axios
      .get(`/trending/api/location/countries?RegionID&Lang=${this.$i18n.localeProperties["langQuery"]}`)
        .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.countryList = data;
              //console.log(this.countryList);
              this.countryOptions = this.countryList.map((item) => {
                return {
                    id: item.CountryID,
                    name: item.CountryName,
                };
              });

            }
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },

  },
  watch: {
    userCompanyId: {
      handler: function () {
        this.getCompanyList();
      },
      deep: true,
    },
  },
};
</script>

<style scoped lang="scss">

</style>
