<template>
  <div class="container-fluid">
    <the-content-loading
      class="absolute-positioning"
      v-if="fetchingData"
    ></the-content-loading>

    <div v-else>
      <div v-if="listTakenFromTreeGetter?.length">
        <div class="row">
          <div class="col-12">
            <div class="favorite-list firefox-scrollbar">
              <favorite-list-item
                v-for="(item, index) in listTakenFromTreeGetter"
                :key="index"
                :item="item"
                :index="index"
                :searchText="searchText"
              ></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>
    </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>
  </div>
</template>
<script>
import { mapState, mapActions } from "pinia";
import favoriteApi from "~/apis/favoriteApi";

export default {
  props: {
    data_type: {
      default: "bookmark", // or bookmark, history
    },
  },
  beforeMount() {
    this.httpService = new HttpService(import.meta.env.VITE_REPO_BASE_URL);
  },
  mounted() {
    if (this.activeSchemaGetter) this.showDefaultList();
  },
  watch: {
    activeEventTreeListGetter(newVal) {
      if (this.loading) return;
      this.loading = true;

      if (newVal.pid == 1 || newVal.pid == 2) {
        this.titleList = newVal.parent.name;
        this.item = {
          key: newVal.key,
          favoriteItem: newVal.parent.key,
        };
      } else if (newVal.pid == 0) {
        this.titleList = newVal.name;
        this.item = {
          key: "all",
          favoriteItem: newVal.key,
        };
      } else {
        return;
      }
      this.getAnswerTreeSelection(this.item, newVal);
    },
  },
  data() {
    return {
      httpService: undefined,
      searchText: "",
      loading: false,
      pagination: {
        pages: 0,
        total: 0,
        page: 1,
        offset: 0, // page * per_page
        limit: 10, //per_page
      },
      favoritelist: [],
      item: "",
      sorting: "",
      titleList: "",

      typingTimer: 0,
      doneTypingInterval: 500,
    };
  },
  computed: {
    ...mapState({
      organNameGetter: "organNameGetter",
      schemasGetter: "schemasGetter",
      activeSchemaGetter: "activeSchemaGetter",
    }),
    ...mapState("favorite", [
      "listTakenFromTreeGetter",
      "activeEventTreeListGetter",
    ]),
  },
  methods: {
    ...mapActions("favorite", [
      "SET_LIST_TAKEN_FROM_TREE",
      "SET_ACTIVE_EVENT_TREE_LIST",
    ]),
    /**
     * هنگامی که کلیدی فشار داده می‌شود، تایمر تایپ کردن را متوقف می‌کند.
     */
    onKeyDown() {
      clearTimeout(this.typingTimer);
    },

    sendQuery() {
      clearTimeout(this.typingTimer);

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

        let url = favoriteApi.favorite.getList;
        url = url.replace("{{data_type}}", this.data_type);
        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 };
          })
          .finally(() => {
            this.loading = 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.activeSchemaGetter.children.find(
        (item) => item.key == key
      );
      if (item) return item.name;

      return "";
    },
    showtext(item) {
      let _name = "navigation";

      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
    showDefaultList(event) {
      if (this.loading) return;
      this.loading = true;

      let primitiveEvent = this.activeSchemaGetter;
      this.item = {
        key: "all",
        favoriteItem: primitiveEvent.key,
      };
      let url = favoriteApi.favorite.getList;
        url = url.replace("{{data_type}}", this.data_type);
        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 };
        })
        .finally(() => {
          this.loading = 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.data_type);
        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 };
        })
        .finally(() => {
          this.loading = false;
        });
      this.SET_ACTIVE_EVENT_TREE_LIST(event);
    },
    deleteItem(item) {
      let url = favoriteApi.favorite.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.httpService
            .postRequest(url)
            .then((res) => {
              setTimeout(() => {
                this.nextPage();
              }, 1000);
            })
            .catch((error) => {
              
            });
        }
      });
    },
    // #endregion
    // #region  pagination
    nextPage() {
      let url = favoriteApi.favorite.getList;
        url = url.replace("{{data_type}}", this.data_type);
        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.nextPage();
    },
    pageLimitChanged(paging) {
      this.resetPagination();
      this.pagination.limit = paging.limit;
      // this.$emit("changePage", this.page);
      // this.getQuery(false, true);
      this.nextPage();
    },
    sortChanged(sorting) {
      this.pagination.page = this.pagination.offset = 0;
      this.sorting = sorting;
      // this.$emit("changePage", this.sorting);
      // this.getQuery(false, true);
      this.nextPage();
    },
    resetPagination() {
      this.pagination = {
        pages: 0,
        total: 0,
        page: 1,
        offset: 0,
        limit: 10,
      };
    },

    // #endregion
  },

};
</script>
<style lang="scss"></style>
