<template>
  <div>
    <NuxtLayout name="default" :menu="sidbarMenu">
      <div class="container-fluid" :class="$route.name">
        <div class="row">
          <div class="col-12">
            <template v-if="canView">
              <div class="row favorite-header-color pt-3">
                <div class="col-12">
                  <ul class="nav nav-tabs">
                    <li class="nav-item">
                      <button
                        title="همه"
                        type="button"
                        @click.prevent="onSelectCat('همه')"
                        class="btn nav-link h-100 d-flex align-items-center"
                        :class="{
                          active: activeCat == 'همه',
                        }"
                      >
                        <span
                          class="number d-flex align-items-center justify-content-center ml-2"
                          ><span>{{ totalCounts }}</span></span
                        >
                        همه
                      </button>
                    </li>
                    <li
                      class="nav-item position-relative"
                      v-for="(tabItem, index) in categories"
                      :key="index"
                    >
                      <button
                        :title="tabItem.name"
                        type="button"
                        @click.prevent="onSelectCat(tabItem)"
                        class="btn nav-link h-100 d-flex justify-content-center align-items-center"
                        :class="{
                          active: activeCat == tabItem,
                        }"
                      >
                        <span
                          class="number d-flex align-items-center justify-content-center ml-2"
                          ><span>{{ getCatCounts(tabItem) }}</span></span
                        >
                        <span> {{ tabItem }}</span>

                        <button-component
                          v-if="
                            $route.name == 'favorites' && activeCat == tabItem
                          "
                          @click="editCat(tabItem)"
                          v-tooltip="'ویرایش'"
                          classes="btn cat-edit-btn"
                          buttonText=""
                        >
                          <svg class="icon icon-Component-242--1">
                            <use xlink:href="#icon-Component-242--1"></use>
                          </svg>
                        </button-component>
                      </button>
                    </li>
                    <li class="nav-item">
                      <button
                        v-if="$route.name == 'favorites'"
                        title="ایجاد"
                        type="button"
                        @click.prevent="openModal()"
                        class="btn nav-link h-100"
                      >
                        <svg class="icon icon-Component-133--1">
                          <use xlink:href="#icon-Component-133--1"></use>
                        </svg>
                      </button>
                    </li>
                  </ul>
                </div>
              </div>

              <the-content-loading
                class="absolute-positioning"
                v-if="fetchingData"
              ></the-content-loading>

              <div v-else>
                <div v-if="list?.length">
                  <div class="row">
                    <div class="col-12">
                      <div class="favorite-list firefox-scrollbar">
                        <favorite-list-item
                          v-for="(item, index) in list"
                          :key="index"
                          :entity="item"
                          :index="index"
                          :searchText="searchText"
                          :categories="categories"
                          @getList="showDefaultList"
                          @add-to-cat="onAddToCat"
                        ></favorite-list-item>
                      </div>
                    </div>
                  </div>
                  <div class="row mt-3">
                    <div class="col-12">
                      <!-- <jahat-pagination
                    class="pagination"
                    style="font-size: 13px"
                    :paginationInfo="pagination"
                    @page-changed="pageChanged"
                    @page-limit-changed="pageLimitChanged"
                    @sort-changed="sortChanged"
                  >
                  </jahat-pagination> -->
                    </div>
                  </div>
                </div>
                <no-data v-else></no-data>
              </div>
              <!-- <no-data v-else>
            <the-content-loading v-if="fetchingData"></the-content-loading>

            <div
              v-else
              class="d-flex justify-content-center align-items-center"
            >
              <div
                class="alert alert-warning d-flex justify-content-center align-items-center"
              >
                <span
                  class="tavasi tavasi-warning-circle color-inherit ml-1 text__32"
                ></span>
                عدم دسترسی
              </div>
            </div>
          </no-data> -->
            </template>
          </div>
        </div>
        <!-- <base-modal-v2
      v-if="showBaseModal"
      modalSize="modal-sm"
      minHeight="auto"
      :hasFooter="false"
      @close="closeModal"
    >
      <slot>ایجاد پوشه جدید</slot>

      <slot name="body">
        <fav-new-category
          :activeTab="activeTabKey"
          :categories="categories"
          :editCat="editCatItem"
          @close="closeModal"
        ></fav-new-category>
      </slot>

    </base-modal-v2> -->
      </div>
    </NuxtLayout>
  </div>
</template>

<script>
// import monirMenu from "~/json/dashboard/monir/menu.json";
// import majlesMenu from "~/json/dashboard/majles/menuDefault.json";
import { useCommonStore } from "~/stores/commonStore";
import { mapState, mapActions } from "pinia";
import favoriteApi from "~/apis/favoriteApi";
import { useFavoriteStore } from "~/stores/favoriteStore";
import { useAuthStore } from "~/stores/authStore";
import { clearBodyClass } from "@manuals/utilities";

import monirMenu from "~/json/dashboard/monir/menu.json";
import majlesMenu from "~/json/dashboard/majles/menuDefault.json";

export default {
  name:"favortires",
  setup() {
    definePageMeta({
      layout: false,
      // layout: "dashboard-layout",
    });
  },
  beforeMount() {
    // const useCommonStore = commonStore();
    // this.sidebarMenuSetter(monirMenu);
    this.activeTabKey = "bookmark";

    clearBodyClass();
  },
  mounted() {
    this.TOGGLE_PANEL(false);
    this.setBodyClass("favorite-page");

    if (this.isRealUser) {
      this.canView = true;

      let schemaExist = this.favoriteSchemaGetter;
      if (!schemaExist) this.getSchemas();

      // if (schemaExist == "object") {
      this.getCategories("bookmark");
      // } else {
      // this.getSchemas();
      // }
    } else {
      this.canView = false;
    }
  },
  destroyed() {
    clearBodyClass();
  },
  data() {
    return {
      routeName: buildName(),
      showListPanel: false,

      dateRange: 0,
      totalCounts: 0,
      list: [],
      categories: [],
      activeTabKey: "bookmark", // history
      activeCat: "همه",
      editCatItem: null,
      canView: false,
      showBaseModal: false,
      searchText: "",
      httpService: undefined,
      statusFavoriteMenu: false,
      fetchingData: false,

      pagination: {
        pages: 0,
        total: 0,
        page: 1,
        offset: 0, // page * per_page
        limit: 10, //per_page
      },
      // favoritelist: [],
      counts: [],
      // item: "",
      sorting: {
        sortby: "created",
        sortorder: "asc", // asc | desc
      },
      // titleList: "",

      typingTimer: 0,
      doneTypingInterval: 500,
    };
  },
  computed: {
    ...mapState(useCommonStore, ["isSidebarCollapsed"]),
    // ...mapState({
    // organNameGetter: "organNameGetter",
    // }),
    ...mapState(useAuthStore, ["isRealUser"]),
    ...mapState(useFavoriteStore, [
      // "listTakenFromTreeGetter",
      // "activeEventTreeListGetter",
      "favoriteSchemaGetter",
      // "favoriteActiveTabGetter",
    ]),
    sidbarMenu() {
      if (isMajlesBuild()) return majlesMenu;
      else return monirMenu;
    },
  },
  methods: {
    ...mapActions(useCommonStore, [
      "TOGGLE_PANEL",
      "getSystems",
      "setBodyClass",
      "sidebarCollapsedSetter",
      "activeSystemSetter",
      "sidebarMenuSetter",
    ]),

    ...mapActions(useFavoriteStore, [
      // "SET_LIST_TAKEN_FROM_TREE",
      // "SET_ACTIVE_EVENT_TREE_LIST",
      "favoriteActiveTabSetter",
      "favoriteSchemaSetter",
    ]),
    // ...mapActions(["checkPermissions"]),
    onDatePickerChanged($event) {
      this.activeCat = "range";
      this.showDefaultList();
    },
    editCat(cat) {
      this.editCatItem = cat;
      this.openModal();
    },
    getCatCounts(catName) {
      let cat = this.counts?.find((i) => i.key == catName);
      if (cat) return cat.doc_count;
      return 0;
    },
    async onAddToCat({ cats, cat, id }) {
      let url = favoriteApi.favorite.setFavoritesCat;

      url = url.replace("@data_type", this.activeTabKey);
      url = url.replace("@id", id);

      let payload = {
        tags: [...cats, cat],
      };

      try {
        const { $api } = useNuxtApp();
        const data = await $api(url, {
          baseURL: import.meta.env.VITE_REPO_BASE_URL,
          method: "POST",
          body: payload,
        });

        this.showDefaultList();
      } catch (err) {}

      // this.httpService.postRequest(url, payload).then((res) => {
      //   setTimeout(() => {
      //     this.showDefaultList();
      //   }, 500);
      // });
    },
    setActiveTab(newTab) {
      this.activeTabKey = newTab;
      this.getCategories();
    },
    async getCategories(dataType = "bookmark") {
      if (this.fetchingData) return;
      this.fetchingData = true;

      let url = favoriteApi.favorite.getCategories;
      url = url.replace("@data_type", dataType);

      try {
        const { $api } = useNuxtApp();
        const res = await $api(url, {
          baseURL: import.meta.env.VITE_REPO_BASE_URL,
        });

        this.categories = res.data;
        this.getCounts();

        this.showDefaultList();
        this.fetchingData = false;
      } catch (err) {}

      // this.httpService
      //   .getRequest(url)
      //   .then((res) => {
      //     this.categories = res.data;
      //     this.getCounts();

      //     this.showDefaultList();
      //   })
      //   .finally(() => {
      //     this.fetchingData = false;
      //   });
    },
    onSelectCat(event) {
      this.activeCat = event;
      this.showDefaultList();

      // this.SET_ACTIVE_EVENT_TREE_LIST(event);
    },
    async getSchemas() {
      try {
        const { $api } = useNuxtApp();
        const res = await $api(favoriteApi.schema.list, {
          baseURL: import.meta.env.VITE_REPO_BASE_URL,
          method: "POST",
          body: {
            organ: "public",
            system: "favorite",
            build_state: buildState(),
          },
        });

        this.favoriteSchemaSetter(res.data.favorite);
        let schema = res.data.favorite?.find(
          (item) => item.key == this.activeTabKey
        );
        console.log(this.activeTabKey);
        console.log(schema);
        this.favoriteActiveTabSetter(schema);
      } catch (err) {}

      // this.httpService
      //   .postRequest(favoriteApi.schema.list, {
      //     organ: "public",
      //     system: "favorite",
      //     build_state: this.buildState(),
      //   })
      //   .then((response) => {
      //     // console.log(response)
      //     this.favoriteSchemaSetter(response.data.favorite);
      //     let schema = response.data.favorite?.find(
      //       (item) => item.key == this.activeTabKey
      //     );
      //     console.log(this.activeTabKey);
      //     console.log(schema);
      //     this.favoriteActiveTabSetter(schema);
      //   });
    },
    // afterFormSaved() {
    //   this.showDefaultList();
    // },
    openModal() {
      this.showBaseModal = true;
    },
    closeModal() {
      this.showBaseModal = false;
      this.getCategories();
    },

    // updateFavoriteList() {
    //   setTimeout(() => {
    //     this.getAnswerTreeSelection(this.item, this.activeEventTreeListGetter);
    //   }, 1000);
    // },
    // openPagGrup(data) {
    //   this.enablePanelToggling = data;
    //   if (this.enablePanelToggling == 1) {
    //     this.showToggleListPanel();
    //   }
    // },

    //To close the menu
    closeMenu(event) {
      // this.$refs.favoriteList.$el.classList.toggle("d-none");
      this.$refs.favoriteList.$el.classList.add("d-none");
      this.$refs.ShowMenu.classList.remove("d-none");
      // this.statusFavoriteMenu = event;
      // if (event == true) {
      //   this.$refs.ShowMenu.classList.add("d-none");
      // } else {
      //   this.$refs.ShowMenu.classList.remove("d-none");
      // }
    },
    // showFavoriteList(event) {
    //   this.$refs.favoriteList.$el.classList.remove("d-none");
    //   this.$refs.ShowMenu.classList.add("d-none");
    // },
    //To show the menu
    // showMenu() {
    //   this.$refs.favoriteList.$el.classList.add("d-none");
    // },
    async getCounts() {
      let url = favoriteApi.favorite.getCounts;
      url = url.replace("@data_type", this.activeTabKey);

      try {
        const { $api } = useNuxtApp();
        const res = await $api(url, {
          baseURL: import.meta.env.VITE_REPO_BASE_URL,
        });

        this.totalCounts = res.hits.total.value;
        this.counts = res.aggregations.result.buckets;
      } catch (err) {}

      // this.httpService.getRequest(url).then((res) => {
      //   this.totalCounts = res.hits.total.value;
      //   this.counts = res.aggregations.result.buckets;
      // });
    },
    /**
     * هنگامی که کلیدی فشار داده می‌شود، تایمر تایپ کردن را متوقف می‌کند.
     */
    onKeyDown() {
      clearTimeout(this.typingTimer);
    },

    sendQuery() {
      this.activeCat = "search";
      clearTimeout(this.typingTimer);

      this.typingTimer = setTimeout(() => {
        this.resetPagination();
        this.showDefaultList();

        // let url = favoriteApi.favorite.getList;
        // url = url.replace("@data_type", this.activeTabKey);
        // url = url.replace("@offset", this.pagination.offset);
        // url = url.replace("@limit", this.pagination.limit);

        // url += this.searchText?.length ? `/q=${this.searchText}` : "";

        // this.httpService
        //   .getRequest(url)
        //   .then((res) => {
        //     this.SET_LIST_TAKEN_FROM_TREE(res.hits.hits);

        //     const total = res.hits.total.value;
        //     const pages = Math.ceil(total / this.pagination.limit);
        //     const pagination = {
        //       total: total,
        //       pages: pages == 0 ? 1 : pages,
        //     };

        //     this.pagination = { ...this.pagination, ...pagination };
        //     this.fetchingData = false;
        //   })
        //   .finally(() => {
        //     this.fetchingData = false;
        //   });
      }, this.doneTypingInterval);
    },
    // #region  all
    // datefa(item) {
    //   var m = item * 1000; //برای تبدیل به میلی ثانیه
    //   var d = new Date(m).toLocaleDateString("fa-IR");
    //   return d;
    // },
    //change  label for  favorite-item-label
    // labelchange(key) {
    //   let item = this.favoriteSchemaGetter.children.find(
    //     (item) => item.key == key
    //   );
    //   if (item) return item.name;

    //   return "";
    // },
    // showtext(item) {
    //   let name = "navigationView";

    //   const routeData = this.$router.resolve({
    //     name: name,
    //     params: {
    //       id: item._source.ref_id,
    //       key: item._source.ref_key,
    //     },
    //     query: {
    //       searchtext: this.searchText ?? undefined,
    //     },
    //   });
    //   window.open(routeData.href, "_blank");
    // },
    // #endregion

    // #region  add to favotites list
    async showDefaultList(event) {
      // if (this.fetchingData) return;
      // this.fetchingData = true;

      // let primitiveEvent = this.favoriteActiveTabGetter;

      // this.item = {
      //   key: "all",
      //   favoriteItem: primitiveEvent?.key,
      // };

      let url = favoriteApi.favorite.getList;
      url = url.replace("@data_type", this.activeTabKey);
      url = url.replace("@offset", this.pagination.offset);
      url = url.replace("@limit", this.pagination.limit);

      if (this.activeCat == "range") {
        url = url.replace("@filter", "range=" + this.dateRange.join("_"));
      } else if (this.activeCat == "search") {
        url = url.replace("@filter", "query=" + this.searchText);
      } else if (this.activeCat == "همه") {
        url = url.replace("/@filter", "");
      } else {
        url = url.replace("@filter", "tag=" + this.activeCat);
      }

      try {
        const { $api } = useNuxtApp();
        const res = await $api(url, {
          baseURL: import.meta.env.VITE_REPO_BASE_URL,
        });

        this.list = res.hits.hits;

        const total = res.hits.total.value;
        const pages = Math.ceil(total / this.pagination.limit);
        const pagination = {
          total: total,
          pages: pages == 0 ? 1 : pages,
        };

        this.pagination = { ...this.pagination, ...pagination };
      } catch (err) {}
      // this.httpService
      //   .getRequest(url)
      //   .then((res) => {
      //     // this.SET_LIST_TAKEN_FROM_TREE(res.hits.hits);
      //     this.list = res.hits.hits;

      //     const total = res.hits.total.value;
      //     const pages = Math.ceil(total / this.pagination.limit);
      //     const pagination = {
      //       total: total,
      //       pages: pages == 0 ? 1 : pages,
      //     };

      //     this.pagination = { ...this.pagination, ...pagination };
      //   })
      //   .finally(() => {
      //     // this.fetchingData = false;
      //   });
      // this.SET_ACTIVE_EVENT_TREE_LIST(primitiveEvent);
      // this.titleList = primitiveEvent.name;
    },
    // getAnswerTreeSelection(item, event) {
    //   let url = favoriteApi.favorite.getList;
    //   url = url.replace("{{data_type}}", this.activeTabKey);
    //   url = url.replace("{{offset}}", this.pagination.offset);
    //   url = url.replace("{{limit}}", this.pagination.limit);

    //   this.httpService
    //     .getRequest(url)
    //     .then((res) => {
    //       this.SET_LIST_TAKEN_FROM_TREE(res.hits.hits);
    //       this.getCounts();
    //       const total = res.hits.total.value;
    //       const pages = Math.ceil(total / this.pagination.limit);
    //       const pagination = {
    //         total: total,
    //         pages: pages == 0 ? 1 : pages,
    //       };

    //       this.pagination = { ...this.pagination, ...pagination };
    //     })
    //     .finally(() => {
    //       this.fetchingData = false;
    //     });
    //   this.SET_ACTIVE_EVENT_TREE_LIST(event);
    // },
    async deleteItem(item) {
      let url = favoriteApi.bookmark.delete;
      url = url.replace("{{data_type}}", item._source.data_type);
      url = url.replace("{{id}}", item._source.ref_id);

      this.mySwalConfirm({
        title: "هشدار!!!",
        html: `از حذف آیتم جاری اطمینان دارید؟ `,
        icon: "warning",
      }).then((result) => {
        if (result.isConfirmed) {
          this.deleteRequest();
        }
      });
    },

    async deleteRequest() {
      try {
        const { $api } = useNuxtApp();
        const res = await $api(url, {
          baseURL: import.meta.env.VITE_REPO_BASE_URL,
          method: "POST",
        });

        setTimeout(() => {
          this.showDefaultList();
        }, 1000);
      } catch (err) {}
    },
    // #endregion
    // #region  pagination
    // nextPage() {
    //   let url = favoriteApi.favorite.getList;
    //   url = url.replace("{{data_type}}", this.activeTabKey);
    //   url = url.replace("{{offset}}", this.pagination.offset);
    //   url = url.replace("{{limit}}", this.pagination.limit);

    //   this.httpService.getRequest(url).then((res) => {
    //     this.SET_LIST_TAKEN_FROM_TREE(res.hits.hits);
    //     const total = res.hits.total.value;
    //     const pages = Math.ceil(total / this.pagination.limit);
    //     const pagination = {
    //       total: total,
    //       pages: pages == 0 ? 1 : pages,
    //     };

    //     this.pagination = { ...this.pagination, ...pagination };
    //   });
    // },
    pageChanged(paging) {
      let page = paging.pageNumber;
      page -= 1;
      this.pagination.offset = page * paging.limit;
      this.pagination.limit = paging.limit;
      this.pagination.page = paging.pageNumber;
      // this.$emit("changePage", this.page);
      // this.getQuery(false, true);
      this.showDefaultList();
    },
    pageLimitChanged(paging) {
      this.resetPagination();
      this.pagination.limit = paging.limit;
      // this.$emit("changePage", this.page);
      // this.getQuery(false, true);
      this.showDefaultList();
    },
    sortChanged(sorting) {
      this.pagination.page = this.pagination.offset = 0;
      this.sorting = sorting;
      // this.$emit("changePage", this.sorting);
      // this.getQuery(false, true);
      this.showDefaultList();
    },
    resetPagination() {
      this.pagination = {
        pages: 0,
        total: 0,
        page: 1,
        offset: 0,
        limit: 10,
      };
    },

    // #endregion
  },
  components: {
    FavoriteListItem: defineAsyncComponent(() =>
      import("@/components/favorites/components/FavoriteListItem.vue")
    ),
  },

  
};
</script>

<style lang="scss">
@import "../assets/favorites/scss/favorites";
</style>

<style lang="scss" scoped>
.nav-tabs-container {
  display: flex;
  justify-content: center;
}
.favorite-header-color {
  background: rgb(230, 231, 232);
  .cat-edit-btn {
    // position: absolute;
    // top: -0.5em;
    // left: -0.5em;
    // padding: 0;
    color: #aaa;
    font-size: 0.8rem;

    &:hover {
      filter: brightness(0.5);
    }
  }
}
</style>

<style lang="scss">
.favorite-header-color {
  background: rgb(230, 231, 232);

  .date-time-picker {
    .vpd-icon-btn {
      margin-bottom: 0;
    }
    .vpd-main .vpd-input-group .form-control {
      min-width: 16em;
    }
  }
}
.favorites {
  .nav-link {
    padding: 0.5em 2.5em !important;
    &.active {
      padding: 0.5em 2.5em !important;
    }
    &:hover {
      color: var(--primary-color);
      border-color: transparent;
      transition: background-color 0.3s ease, color 0.3s ease;
    }
  }
  .number {
    height: 1em !important;
    width: 0em !important;
    background-color: #f6f6f6;
    border-radius: 1em;
    padding: 0.7em;
    color: black;
  }
}
</style>