<template>
  <!-- #region  لیست تمام موجودیت ها   -->
  <div>
    <div class="navigation mt-3 firefox-scrollbar">
      <div
        v-for="(item, key) in listEntity"
        :key="key"
        class="item mt-2"
        :class="{ active: activeItemClass(item) }"
      >
        <div class="d-flex position-relative text-10 mt-2 item-navigation">
          <i
            class="tavasi tavasi-Component-149--3 ms-1"
            style="color: var(--text-primary-highlight)"
          ></i>
          <a
            @click.prevent="showEntityContent(item, key)"
            class="text-title"
            :title="item.title"
            data-bs-toggle="tooltip"
            data-placement="top"
          >
            {{
              getDataValue(
                item,
                activeEntityViewSchemaGetter?.entity_title,
                activeEntityViewSchemaGetter?.list_title
              )
            }}
          </a>
        </div>
      </div>
    </div>
    <div class="mt-2 me-auto" style="bottom: 20px" v-if="showPagination">
      <div v-if="isMorePagination">
        <more-pagination @next-page="pageChanged"></more-pagination>
        <span class="d-flex justify-content-center mt-2">
          از {{ pagination.total }} جلسه مقدار {{ listEntity.length }} جلسه
          مشاهده شد
        </span>
      </div>
      <!-- <div v-else>
        <span> تمام موارد را مشاهده کردید </span>
      </div> -->
      <no-data v-else>
        <div 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 ms-1 text__32"
            ></span>
            تمام موارد را مشاهده کردید
          </div>
        </div>
      </no-data>
    </div>
  </div>

  <!-- #endregion -->
</template>
<script>
import { mapActions, mapState } from "pinia";

import { useEntityStore } from "@search/stores/entityStore";
import repoApi from "~/apis/repoApi";

/**
 * @vue-data {Array} [listEntity=[]] - آرایه‌ای از موجودیت‌ها.
 */
export default {
  props: ["item"],
  // mixins: [entityViewMixin],
  mounted() {
    if (this.$route.query.listkey) {
      this.getEntityList(
        this.$route.params.key,
        this.$route.params.id,
        this.$route.query.listkey
      );
      this.showPagination = true;
    } else if (this.listEntity.length == 0)
      this.listEntity = this.listEntityGetter;
  },
  computed: {
    ...mapState(useEntityStore, [
      "activeEntityViewSchemaGetter",
      "activeTabGetter",
      "listEntityGetter",
    ]),
  },
  data() {
    return {
      listEntity: [],
      selectedItem: undefined,
      pagination: {
        pages: 0,
        total: 0,
        page: 1,
        offset: 0, // page * per_page
        limit: 15, //per_page
      },
      isMorePagination: true,
      showPagination: false,
    };
  },
  methods: {
    // ...mapActions(useEntityStore, ["activeResearchTypeSetter"]),
    ...mapActions(useEntityStore, ["SET_ITEM_ENTITY"]),
    pageChanged(paging) {
      // let page = paging.pageNumber;
      // page -= 1;

      if (this.pagination.offset <= this.pagination.total) {
        this.pagination.offset = this.pagination.page * this.pagination.limit;
        this.pagination.limit = this.pagination.limit;
        this.pagination.page++;
        this.getEntityList(
          this.$route.params.key,
          this.$route.params.id,
          this.$route.query.listkey
        );
      }
    },
    /**
     * این تابع لیست موجودیت‌ها را بر اساس نوع موجودیت، شناسه موجودیت و کلید لیست دریافت می‌کند.
     * @param {string} _entityType - نوع موجودیت
     * @param {string} _entityId - شناسه موجودیت
     * @param {string} _listKey - کلید لیست
     */

    async getEntityList(_entityType, _entityId, _listKey) {
      this.entity_type = _entityType;

      let url = repoApi.public.list;
      url = url.replace("{{index_key}}", _entityType);
      url = url.replace("{{entity_id}}", _entityId);
      url = url.replace("{{list_key}}", _listKey);
      url = url.replace("{{offset}}", this.pagination.offset);
      url = url.replace("{{limit}}", this.pagination.limit);

      try {
        const { $api } = useNuxtApp();
        const res = await $api(url, {
          baseURL: repoUrl(),
          body: {
            organ: this.organNameGetter,
            system: "search",
            build_state: buildState(),
          },
        });

        this.listEntity.push(...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 };
        if (this.pagination.offset >= this.pagination.total) {
          this.isMorePagination = false;
        }
      } catch (err) {}
    },
    /**
     * این تابع مقدار داده‌ای خاص از آیتم و کلید داده شده را بازمی‌گرداند.
     * @param {Object} item - آیتم داده
     * @param {string} key - کلید داده
     * @param {Object} [list_title] - قالب و کلیدهای لیست عنوان (اختیاری)
     * @returns {string} - مقدار داده‌ای
     */
    getDataValue(item, key, list_title = undefined) {
      if (!key) key = "title";

      let text = "";
      if (list_title) {
        text = list_title.template;
        list_title.keys.forEach((el) => {
          if (item._source[el.key]) {
            let tt = item._source[el.key];
            if (el.isDate) {
              tt = new Date(tt).toLocaleDateString("fa-IR");
            }
            text = text.replace("{" + el.key + "}", tt);
          } else {
            let tt = item._source.title;
            if (el.isDate) {
              tt = new Date(tt).toLocaleDateString("fa-IR");
            }
            text = text.replace("{" + el.key + "}", tt);
          }
        });
      } else text = item._source[key];

      return text;
    },
    /**
     * این تابع محتوای موجودیت را نمایش می‌دهد و آیتم را به روز می‌کند.
     * @param {Object} item - آیتم موجودیت
     * @param {string} key - کلید موجودیت
     */
    showEntityContent(item, key) {
      this.selectedItem = item;

      let _id = item._id;
      if (
        this.$route.params?.key == "qasection" ||
        this.$route.params?.key == "rgsection"
      ) {
        _id = item._source?.qanon_id;
      }

      let _listkey = this.$route.query.listkey;
      let name = "navigationView";
      if (_listkey) name = "navigation";

      this.SET_ITEM_ENTITY(item);
      this.appendclass();

      this.$router
        .push({
          name: name,
          params: {
            id: _id,
            key: this.$route.params?.key,
          },
          query: {
            searchtext: this.textSearch ?? undefined,
            listkey: _listkey,
          },
        })
        .catch(() => {});
    },
    /**
     * این تابع آدرس URL مرتبط با شناسه داده شده را بازمی‌گرداند.
     * @param {string} _id - شناسه موجودیت
     * @returns {string} - آدرس URL
     */
    urlResolver(_id) {
      let key = this.activeEntityViewSchemaGetter?.key;

      const routeData = this.$router.resolve({
        name: "navigationView",
        params: {
          id: _id,
          key: key,
        },
        query: {
          searchtext: this.$route.query.searchtext ?? undefined,
        },
      });
      return routeData.href;
    },
    /**
     * این تابع کلاس فعال را به آیتم اضافه می‌کند.
     * @param {Object} item - آیتم موجودیت
     * @returns {boolean} - وضعیت فعال بودن آیتم
     */
    activeItemClass(item) {
      let id = item._id ?? item.id_store;
      let id_select = this.$route.params.id;

      if (
        this.$route.params.key == "rgsection" ||
        this.$route.params.key == "qasection"
      ) {
        id = item.qanon_id;
        if (this.selectedItem) {
          id_select = this.selectedItem.qanon_id;
        }
      } else {
        if (this.selectedItem) {
          id_select = this.selectedItem._id ?? this.selectedItem.id_store;
        }
      }

      return id_select == id;
    },
    /**
     * این تابع کلاس "active" را به آیتمی که کاربر بر روی آن کلیک کرده است اضافه می‌کند و از بقیه آیتم‌ها حذف می‌کند.
     */
    appendclass() {
      const listItems = document.querySelectorAll(".item");

      listItems.forEach(function (item) {
        item.addEventListener("click", function () {
          // حذف کلاس "active" از همه المان‌های لیست
          listItems.forEach(function (item) {
            item.classList.remove("active");
          });

          // اضافه کردن کلاس "active" به المانی که کاربر بر روی آن کلیک کرده است
          this.classList.add("active");
        });
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.text-title {
  font-size: 13px;
  text-decoration: none;
  color: #465a71;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  padding: 0.3em;
}
.navigation {
  height: calc(100% - 5em);
  overflow: auto;
  background-color: var(--main-background-white);

  .item {
    &.active {
      .text-title {
        background-color: var(--hover-color);
      }
    }
  }
}
</style>