<template>
  <div
    class="tw-px-[30px] tw-mb-[60px] md:tw-mb-[100px] xl:tw-px-[60px] xl:tw-max-w-screen-xl xl:tw-mx-auto xl:tw-grid xl:tw-grid-cols-[380px_auto] xl:tw-gap-[30px]">
    <section class="xl:tw-col-span-2 tw-mb-5 md:tw-mb-0">
      <centerMode :list="adList" v-if="adList.length"></centerMode>
    </section>
    <section class="xl:tw-col-span-2 tw-mb-[40px] xl:tw-mb-[10px]">
      <Breadcrumbs class="tw-py-[7px] md:tw-py-[10px] xl:tw-py-[13px] tw-mb-4 md:tw-mb-6 xl:tw-mb-0"></Breadcrumbs>
      <sort :results="result" :sortType="sortType" :sortBy="sortBy" @sort="updateSortBy($event)"
        @filter="$modal.show(`sidebar-filter-modal`)"></sort>
    </section>
    <section class="tw-grid tw-grid-cols-1 tw-gap-[30px] tw-auto-rows-min">
      <div class="tw-max-h-min" v-if="$vuetify.breakpoint.xl">
        <DateCard @update="updateDateFilter" :modalChecked="selectedDates" />
      </div>
      <div v-if="$vuetify.breakpoint.xl">
        <oneLevel :label="'exhibition.Show Status'" :list="statusList" @update="updateStatusFilter"></oneLevel>
      </div>
      <div v-if="$vuetify.breakpoint.xl">
        <multipleLevel :label="'Categories'" :placeholder="'Find Categories...'" :list="categoryList"
          :queryItem="categoryQueryFilter" @update="updateCategoryFilter"></multipleLevel>
      </div>
      <div v-if="$vuetify.breakpoint.xl">
        <multipleLevel :label="'Location'" :placeholder="'Find country/city ...'" :list="locationList"
          :queryItem="locationQueryFilter" @update="updateLocationFilter"></multipleLevel>
      </div>
      <div v-if="$vuetify.breakpoint.xl">
        <!-- <rating></rating> -->
      </div>
    </section>
    <section class="">
      <ExhibitionListCard v-for="(item, index) in exhibitionList" :key="index" :item="item"></ExhibitionListCard>
      <div class="tw-mt-[34px] tw-flex tw-justify-end">
        <pagination :pageLength="pageLength" @update="updatePage"></pagination>
      </div>
    </section>
    <div v-if="!$vuetify.breakpoint.xl">
      <!-- <ShowSidebarFilterModal :statusList="statuses" :locationList="locations" :categoryList="categories"
        :statusChecked="selectedStatus" :locationChecked="locationChecked" :categoryChecked="categoryChecked"
        :datesChecked="selectedDates" @updateCategoryFilter="updateCategoryFilter"
        @updateLocationFilter="updateLocationFilter" @updateStatusFilter="updateStatusFilter"
        @updateDateFilter="updateDateFilter">
      </ShowSidebarFilterModal> -->
      <ShowSidebarFilterModal :statusList="statusList" :locationList="locationList" :categoryList="categoryList"
        :statusChecked="selectedStatus" 
        :datesChecked="selectedDates" @updateCategoryFilter="updateCategoryFilter"
        @updateLocationFilter="updateLocationFilter" @updateStatusFilter="updateStatusFilter"
        @updateDateFilter="updateDateFilter">
      </ShowSidebarFilterModal>
    </div>
    <loading :isLoading="isPageLoading"></loading>
  </div>
</template>

<script>
import Breadcrumbs from "~/components/Breadcrumbs.vue";
import centerMode from "@/components/swiper/centerMode";
import ExhibitionListCard from "~/components/exhibition/ExhibitionListCard.vue";
import DateCard from "~/components/exhibition/DateCard.vue";
import sort from "@/components/newComponent/sort/sort";
import multipleLevel from "@/components/newComponent/filter/multipleLevel";
import oneLevel from "@/components/newComponent/filter/oneLevel";
import rating from "@/components/newComponent/filter/rating.vue";
import pagination from "@/components/newComponent/pagination/pagination.vue";
import ShowSidebarFilterModal from "@/components/exhibition/ShowSidebarFilterModal.vue";
import { XIcon } from "vue-feather-icons";
import loading from "@/components/newComponent/loading/loading.vue";

export default {
  name: "ExhibitionView",
  auth: false,
  meta: {
    name: "Exhibition",
  },
  components: {
    centerMode,
    Breadcrumbs,
    DateCard,
    ExhibitionListCard,
    XIcon,
    sort,
    multipleLevel,
    oneLevel,
    rating,
    pagination,
    ShowSidebarFilterModal,
    loading,
  },
  data: () => ({

    currentPage: 1,
    itemsPerPage: 10,
    total: 0,
    adList: [],
    statusList: [],
    exhibitionList: [],
    locationList: [],

    selectedDates: [],
    selectedStatus: [],

    statusMap: new Map(),

    regionMap: new Map(),
    countryMap: new Map(),
    cityMap: new Map(),

    mainCategoryMap: new Map(),
    subCategoryMap: new Map(),

    selectedMainCategory: [],
    selectedSubCategory: [],

    selectedRegion: [],
    selectedCountry: [],
    selectedCity: [],

    favoriteSet: new Set(),

    categoryList: [],
    categoryQueryFilter: "",
    locationQueryFilter: "",
    width: undefined,
    sortType: [
      
      { name: "exhibition.Recommended", value: "Recommended" },
      { name: "exhibition.ShowDate", value: "ShowDate" },
      { name: "exhibition.ExhibitorCount", value: "ExhibitorCount" },
      { name: "exhibition.VisitorCount", value: "VisitorCount" },

    ],
    sortBy: "ShowDate",
    query: ""
  }),
  async created() {

    // console.log("created");
    this.isPageLoading = true;

    // this.getAdList();
    await this.getStatusList();
    await this.getLocationList();
    await this.getCategoryList();
    await this.getFavorite();
    await this.getQuery();
    
    if (process.client) {
      this.width = window.innerWidth;
    }
    this.$nextTick(() => {
      this.isPageLoading = false;
    });
  },
  async mounted() {

    // console.log("mounted");

    this.$nextTick(() => {
      window.addEventListener("resize", this.onResize);
    });
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.onResize);
  },
  computed: {

    result() {
      return this.total;
    },
    pageLength() {
      return Math.ceil(this.result / this.itemsPerPage);
    },
  },
  watch: {

    $route() {

      this.getQuery();

    },
  },
  methods: {
    onResize() {
      if (process.client) {
        this.width = window.innerWidth;
      }
    },
    getAdList() {

      this.adList = [
        {
          id: 'banner_1',
          image: require('/assets/img/banner/banner_1.png'),
          url: '/service?taiwan=taiwan'
        },
        {
          id: 'banner_2',
          image: require('/assets/img/banner/banner_2.png'),
          url: 'javascript:void(0);'
        },
        {
          id: 'banner_3',
          image: require('/assets/img/banner/banner_3.png'),
          url: 'javascript:void(0);'
        },
        {
          id: 'banner_4',
          image: require('/assets/img/banner/banner_4.png'),
          url: 'javascript:void(0);'
        },
        {
          id: 'banner_5',
          image: require('/assets/img/banner/banner_5.png'),
          url: 'javascript:void(0);'
        }
      ]

    },
    async getStatusList() {
      await this.$axios
        .get(
          `/trending/api/Exhibition/Statuses?Lang=${this.$i18n.localeProperties["langQuery"]}`
        )
        .then((result) => {
          if(result && result.data && result.data.DATA && result.data.DATA.rel){

            this.statusList = result.data.DATA.rel;

            this.statusList = this.statusList.map((item => {

              this.statusMap.set(item.Key, item.Value);

              return {
                title: item.Value,
                key: item.Key,
              };

            }));

          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    async getCategoryList() {
      await this.$axios
        .get(
          `/trending/api/Exhibition/Categories?Lang=${this.$i18n.localeProperties["langQuery"]}`
        )
        .then((result) => {

          if(result && result.data && result.data.DATA && result.data.DATA.rel){

            this.categoryList = result.data.DATA.rel;
            this.categoryList = this.categoryList.map((item) => {

              this.mainCategoryMap.set(item.CategoryID, item);

              item.SubCategoryList = item.SubCategoryList.map(

                (children) => {

                  this.subCategoryMap.set(children.CategoryID, children);

                  return {
                    title: children.CategoryName,
                    key: children.CategoryID,
                  };
                }
              );
              return {
                title: item.CategoryName,
                key: item.CategoryID,
                children: item.SubCategoryList,
              };
            });

          }

        })
        .catch((err) => {
          console.log(err);
        });
    },
    async getLocationList() {
      await this.$axios
        .get(
          `/trending/api/Exhibition/Locations?Lang=${this.$i18n.localeProperties["langQuery"]}`
        )
        .then((result) => {

          if(result && result.data && result.data.DATA && result.data.DATA.rel){
            var vm = this;
            vm.locationList = result.data.DATA.rel;

            vm.locationList = vm.locationList.map((region) => {

              this.regionMap.set(region.RegionID, region);

              region.CountryList = region.CountryList.map((country) => {

                this.countryMap.set(country.CountryID, country);

                country.CityList = country.CityList.map((city) => {

                  this.cityMap.set(city.CityID, city);

                  return {
                    title: city.CityName,
                    key: city.CityID,
                  };
                });
                return {
                  title: country.CountryName,
                  key: country.CountryID,
                  children: country.CityList,
                };
              });
              return {
                title: region.RegionName,
                key: region.RegionID,
                children: region.CountryList,
              };
            });

            return result.data.DATA.rel;

          }

        })
        .catch((err) => {
          console.log(err);
        });
    }, 
    async getExhibitionCard() {

      await this.$axios
        .get(
          `/trending/api/Exhibition/Cards?Lang=${this.$i18n.localeProperties["langQuery"]}` +
          `&PageIndex=${this.currentPage}` +
          `&PageSize=${this.itemsPerPage}` +
          `&RegionIDs=${JSON.stringify(this.selectedRegion)}` +
          `&CountryIDs=${JSON.stringify(this.selectedCountry)}` +
          `&CityIDs=${JSON.stringify(this.selectedCity)}` +
          `&MainCategoryIDs=${JSON.stringify(this.selectedMainCategory)}` +
          `&SubCategoryIDs=${JSON.stringify(this.selectedSubCategory)}` +
          `&Status=${JSON.stringify(this.selectedStatus)}` +
          `&Date=${JSON.stringify(this.selectedDates)}` +
          `&Sort=${this.sortBy}` +
          `&Query=${this.query}`
        )
        .then((result) => {

          if(result && result.data && result.data.DATA && result.data.DATA.rel){
            let data = result.data.DATA.rel
            if(data.DataList.length>0){
              this.total = data.Total;
              this.exhibitionList = data.DataList;
              this.setFavorite();
            }
          }

        })
        .catch((err) => {
          console.log(err);
          this.exhibitionList = [];
        });
    },
    async getFavorite() {

      this.favoriteSet.clear();

      if (this.$auth.loggedIn) {
        await this.$axios
          .get(
            `/trending/api/Favorite/Favorites?Type=Exhibition`
          )
          .then((result) => {

            if(result && result.data && result.data.DATA && result.data.DATA.rel){

              let favoriteList = [];
              favoriteList = result.data.DATA.rel;

              favoriteList.forEach(item => {

                this.favoriteSet.add(item.ParentID);

              })
            }

          })
          .catch((err) => {
            console.log(err);
          });

      }

    },
    setFavorite() {

      if (this.exhibitionList.length > 0 && this.$auth.loggedIn) {

        for (let i = 0; i < this.exhibitionList.length; i++) {

          if (this.favoriteSet.has(this.exhibitionList[i].ExhibitionID)) {

            this.exhibitionList[i].IsFavorite = "Y";

          }

        }

      }

    },

    getNewExhibitionCard() {

      this.currentPage = 1;
      this.query = "";
      this.getExhibitionCard();

    },

    updateSortBy(data) {

      this.sortBy = data;
      this.getNewExhibitionCard();

    },
    updatePage(value) {

      this.currentPage = value;
      window.scrollTo(0,0);

      this.getExhibitionCard();
      
    },
    updateCategoryFilter(value) {

      this.selectedMainCategory = [];
      this.selectedSubCategory = [];

      value.forEach(key => {

        if (this.mainCategoryMap.has(key)) {
          this.selectedMainCategory.push(key);
        }

        if (this.subCategoryMap.has(key)) {
          this.selectedSubCategory.push(key);
        }

      });

      this.getNewExhibitionCard();

    },

    updateLocationFilter(value) {

      this.selectedRegion = [];
      this.selectedCountry = [];
      this.selectedCity = [];

      value.forEach(key => {

        if (this.regionMap.has(key)) {
          this.selectedRegion.push(key);
        }

        if (this.countryMap.has(key)) {
          this.selectedCountry.push(key);
        }

        if (this.cityMap.has(key)) {
          this.selectedCity.push(key);
        }

      });

      this.getNewExhibitionCard();

    },
    updateStatusFilter(value) {

      this.selectedStatus = [];

      value.forEach(key => {

        if (this.statusMap.has(key)) {
          this.selectedStatus.push(key);
        }

      });

      this.getNewExhibitionCard();

    },
    updateDateFilter(value) {

      this.selectedDates = value;
      this.getNewExhibitionCard();
      
    },
    async getQuery() {

      let vm = this;

      this.selectedMainCategory = [];
      this.selectedSubCategory = [];
      this.selectedCountry = [];
      this.selectedCity = [];
      this.query = "";

      if (this.$route.query.category) {
        vm.categoryQueryFilter = vm.$route.query.category;
        this.selectedMainCategory.push(vm.$route.query.category);
      }

      if (this.$route.query.subcategory) {
        vm.categoryQueryFilter = vm.$route.query.subcategory;
        this.selectedSubCategory.push(vm.$route.query.subcategory);
      }

      if (this.$route.query.country) {
        vm.locationQueryFilter = vm.$route.query.country;
        this.selectedCountry.push(vm.$route.query.country);
      }

      if (this.$route.query.city) {
        vm.locationQueryFilter = vm.$route.query.city;
        this.selectedCity.push(vm.$route.query.city);
      }

      if (this.$route.query.q) {
        this.query = vm.$route.query.q;
      }

      this.getExhibitionCard();
      

    },
  },
};
</script>

<style scoped lang="scss">
.sort-by-text {
  max-width: 142px;

  >h3 {
    border-right: 1px solid #e5e5e5;
  }
}

.sort-by-text-sm {
  max-width: 112px;

  >h3 {
    border-right: 1px solid #e5e5e5;
  }
}
</style>

<style lang="scss">
.filter-zindex {
  z-index: 499 !important;
}

.exhibition-pagination {
  .v-pagination {
    justify-content: flex-end;
  }

  .v-pagination__navigation,
  .v-pagination__item {
    box-shadow: none;
    margin: 0;
    min-width: 28px;

    &.v-pagination__item--active {
      color: $primary-orange !important;
    }
  }
}

.v-breadcrumbs {
  padding: 0px;
}

.v-application ul {
  padding-left: 0px;
}
</style>