<template>
  <div class="menu-bar__content menu-bar-content home-list p-3">
    <!-- <button @click="toggleSidebarMenu()" type="button" class="btn sidebar-toggler"
      :class="{'expanded' : isSidebarCollapsed}">
      <img src="assets/common/img/arrow-bar-left.svg" class="img-fluid" alt="">
    </button> -->

    <Breadcrumbs class="m-start mt-2" />

    <div
      class="home-list__content scroll-needed mt-4"
      :class="{ loading: loading }"
    >
      <div class="last-search h-100">
        <div class="last-search-content h-100" @scroll="loadMore">
          <div v-if="items && items.length">
            <div class="meta-list mb-3 prev-level" style="background:#F6F6F6">
              <a
                @click.prevent="goToListPage()"
                :href="listGetter.title"
                class="meta-list-item text__14"
                :title="listGetter.title"
              >
                {{ listGetter.title }}
              </a>
            </div>
            <div
              v-for="(item, index, key) in items"
              :id="item.id"
              :key="item.id"
              class="item"
            >
              <div
                class="d-flex position-relative"
                :class="{
                  'is-selected': item.active ?? false,
                }"
              >
                <a
                  :class="{ active: item.active ?? false }"
                  @click.prevent="showParagraphs(item, index, key)"
                  :href="item.title"
                  class="title"
                  :title="item.title"
                >
                  <i class="tavasi tavasi-Component-149--3 ml-1"></i>
                  {{ item.title }}
                </a>
              </div>
            </div>
          </div>
          <no-data v-else />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from "pinia";
import apis from "~/apis/listApi";

export default {
  props: {
    listPanelUrl: {
      default: "",
    },
  },
  emits: ["show-paragraph"],
  mounted() {
    this.getListItem();
  },
  data() {
    return {
      prevActiveIndex: 0,
      loading: false,
      fetchingData: false,
      items: [],
      pagination: {
        pages: 0,
        total: 0,
        page: 1,
        offset: 0, // page * per_page
        limit: 50, //per_page
      },
    };
  },
  computed: {
    ...mapState(["isSidebarCollapsed"]),
    ...mapState("list", [
      "selectedProjectGetter",
      "listIdGetter",
      "selectedItemGetter",
      "listGetter",
    ]),
  },
  methods: {
    ...mapActions("list", ["SET_IS_RETURN_FROM_ITEM_SHOW_PAGE"]),
    showParagraphs(item, index) {
      this.$emit("show-paragraph", item);

      this.$set(this.items[this.prevActiveIndex], "active", false);
      this.$set(this.items[index], "active", true);

      this.prevActiveIndex = index;
    },

    getListItem() {
      if (this.fetchingData) return;
      this.fetchingData = true;

      const payload = {
        projectid: this.selectedProjectGetter?.id,
        item_state: this.selectedProjectGetter?.item_state,
        listid: this.listIdGetter,
        subjectid: this.listIdGetter,
        bychilds: 0,

        ...this.pagination,
        // offset: offset,
        // limit: this.pagination.limit,
      };

      let url = apis.listItem.list;

      if (this.$route.params.prevPage == "subjects")
        url = apis.subjectRelation.list;

      ApiService.formData(url, payload)
        .then((res) => {
          this.items = res.data.data;

          this.items.forEach((element, index) => {
            if (element.id == this.selectedItemGetter.id) {
              element["active"] = true;
              this.prevActiveIndex = index;
            }
          });

          this.pagination = {...this.pagination,...res.data.pagination};

        })
        .catch((err) => {
          this.mySwalToast({
            title: err.response.data.message,
            html: "",
            text: "",
            icon: "error",
          });
        })
        .finally(() => {
          this.fetchingData = false;
        });
    },
    goToListPage() {
      this.SET_IS_RETURN_FROM_ITEM_SHOW_PAGE(this.listGetter.parent);

      const routeName = this.$route.params.prevPage;

      this.$router.push({
        name: routeName,
      });
    },
    loadMore($event) {
      // const listElm = document.querySelector("#last-search");
      const listElm = $event.target;

      const vm = this;
      if (vm.busy) return;

      if (listElm.scrollTop + listElm.clientHeight >= listElm.scrollHeight) {
        this.busy = true;
        vm.pagination.offset = vm.pagination.offset + vm.pagination.limit;

        if (vm.pagination.total > vm.pagination.offset) {
          setTimeout(() => {
            vm.getListOnScroll();
          }, 300);
        } else {
          vm.mySwalToast({
            title: "کاربر محترم",

            html: "دیگر رکوردی جهت بارگزاری وجود ندارد.",
            icon: "info",
            position: "bottom-start",
          });
          vm.busy = false;
        }
      } else vm.busy = false;
    },
    getListOnScroll() {
      if (this.fetchingData) return;
      this.fetchingData = true;

      const payload = {
        projectid: this.selectedProjectGetter?.id,
        item_state: this.selectedProjectGetter?.item_state,
        listid: this.listIdGetter,
        subjectid: this.listIdGetter,
        bychilds: 0,

        ...this.pagination,
      };

      let url = apis.listItem.list;

      if (this.$route.params.prevPage == "subjects")
        url = apis.subjectRelation.list;

      ApiService.formData(url, payload)
        .then((res) => {
          this.items = [...this.items, ...res.data.data];

          this.pagination = {...this.pagination,...res.data.pagination};

        })
        .finally(() => {
          this.busy = false;
        });
    },
  },
};
</script>

<style scoped lang="scss">
.open-sub-folder {
  text-decoration: none;

  &:hover {
    background-color: #eee;
  }
}

.menu-bar__content {
  position: static;
  flex: 1 1 100%;
  max-width: 305px;
  width: auto;
  min-width: 305px;
}

.home-list__content {
  /*max-height: calc(100vh - 12em);*/
  height: calc(100vh - 8.5em);
  position: relative;
  overflow-x: hidden;
  padding-left: 0.3em;

  &.loading {
    //background-image: url('./img/item-loading.svg');
    background-repeat: repeat-y;
    background-position: top right;
    background-size: 12em;

    &::before {
      content: "";
      clear: both;

      position: absolute;
      right: 0;
      width: 0.5em;

      height: 100%;
      background-color: #fff;

      animation-name: example;
      animation-duration: 2s;
      animation-fill-mode: forwards;
      animation-iteration-count: infinite;
      animation-timing-function: ease-in-out;
    }
  }
}

.sidebar-toggler {
  right: 2.6em;

  &.expanded {
    right: 11.1em;
  }
}

.meta-list {
  display: flex;
  align-items: ceter;
  flex-wrap: nowrap;
  white-space: nowrap;
  overflow: auto;

  .meta-list-item {
  }
}
</style>