<template>
  <!-- #region  لیست تمام موجودیت ها   -->
  <div class="navigation mt-3">
    <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)"
          class="text-title"
          v-tooltip="getTitle(item)"
          data-bs-toggle="tooltip"
          data-placement="top"
        >
          {{ getTitle(item) }}
        </a>
      </div>
    </div>
  </div>
  <!-- #endregion -->
</template>
<script>
import { mapState, mapActions } from "pinia";
import favoriteApi from "~/apis/favoriteApi";
import { useEntityStore } from "@search/stores/entityStore";
import { useSearchStore } from "~/stores/searchStore";
import { useCommonStore } from "~/stores/commonStore";
export default {
  props: ["item"],
  // mixins: [idbUtil],
  beforeMount() {
    this.httpService = useNuxtApp()["$http"];
  },
  mounted() {
    this.refreshList();
    this.ready = true;

    // if (this.$route.query.listkey) {
    // this.getAllFromIdb();
    // } else if (this.listEntity.length == 0)
    // this.listEntity = this.userHistoryGetter[this.$route.params.key];
  },
  computed: {
    ...mapState(useEntityStore, [
      "activeEntityViewSchemaGetter",
      "activeTabGetter",
      "listEntityGetter",
    ]),
    ...mapState(useCommonStore, ["userHistoryGetter"]),
  },
  data() {
    return {
      listEntity: [],
      selectedItem: undefined,
    };
  },
  methods: {
    ...mapActions(useEntityStore, ["SET_ITEM_ENTITY"]),

    refreshList() {
      this.getList();
      //  this.db =  this.getDb(this.$route.params.key);
      //  this.listEntity = this.getAllFromIdb(this.$route.params.key);
    },
    async getList() {
      let url = repoUrl()+ favoriteApi.favorite.getList;
      url = url.replace("@data_type", "history");
      url = url.replace("@offset", 0);
      url = url.replace("@limit", 30);
      url = url.replace("/@filter", "");

      this.httpService
        .getRequest(url)
        .then((res) => {
          this.listEntity = res?.hits?.hits;
          // res.hits.hits.forEach((item)=>{
          //   this.listEntity.push(item._source);
          // })
        })
        .finally(() => {
          // this.fetchingData = false;
        });
    },

    getTitle(item) {
      // if (this.activeEntityViewSchemaGetter?.entity_title)
      //   return item[this.activeEntityViewSchemaGetter.entity_title];
      return item._source.title;
    },
    /**
     * این تابع مقدار داده‌ای خاص از آیتم و کلید داده شده را بازمی‌گرداند.
     * @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 text = item._source[key];

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

      // console.log(item)

      let id = item._source?.ref_id;
      let key = item._source?.ref_key;
      // let type = 'item'
      // //"list,parent_key=qanon_id" or  "item"
      // if (item?.ref_property)
      //     properties = item?.ref_property.split(',')
      //     type = properties[0]

      let name = "navigation";
      if (key == "qasection" || key == "rgsection") {
      }

      this.$router
        .push({
          name: name,
          params: {
            id: id,
            key: key,
          },
        })
        .catch(() => {});

      // this.SET_ITEM_ENTITY(item);
      // this.appendclass();
    },
    /**
     * این تابع آدرس 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._source.ref_id;
      let id_select = this.$route.params.id;

      if (this.selectedItem) {
        id_select = this.selectedItem._source.ref_id;
      }

      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>