<template>
  <div class="m1 main-page">
    <div v-if="showMainpag">
      <div class="home-list p-3 m2" ref="myInput3" id="main">
        <div class="row mt-1">
          <Breadcrumbs
            class="m-start mt-2 Breadcrumbs"
            style="font-size: 12px"
          />
        </div>

        <div class="row mt-2">
          <div
            class="col-md-12 col-sm-12 d-flex"
            style="justify-content: space-around"
          >
            <button
              v-if="listGetter && listGetter.length"
              :class="{ 'text-primary borderBottom': showNavigation }"
              type="button"
              class="popUp-tab__clear btn"
              style="font-size: 12px"
              @click.prevent="showNavigation = true"
            >
              پیمایش
            </button>
            <button
              :class="{ 'text-primary borderBottom': !showNavigation }"
              type="button"
              class="popUp-tab__clear btn"
              @click.prevent="showNavigation = false"
              style="margin-right: -20px; font-size: 12px"
            >
              فهرست
            </button>
            <button
              title="بستن"
              @click="showPanel()"
              type="button"
              class="popUp-tab__clear btn"
              style="margin-right: -20px"
            >
              <span class="tavasi tavasi-Component-21--1"></span>
            </button>
          </div>
        </div>
        <hr />
        <div class="row" style="margin-top: 1.25rem !important">
          <div class="col-md-12">
            <div v-if="listGetter && listGetter.length">
              <div v-if="showNavigation">
                <div class="navigation">
                  <div
                    v-if="listGetter"
                    v-for="(item, key) in listGetter"
                    :key="key"
                    class="item"
                    :class="{ Active: activeItemClass(item) }"
                  >
                    <div
                      class="d-flex position-relative text-10 mt-2 item-navigation"
                    >
                      <a
                        @click.prevent="showtext(item, key)"
                        :href="item.branch"
                        class=""
                        :title="item.branch"
                        style="
                          font-size: 12px;
                          text-decoration: none;
                          color: black;
                        "
                      >
                        <i class="tavasi tavasi-Component-149--3 ml-1"></i>
                        {{ item.title }}
                      </a>
                    </div>
                  </div>

                  <!-- <div
                  v-for="(item, index, key) in items"
                  :id="item.id"
                  :key="item.id"
                  class="item"
                >
                  <div
                    class="d-flex position-relative text-10 mt-2"
                    :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"
                      style="font-size: 12px; text-decoration: none"
                    >
                      <i class="tavasi tavasi-Component-149--3 ml-1"></i>
                      {{ item.title }}
                    </a>
                  </div>
                </div> -->
                </div>
              </div>
              <div v-else>
                <div class="navigation mt-3" style="max-height: 230px">
                  <div
                    class="text-truncate"
                    style="max-width: 200px; font-size: 12px"
                    v-html="textlists"
                  ></div>
                </div>
              </div>
            </div>
            <div v-else>
              <div class="navigation mt-3" style="max-height: 230px">
                <div
                  class="text-truncate"
                  style="max-width: 200px; font-size: 12px"
                  v-html="textlists"
                ></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- <div v-else>
        <button  @click="showpag=true">
          <span class="tavasi tavasi-menu"></span>
        </button>
      </div> -->
    <div v-else>
      <div class="button-show">
        <div class="button-main">
          <button @click="showfilter()">
            <span class="tavasi tavasi-Component-158--5"></span>
          </button>
        </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();
    this.listMindex();
    this.list();
  },
  data() {
    return {
      id: this.$route.params.id,

      searchText: this.$route.params.searchtext,
      statuspag: 1,
      showpag: true,
      showMainpag: true,
      showNavigation: true,
      prevActiveIndex: 0,
      loading: false,
      fetchingData: false,
      items: [],
      lists: "",
      textlists: "",
      // 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",
    ]),
  },
  watch: {
    selectedItemGetter(newVal) {
      this.listMindex();
    },
  },

  methods: {
    ...mapActions(["sidebarCollapsedSetter"]),
    ...mapActions("list", [
      "SET_IS_RETURN_FROM_ITEM_SHOW_PAGE",
      "SET_SELECTED_ITEM",
      "SET_LIST",
    ]),
    activeItemClass(item) {
      if (item.id_store || item._id)
        return item.id_store == this.id || item._id == this.id;
    },
    //newMehdi
    list() {
      const storedList = localStorage.getItem("myList");
      if (storedList) {
        const myList = JSON.parse(storedList);
        this.SET_LIST(myList);
      } else {
        console.log("No list found in localStorage.");
      }
    },
    showtext(item, key) {
      // let items = this.listGetter[key].mindex;
      // let cloneItem = structuredClone(item);
      // cloneItem = { ...item,mindex:items};

      // this.SET_SELECTED_ITEM(cloneItem);

      this.SET_SELECTED_ITEM(item);
      this.appendclass();
    },
    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");
        });
      });
    },

    //newMehdi

    getHighlight(text) {
      if (window.location.href.includes("search")) {
        var words = this.searchText.split(" ");

        var index = 1;
        words.forEach((w) => {
          if (w == "" || w == " ") {
            return;
          }
          let classname = `searchHilight${index}`;
          text = text.replaceAll(
            w,
            "<span class='" + classname + "'>" + w + "</span>"
          );
          var w1 = this.normalize(w);
          if (w1 != w) {
            text = text.replaceAll(
              w1,
              "<span class='" + classname + "'>" + w1 + "</span>"
            );
          }
          index = index + 1;
          if (index > 5) index = 1;
        });
        return text;
      } else {
        return;
      }
    },
    normalize(item) {
      item = item.replaceAll("،", "");
      item = item.replaceAll(":", "");
      item = item.replaceAll(".", "");

      item = item.replaceAll("ک", "ك");
      item = item.replaceAll("ی", "ي");
      item = item.replaceAll("إ", "ا");
      item = item.replaceAll("أ", "ا");
      item = item.replaceAll("آ", "ا");
      item = item.replaceAll("ة", "ت");
      return item;
    },

    // mehdi

    showPanel() {
      // this.$emit("hide-panel");
      this.$emit("statusPagTest1", (this.statuspag = 2));
      this.showMainpag = false;

      // this.showpag= false;
    },
    showfilter() {
      this.$emit("statusPagTest1", (this.statuspag = 1));
      // this.$refs.myInput3.classList.remove("d-md-none");
      // document.getElementById("main").classList.toggle("d-main-none");
      // document.getElementById("main").style.display = "inline-block";
      this.showMainpag = true;
    },
    listMindex(key) {
      if (this.selectedItemGetter !== undefined) {
        if (window.location.href.includes("search")) {
          var list = this.getHighlight(this.selectedItemGetter.mindex).split(
            "\n"
          );
          var tt = "";
          list.forEach((list) => {
            tt = tt + "<p>" + list + "</p>";
          });
          this.textlists = tt;
        } else {
          var list = this.selectedItemGetter.mindex.split("\n");
          var tt = "";
          list.forEach((list) => {
            tt = tt + "<p>" + list + "</p>";
          });
          this.textlists = tt;
        }
      }
    },
    // showfilter() {
    //   this.$ref.myInput.classList.remove("hide");

    //   this.showpag1=true
    // },
    // hidefilter() {
    //   this.$ref.myInput.classList.add("hide");

    //   this.showpag1=false
    // },

    // mehdi
    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;
    },
    showParagraphs1(item, key) {
      this.$emit("show-paragraph1", item);
    },

    // 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: 250px;
  width: auto;
  height: 180px;

  &.show-list-panel {
    right: 0px !important;
  }
}

.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 {
  }
}

//mehdi
.close {
  width: 20px;
}

.m2 {
  // background-color: red;
  position: relative;

  &::before {
    content: "";
    height: 35em;
    border-left: solid #f1f1f1 1px;
    position: absolute;
    top: 15px;
    left: 0px;
    right: 0px;
    bottom: 0px;
  }
}
.borderBottom {
  position: relative;

  &::before {
    content: "";
    border-bottom: solid #00b6e3 2px;
    position: absolute;
    top: 31px !important;
    left: 0px;
    right: 0px;
    bottom: 0px;
  }
}
hr {
  margin: 0px;
}
.navigation {
  overflow-y: scroll;
  width: 200px;
  height: 70vh;

  max-width: 300px;
  .item {
    position: relative;
    top: 10px;

    .item-navigation a:hover {
      color: #00b6e3 !important;
    }
  }
}
.lists {
  overflow-y: scroll;
}
.borderBottom::before {
  content: "";
  border-bottom: solid #00b6e3 2px;
  position: absolute;
  top: 46px;
  left: 0px;
  right: 0px;
  bottom: 0px;
}
.ctive {
  position: relative;
  background-color: #d8f8fd;
  text-decoration: none;
}
.Active {
  //text-decoration: none;
  color: #00b6e3 !important;
  .item-navigation a {
    color: #00b6e3 !important;
  }
}

.Breadcrumbs {
  //width: 230px;
  margin: 2px auto;
  position: relative;
  right: 10px;
}

.btnHide svg {
  transform: rotate(180deg);
}
.button-main {
  position: relative;

  & button {
    border: 0px;
    background-color: #f8f8f8;
    text-align: center;
    & span {
      color: #333238;
    }
  }
}

@media (min-width: 992px) {
  .menu-bar-content {
    max-width: 220px !important;
  }
  .d-main-none {
    display: none;
  }
  .button-main {
    top: 5px;
    right: 10px;
  }
}
@media only screen and (min-width: 768px) and (max-width: 991.98px) {
  .Breadcrumbs {
    position: relative !important;
    top: 0px !important;
  }
  .menu-bar-content {
    max-width: 220px !important;
    position: relative;
    top: 0px;
    right: 0px;
  }
  .navigation {
    width: 200px !important;
    & div {
      width: 190px !important;
    }
  }
  .hide {
    display: none;
  }
  .d-main-none {
    display: none;
  }
  .button-show {
  }
  .button-main {
    top: 20px;
    right: 53px;
  }
  .main-page {
    position: fixed;
    right: 0rem;
    background-color: #fff;
    z-index: 9;
    height: 39rem;
    margin: 0px;
  }
}

@media only screen and (min-width: 576px) and (max-width: 766.98px) {
  .Breadcrumbs {
    position: relative !important;
    top: 0px !important;
  }

  .navigation {
    width: 200px !important;
    & div {
      width: 190px !important;
    }
  }
  .menu-bar-content {
    max-width: 220px !important;
    position: fixed;
    top: 0px;
    right: 0px !important;
    background-color: #fff;
    z-index: 999999;
  }
  .button-main {
    display: none;
  }
  .main-page {
    position: fixed;
    right: 0rem;
    background-color: #fff;
    z-index: 9;
    height: 39rem;
    margin: 0px;
  }
}
@media (max-width: 575.98px) {
  .Breadcrumbs {
    position: relative !important;
    top: 0px !important;
  }

  .menu-bar-content {
    max-width: 220px !important;
    position: relative;
    top: 0px;
    right: 0px !important;
    background-color: #fff;
  }
  .navigation {
    width: 200px !important;
    & div {
      width: 190px !important;
    }
  }
  .menu-bar-content {
    max-width: 220px !important;
    position: fixed;
    top: 0px;
    right: 0px !important;
    background-color: #fff;
    z-index: 9999999;
  }
  .button-main {
    display: none;
  }
  .main-page {
    position: fixed;
    right: 0rem;
    background-color: #fff;
    z-index: 9;

    height: 39rem;
    margin: 0px;
  }
}

//mehdi
</style>
