<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.company_tax_no }}
              </div>
              <div class="tw-pb-[6px] tw-text-[14px] tw-font-medium tw-text-base-primary">
                {{ item.company_name }}
              </div>
              <div class="tw-pb-[6px] tw-body-4 tw-text-base-primary tw-font-medium">
                {{
                countrySortOptions[item.company_country] +
                "．" +
                item.company_city
                }}
              </div>
              <div class="tw-text-[14px] tw-text-neutrals-700">
                {{ item.company_address1 + item.company_address2 }}
              </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.company_name }}</div>
                <div>{{ item.company_tax_no }}</div>
                <div>{{ countrySortOptions[item.company_country] }}</div>
                <div>{{ item.company_city }}</div>
                <div>{{ item.company_address1 + item.company_address2 }}</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>

        <!-- <v-card
          class="mx-7 mb-5 py-3 pe-5 ps-3 border-radius-10"
          v-for="(item, index) in userCompanyList"
          :key="index"
          color="neutrals"
        >
          <v-spacer class="d-flex">
            <v-spacer class="px-3">
              <div>{{ item.company_tax_no }}</div>
              <div>{{ item.company_name }}</div>
              <div class="d-flex align-center">
                <span>{{ countrySortOptions[item.company_country] }}</span>
                <div class="circle-delimeter mx-1"></div>
                <span>{{ item.company_city }}</span>
              </div>
              <div>
                <span v-if="item.company_address1">{{
                  item.company_address1
                }}</span>
                <span v-if="item.company_address2 && !item.company_address1">{{
                  item.company_address2
                }}</span>
              </div>
            </v-spacer>
            <div class="d-flex align-center">
              <v-btn
                @click="activeEditCompanyInfoDialog(item)"
                class="d-flex justify-center"
                icon
              >
                <unicon name="pen" height="20px" fill="neutrals-darken5" />
              </v-btn>
              <v-btn @click="deleteUserCompany(item)" icon>
                <unicon
                  name="trash-alt"
                  height="20px"
                  fill="neutrals-darken5"
                />
              </v-btn>
            </div>
          </v-spacer>
        </v-card>
        <v-spacer class="d-flex justify-center mb-15">
          <v-btn
            @click="$modal.show('addCompany')"
            color="primary border-radius-12 text-capitalize"
            width="150px"
          >
            <v-icon>mdi-plus</v-icon>
            <span>{{ $t("userProfile.addNewCompany") }}</span>
          </v-btn>
        </v-spacer>
        <v-spacer class="mb-4"></v-spacer> -->

        <CompanyEditInfoDialog :companyEditInfoDialogActive="companyEditDialogActive" :userCompany="propUserCompany"
          :countryOptions="countryOptions" :user_uuid="user_uuid" @refetch-company="getCompanyList"
          @refetch-user="fetchUserData" @close-edit-dialog="
            companyEditDialogActive = !companyEditDialogActive
          "></CompanyEditInfoDialog>
        <CompanyAddNewDialog :companyAddNewDialogActive="companyAddNewDialogActive" :countryOptions="countryOptions"
          :addNewCompanyList="userAddNewCompanyList" :user_uuid="user_uuid" @refetch-company="getCompanyList"
          @refetch-user="fetchUserData" @close-add-new-dialog="
            companyAddNewDialogActive = !companyAddNewDialogActive
          "></CompanyAddNewDialog>
        <CompanyDeleteDialog :deleteCompanyInfoDialogAcitve="companyDeleteDialogAcitve" :companyData="propUserCompany"
          @refetch-company="getCompanyList" @refetch-user="fetchUserData" @closeCompanyDeleteDialog="
            companyDeleteDialogAcitve = !companyDeleteDialogAcitve
          "></CompanyDeleteDialog>
      </div>
    </div>
  </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";

export default {
  name: "companyInfo",
  layout: "profile",
  components: {
    TwoDots,
    CompanyDeleteDialog,
    CompanyEditInfoDialog,
    CompanyAddNewDialog,
    userSidebar,
  },
  data() {
    return {
      firstName: "",
      lastName: "",
      userData: {},
      userCompanyId: [],
      userCompanyList: [],
      userAddNewCompanyList: [],
      userSavedExhibitionList: [],
      userVisibleSavedExhibitionList: [],
      userSavedExhibitionPageLength: 0,
      yearOptions: [],
      monthOptions: [],
      dayOptions: [],
      countryOptions: [],
      countrySortOptions: [],
      yearSelect: "",
      monthSelect: "",
      daySelect: "",
      phoneValid: false,
      companyEditDialogActive: false,
      companyAddNewDialogActive: false,
      companyDeleteDialogAcitve: false,
      propUserCompany: {},
      countryOptions: [],
      user_uuid: "",
      emptyImage: require("~/assets/img/companyEmpty.png"),
      userCompanyList: [],
      userAddNewCompanyList: [],
      companyTableColumns: [
        {
          text: "Company Name",
          value: "company_name",
          sortable: false,
          width: "16%",
        },
        {
          text: "Tax Number",
          value: "company_tax_no",
          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: "company_address",
          sortable: false,
          width: "39%",
        },
        {
          text: "",
          value: "action",
          sortable: false,
          width: "7%",
        },
      ],
    };
  },
  created() {
    // this.fetchUserData();
    // this.fetchSortCountry();
    // this.getCompanyList();
    // this.fetchCountry();
    if (this.$auth.$storage.getUniversal("jwt")) {
      const jsonPayload = jwt_decode(
        this.$auth.$storage.getUniversal("jwt").token
      );
      this.user_uuid = JSON.parse(jsonPayload.ueid);
    }
  },
  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: {
    fetchSortCountry() {
      this.$axios
        .get(
          `t/exhibitions/locations?lang=${this.$i18n.locale.replace(
            "-",
            ""
          )}&sort=False`
        )
        .then((res) => {
          this.countrySortOptions = res.data.country_name_list;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    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.$auth.$storage.getUniversal("jwt").user_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(
          `/member/users/${this.$auth.$storage.getUniversal("jwt").user_id
          }?jwt=${this.$auth.$storage.getUniversal("jwt").token}`
        )
        .then((res) => {
          this.userData = res.data;
          this.userCompanyId = res.data.UserCompany;
          this.firstName = res.data.first_name;

          this.lastName = res.data.last_name;
          this.userData.phone
            ? (this.phoneValid = true)
            : (this.phoneValid = false);
          !this.userData.prefer_country &&
            typeof this.userData.prefer_country === "object"
            ? this.userData.prefer_country
            : (this.languageSelect = JSON.parse(this.userData.prefer_country));
          if (
            !this.userData.birth_date &&
            typeof this.userData.birth_date === "object"
          ) {
            this.yearSelect = "";
            this.monthSelect = "";
            this.daySelect = "";
          } else {
            const date = this.userData.birth_date.split("-");
            this.yearSelect = date[0];
            this.monthSelect = date[1];
            this.daySelect = date[2];
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    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();
    },
    handleImageUpdate(pictureURL) {
      this.userData.picture = pictureURL;
      this.patchUserData();
      this.closeCropDialog();
    },

    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
        .post(
          `/member/company/list?jwt=${this.$auth.$storage.getUniversal("jwt").token || ""
          }`,
          this.userCompanyId
        )
        .then((res) => {
          this.userCompanyList = res.data.company_list;

          this.userAddNewCompanyList = res.data.add_new_company_list;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    fetchCountry() {
      this.$axios
        .get("/users/countries")
        .then((res) => {
          this.countryOptions = res.data.result;
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
  watch: {
    userCompanyId: {
      handler: function () {
        this.getCompanyList();
      },
      deep: true,
    },
  },
};
</script>

<style scoped lang="scss">

</style>
