<template>
  <div
    class="tw-px-[30px] tw-mt-[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-[36px] md:tw-mb-[24px] lg:tw-mb-[34px]">
      <Breadcrumbs></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 v-if="$vuetify.breakpoint.xl">
        <multipleLevel :label="'Categories'" :placeholder="$t('Find category/subcategory ...')" :list="categoryList" :queryItem="categoryQueryFilter"
          @update="updateCategoryFilter"></multipleLevel>
      </div>
      <div v-if="$vuetify.breakpoint.xl">
        <multipleLevel :label="'Location'" :placeholder="$t('Find country/city ...')" :list="locationList"
          :queryItem="locationQueryFilter" @update="updateLocationFilter"></multipleLevel>
      </div>
      <div v-if="$vuetify.breakpoint.xl">
        <price :max="maxPrice" :currentValue="priceRangeFilter" @update="updatePriceRange"></price>
      </div>
      <div v-if="$vuetify.breakpoint.xl">
        <!-- <rating @update="updateRatingRange"></rating> -->
      </div>
    </section>
    <section class="">
      <ServiceListCard class="tw-mb-[30px]" v-for="(item, index) in serviceList" :key="index" :service="item">
      </ServiceListCard>
      <div class="tw-mt-[34px] tw-flex tw-justify-end">
        <pagination :pageLength="pageLength" @update="updateCurrentPage"></pagination>
      </div>
    </section>
    <div v-if="!$vuetify.breakpoint.xl">
      <sidebarFilterModal :max="maxPrice" :locationList="locationList" 
        :locationChecked="locationNameFilter" :categoryChecked="categoryFilter" :priceChecked="priceRangeFilter"
        @updatePriceRange="updatePriceRange" @updateCategoryFilter="updateCategoryFilter"
        @updateLocationFilter="updateLocationFilter"></sidebarFilterModal>
    </div>
    <loading :isLoading="isPageLoading"></loading>
  </div>
</template>
<script>
import Breadcrumbs from "@/components/Breadcrumbs";
import sort from "@/components/newComponent/sort/sort";
import oneLevel from "@/components/newComponent/filter/oneLevel";
import multipleLevel from "@/components/newComponent/filter/multipleLevel";
import price from "@/components/newComponent/filter/price";
import rating from "@/components/newComponent/filter/rating.vue";
import pagination from "@/components/newComponent/pagination/pagination.vue";
import sidebarFilterModal from "@/components/newComponent/modal/sidebarFilterModal.vue";
import ServiceListCard from "@/components/service/ServiceListCard";
import loading from "@/components/newComponent/loading/loading.vue";

export default {
  name: "ServiceList",
  auth: false,
  components: {
    Breadcrumbs,
    sort,
    oneLevel,
    multipleLevel,
    price,
    rating,
    sidebarFilterModal,
    ServiceListCard,
    pagination,
    loading,
  },
  meta: {
    pageName: "Service List",
  },
  data() {
    return {
      renderList: [],
      serviceList: [],
      sortType: [
        // { name: "Ratings", value: "Ratings" },
        // { name: "ShowEasy Recommended", value: "ShowEasy Recommended" },
        { name: "Popularity", value: "Popularity" },
        { name: "Price (Low to High)", value: "Price" },
        { name: "Recently Added", value: "Recently Added" },
      ],
      locationList: [],
      categoryList: [],
      // regionNameList: ['123'],
      countryNameList: ['Asia','Asia1'],
      cityNameList: ['Taiwan','Taiwan1'],
      categoryNameList: ['Rental cars','Rental cars1'],
      subcategoryNameList: ['子類1'],
      sortBy: "CreateDate",
      maxPrice: 100,
      priceRangeFilter: [0,100],
      ratingRangeFilter: [0, 5],
      locationNameFilter: ['Asia','Taiwan'],
      categoryFilter: ['Rental cars','Rental cars1'],
      perPageItems: 10,
      currentPage: 1,
      total: 0,
      locationQueryFilter: "",
      categoryQueryFilter: "",
      isPageLoading: false,
      mainCategoryMap: new Map(),
      subCategoryMap: new Map(),
      mainLocationMap: new Map(),
      subLocationMap: new Map(),
      subLocationMap2: new Map(),
      mainCategoryQuery: '',
      subCategoryQuery: '',
    };
  },
  async created() {
    this.isPageLoading = true;
    await this.getQuery();
    await this.getServiceList();
    await this.getCategoryList();
    await this.getLocationList();
    await this.getPriceRange();
    this.isPageLoading = false;
    // this.renderList = this.sliceRenderList(this.serviceFilter);
  },
  mounted() { },
  computed: {
    // serviceFilter() {
    //   var vm = this;
    //   if (Array.isArray(vm.serviceList)) {
    //     let priceList = vm.filterByPrice(
    //       vm.serviceList,
    //       vm.priceRangeFilter[0],
    //       vm.priceRangeFilter[1]
    //     );
    //     priceList = priceList == undefined ? [] : priceList;
    //     let locationList = vm.filterByLocation(
    //       priceList,
    //       vm.locationNameFilter
    //     );
    //     locationList = locationList == undefined ? [] : locationList;
    //     let categoryList = vm.filterByCategory(
    //       locationList,
    //       vm.categoryFilter
    //     );
    //     categoryList = categoryList == undefined ? [] : categoryList;
    //     if(categoryList.length<1){
    //       return [];
    //     }
    //     let sortedList = vm.sortServiceList(categoryList);
    //     return sortedList;
    //   } else {
    //     return [];
    //   }
    // },
    result() {
      return this.total;
    },
    pageLength() {
      return Math.ceil(this.result / this.perPageItems);
    },
    // renderList() {
    //   let arr = this.sliceRenderList(this.serviceFilter);
    //   return arr;
    // },
    currency() {
      return this.$store.getters.getCurrency;
    },
  },
  watch: {
    currency: {
      handler: async function (newVal, oldVal) {
        let vm = this;
        if (newVal !== oldVal) {
          await vm.getServiceList();
          // let data =await vm.mapServiceLocationName(
          //   vm.serviceList,
          //   vm.countryNameList,
          //   vm.cityNameList
          // );
          // vm.serviceList = data == undefined ? [] : data;
          // vm.serviceList =await vm.mapServiceCategoryName(
          //   vm.serviceList,
          //   vm.categoryNameList
          // );
          // vm.serviceList = data == undefined ? [] : data;
          // vm.renderList =await vm.serviceList;
          await vm.getPriceRange();0
          vm.isPageLoading = false;
        }
      },
    },
    $route: {
      handler: function () {
        this.getQuery();
      },
    },
  },
  methods: {
    async getServiceList() {
      let vm = this;
      let keyword = "";
      let category = "";
      let subcatg = "";
      if (this.$route.query.q) {
        keyword = "&keyword=" + this.$route.query.q;
      }
      if (this.$route.query.category) {
        category = "&category=" + this.$route.query.category;
      }
      if (this.$route.query.subcatg) {
        subcatg = "&subcatg=" + this.$route.query.subcatg;
      }
      await this.$axios.get(`/trending/api/Onsite/ServiceLists?Lang=${this.$i18n.localeProperties["langQuery"]}&PageIndex=${this.currentPage}
      &PageSize=${this.perPageItems}&SortField=CreateDate&sortOrder=desc`).then((response) => {
          if(response && response.data && response.data.DATA && response.data.DATA.rel){
            let data = response.data.DATA.rel
            if(data.DataList.length>0){
              this.total = data.Total;
              this.serviceList = data.DataList;
            }
          }
      })
      .catch((err) => {
          console.log(err);
      });
    },
    async getCategoryList() {
      await this.$axios
      .get(`/trending/api/Onsite/Categories?Lang=${this.$i18n.localeProperties["langQuery"]}`)
      .then((response) => {
        if(response && response.data && response.data.DATA && response.data.DATA.rel){
          let data = response.data.DATA.rel
          if(data.length>0){
            this.categoryList = data.map((item) => {
              this.mainCategoryMap.set(item.CategoryID, item);
              if(item.SubCategoryList && item.SubCategoryList.length>0){
                item.SubCategoryList = item.SubCategoryList.map(
                  (children) => {
                    this.subCategoryMap.set(children.CategoryID, children);
                    return {
                      title: children.CategoryName,
                      key: children.CategoryID,
                    };
                  }
                );
              }else{
                item.SubCategoryList = [];
              }
              return {
                title: item.CategoryName,
                key: item.CategoryID,
                children: item.SubCategoryList,
              };
            });
          }
        }
      })
      .catch((error) => 
        console.log(error)
      );
    },
    async getLocationList() {
      await this.$axios
      .get(`/trending/api/Onsite/Locations?Lang=${this.$i18n.localeProperties["langQuery"]}`)
      .then((response) => {
        if(response && response.data && response.data.DATA && response.data.DATA.rel){
          let data = response.data.DATA.rel
          if(data.length>0){
            // this.locationList = data;
            this.locationList = data.map((item) => {
              this.mainLocationMap.set(item.RegionID, item);
              if(item.CountryList && item.CountryList.length>0){
                item.CountryList = item.CountryList.map(
                  (children) => {
                    this.subLocationMap.set(children.CountryID, children);
                    if(children.CityList && children.CityList.length>0){
                      children.CityList = children.CityList.map(
                        (children2) => {
                          this.subLocationMap2.set(children2.CityID, children2);
                          return {
                            title: children2.CityName,
                            key: children2.CityID,
                          };
                        }
                      );
                    }else{
                      children.CityList = [];
                    }
                    return {
                      title: children.CountryName,
                      key: children.CountryID,
                      children: children.CityList,
                    };
                  }
                );
              }else{
                item.CountryList = [];
              }
              return {
                title: item.RegionName,
                key: item.RegionID,
                children: item.CountryList,
              };
            });
          }
        }
      })
      .catch((error) => 
        console.log(error)
      );
    },
    updateSortBy(data) {
      this.sortBy = data;
      console.log("排序:"+this.sortBy);
      this.getServiceList();
    },
    // sortServiceList(data) {
    //   switch (this.sortBy) {
    //     // case "Ratings":
    //     //   function Ratings(a, b) {
    //     //     if (Number(a.rating) < Number(b.rating)) return 1;
    //     //     if (Number(a.rating) > Number(b.rating)) return -1;
    //     //     return 0;
    //     //   }
    //     //   return data.sort(Ratings);
    //     // case "ShowEasy Recommended":
    //     //   return data;
    //     case "Popularity":
    //       function Views(a, b) {
    //         if (Number(a.view_counts) < Number(b.view_counts)) return 1;
    //         if (Number(a.view_counts) > Number(b.view_counts)) return -1;
    //         return 0;
    //       }
    //       return data.sort(Views);
    //     case "Price":
    //       function Price(a, b) {
    //         if (Number(a.price) < Number(b.price)) return -1;
    //         if (Number(a.price) > Number(b.price)) return 1;
    //         return 0;
    //       }
    //       return data.sort(Price);
    //     case "Recently Added":
    //       function Date(a, b) {
    //         if (
    //           a.launch_dates[0].replace(/-/g, "") <
    //           b.launch_dates[0].replace(/-/g, "")
    //         )
    //           return 1;
    //         if (
    //           a.launch_dates[0].replace(/-/g, "") >
    //           b.launch_dates[0].replace(/-/g, "")
    //         )
    //           return -1;
    //         return 0;
    //       }
    //       return data.sort(Date);
    //     default:
    //       return data;
    //   }
    // },
    mapSavedService(data, savedList) {
      return data.map((item) => {
        item.liked = false;
        if (savedList.includes(item.id)) {
          item.liked = true;
        }
        return item;
      });
    },
    mapServiceLocationName(data, countryList, cityList) {
      data = data.map((item) => {
        Number(item.country) > 0
          ? (item.countryName = countryList[item.country])
          : (item.countryName = "");
        return item;
      });
      data = data.map((item) => {
        Number(item.city) > 0
          ? (item.cityName = cityList[item.city])
          : (item.cityName = "");
        return item;
      });
      return data;
    },
    mapServiceCategoryName(data, categoryList) {
      data = data.map((item) => {
        Number(item.category) > 0
          ? (item.categoryName = categoryList[item.category])
          : (item.categoryName = "");
        return item;
      });
      return data;
    },
    async getPriceRange() {
      let max = 0;
      let vm = this;
      if(vm.serviceList){
        vm.serviceList.forEach((element) => {
          if (element.price > max) {
            max = element.price;
          }
        });
      }
      vm.maxPrice = max;
      vm.priceRangeFilter = [0, max];
    },
    filterByPrice(data, min, max) {
      let item = data.filter((item) => item.price >= min && item.price <= max);
      return item;
    },
    updatePriceRange(value) {
      this.priceRangeFilter = [...value];
    },
    filterByRating(data, min, max) {
      return data.filter((item) => item.price >= min && item.price <= max);
    },
    updateRatingRange(value) {
      console.log(value);
    },
    filterByLocation(data, locations) {
      let list = data.filter(
        (item) =>
          locations.includes(item.cityName) ||
          locations.includes(item.countryName)
      );
      return list;
    },
    updateLocationFilter(value) {
      console.log("位置勾選");
      this.locationNameFilter = value;
      this.getServiceList();
    },
    filterByCategory(data, categories) {
      return data.filter((item) => categories.includes(item.categoryName));
    },
    updateCategoryFilter(value) {
      console.log("類型勾選");
      this.categoryFilter = value;
      this.getServiceList();
    },
    updateCurrentPage(value) {
      console.log("分頁變化");
      this.currentPage = value;
      this.getServiceList();
    },
    sliceRenderList(data) {
      return data.slice(
        (this.currentPage - 1) * this.perPageItems,
        this.currentPage * this.perPageItems
      );
    },
    async getQuery() {
      
      let vm = this;
      // this.locationQueryFilter = "";
      this.categoryQueryFilter = "";
      // if (this.$route.query.hasOwnProperty("country") && this.countryNameList.length>0) {
      //   this.locationQueryFilter =
      //     this.countryNameList[Number(this.$route.query.country)];
      // }
      // if (this.$route.query.hasOwnProperty("city") && this.cityNameList.length>0) {
      //   this.locationQueryFilter =
      //     this.cityNameList[Number(this.$route.query.city)];
      // }
      // if (this.$route.query.hasOwnProperty("region")) {
      //   this.locationQueryFilter =
      //     this.regionNameList[Number(this.$route.query.region)];
      // }
      // if (this.$route.query.hasOwnProperty("category") && this.categoryNameList.length>0) {
      //   this.categoryQueryFilter =
      //     this.categoryNameList[Number(this.$route.query.category)];
      // }
      // if (this.$route.query.hasOwnProperty("subcategory")) {
      //   this.categoryQueryFilter =
      //     this.unsortSubcategoryList[Number(this.$route.query.subcategory)];
      // }
      
      if(vm.$route.query.hasOwnProperty("category")){
        vm.categoryQueryFilter = vm.$route.query.category;
      }else if(vm.$route.query.hasOwnProperty("subcatg")){
        vm.categoryQueryFilter = vm.$route.query.subcatg;
      }
    },
  },
};
</script>
<style lang="scss" scoped>

</style>
