<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__header pt-3 pb-0">
      <div class="flex-grow-1">
        <form
          class="search-form rounded-3 mx-0 w-100"
          role="search"
          @submit.prevent="sendQuery"
        >
          <div class="form-group">
            <div class="d-flex">
              <multiselect
                :allow-empty="false"
                :searchable="true"
                :close-on-select="true"
                :show-labels="false"
                label="title"
                track-by="id"
                placeholder="انتخاب پروژه"
                :value="selectedProjectGetter"
                :options="projects"
                @select="selectProject"
                :hide-selected="false"
                :limit-text="
                  (count) => {
                    return `و ${count} پروژه دیگر`;
                  }
                "
                :max-height="200"
              >
              </multiselect>

              <!-- <select
                v-model="projectId"
                class="form-control combo"
                @change="getList()"
              >
                <option
                  v-for="project in projects"
                  :key="project.id"
                  :value="project.id"
                >
                  {{ project.title }}
                </option>
              </select> -->

              <div class="dropdown">
                <button
                  class="btn pl-0"
                  type="button"
                  id="dropdownMenu2"
                  data-toggle="dropdown"
                  aria-haspopup="true"
                  aria-expanded="false"
                >
                  <i class="tavasi tavasi-Component-281--1"></i>
                </button>
                <div class="dropdown-menu " aria-labelledby="dropdownMenu2">
                  <button
                    class="dropdown-item text-right d-flex align-item-center"
                    @click.prevent="showReplaceInput = !showReplaceInput"
                    type="button"
                  >
                    <i class="tavasi tavasi-Component-78--9---2 mt-1"
                      ><span class="path1"></span><span class="path2"></span
                    ></i>
                    <div class="mx-1">جستجو</div>
                  </button>
                  <button
                    v-can="'list_new'"
                    data-toggle="modal"
                    data-target="#list-modal"
                    @click.prevent="openModal()"
                    class="dropdown-item text-right d-flex align-item-center "
                    type="button"
                  >
                    <span class="tavasi tavasi-add-folder ml-1"
                      ><span class="path1"></span><span class="path2"></span
                      ><span class="path3"></span><span class="path4"></span
                      ><span class="path5"></span><span class="path6"></span
                      ><span class="path7"></span><span class="path8"></span
                    ></span>
                    <!-- <span class="tavasi tavasi-Component-133--1 mt-1"></span> -->
                    <!-- <span class="tavasi tavasi-add"></span> -->
                    <div class="mx-1">پوشه جدید</div>
                  </button>
                </div>
              </div>
            </div>
          </div>

          <div v-if="showReplaceInput" class="form-group">
            <div class="input-group">
              <input
                v-model="searchForm.query"
                type="search"
                required
                class="form-control"
                id="search-query"
                placeholder="جستجو..."
                name="search-query"
                aria-label="جستجو در اسناد، عناوین و واژگان"
                aria-describedby="basic-addon1"
                size="50"
                @keyup="sendQuery()"
                @keydown="onKeyDown()"
              />
              <div class="input-group-append">
                <button
                  @click="showReplaceInput = !showReplaceInput"
                  type="button"
                  class="input-group-text show-reset-btn"
                  id="basic-addon1"
                >
                  <i class="tavasi tavasi-Component-294--1"></i>
                </button>
              </div>
            </div>
          </div>
        </form>
      </div>
    </div>

    <div class="home-list__content scroll-needed" :class="{ loading: loading }">
      <div class="last-search h-100" id="last-search">
        <div class="last-search-content h-100" @scroll="loadMore">
          <div v-if="list && list.length">
            <div
              class="meta-list mb-3 prev-level"
              style="background:#F6F6F6"
              v-if="meta.length"
            >
              <div v-for="(metaItem, index) in meta">
                <a
                  :key="'meta' + metaItem.id"
                  @click.prevent="getParentList(metaItem.parent_id)"
                  :href="metaItem.title"
                  class="meta-list-item text__14"
                  :title="metaItem.title"
                >
                  {{ metaItem.title }}
                </a>
                <span
                  :key="'id' + metaItem.id"
                  style="font-size: 1.4rem; color:blue"
                  v-if="index < meta.length - 1"
                  class="tavasi tavasi-Component-22--1"
                ></span>
              </div>
            </div>

            <draggable
              handle=".my-handle"
              group="people"
              @add="onDrop"
              @choose="handleChoose"
              @unchoose="handleUnChoose"
              @change="handleChange"
              :list="list"
            >
              <div
                :id="item.id"
                v-for="(item, index) in list"
                :key="'id' + item.id"
                class="item"
              >
                <div
                  class="d-flex position-relative"
                  :class="{ 'is-selected': item?.isSelected }"
                >
                  <rename-form
                    v-if="
                      item?.editMode && item?.parentComponent === 'listPanel'
                    "
                    :title="item.title"
                    :loading="loading"
                    @closeForm="item.editMode = false"
                    @saveChanges="editItem($event, item, list)"
                  ></rename-form>
                  <div v-else>
                    <a
                      v-if="item.children"
                      @click.prevent="getListChildren(item, index)"
                      :href="item.title"
                      class="open-sub-folder"
                      :title="item.title"
                    >
                      <!-- <span
                        v-if="item.children?.length"
                        class="tavasi tavasi-remove"
                      ></span> -->
                      <span
                        v-if="item.children?.length"
                        class="tavasi tavasi-Component-154--22 ml-1"
                      ></span>
                      <!-- <span v-else class="tavasi tavasi-add"></span> -->
                      <span
                        v-else
                        class="tavasi tavasi-Component-133--1 color-costom ml-1"
                      ></span>
                    </a>

                    <a
                      :class="{ active: item?.active ?? false }"
                      @click.prevent="getItems(item, index)"
                      :href="item.title"
                      class="title"
                      :title="item.title"
                    >
                      <span class="my-handle">
                        <!--                  <i v-if="item.children === 0" class="tavasi tavasi-Component-149&#45;&#45;3"></i>-->
                        <i
                          v-if="!item.children || item.children.length === 0"
                          class="tavasi tavasi-Component-149--3 ml-1"
                        ></i>

                        <!--                  <i v-else class="tavasi tavasi-Component-360&#45;&#45;58">-->
                        <!--                    <span class="path1"></span>-->
                        <!--                    <span class="path2"></span>-->
                        <!--                  </i>-->
                      </span>

                      {{ item.title }}
                    </a>
                    <div v-if="!item?.isSelected">
                      <context-menu
                        v-can="'list_folder_edit'"
                        :parentComponent="'listPanel'"
                        :list="list"
                        :clickedItem="item"
                        :contextMenu="contextMenu"
                        @remove-item="removeItem(item, list)"
                        @update-order="updateOrder($event, item, list, index)"
                        @new-sub-folder="
                          openNewSubFolderModal(item, list, index)
                        "
                      >
                      </context-menu>
                    </div>
                  </div>
                </div>
                <div v-if="Array.isArray(item.children)">
                  <draggable
                    handle=".my-handle"
                    @add="onDrop"
                    group="people"
                    tag="ul"
                    class="children list-unstyled"
                    :list="item.children"
                    :id="item.id"
                  >
                    <li
                      :id="child.id"
                      class="position-relative"
                      v-for="(child, childIndex) in item.children"
                      :key="child.title"
                    >
                      <rename-form
                        v-if="
                          child?.editMode &&
                            child?.parentComponent === 'listPanel'
                        "
                        :title="child.title"
                        :loading="loading"
                        @closeForm="child.editMode = false"
                        @saveChanges="editItem($event, child, item.children)"
                      ></rename-form>
                      <div v-else>
                        <a
                          :class="{ active: child?.active ?? false }"
                          @click.prevent="getItems(child, childIndex)"
                          :href="child.title"
                          class="title"
                          :title="child.title"
                        >
                          <span class="my-handle">
                            <i
                              v-if="child.children === 0"
                              class="tavasi tavasi-Component-149--3 ml-1"
                            ></i>

                            <i v-else>
                              <span class="path1"></span>
                              <span class="path2"></span>
                            </i>
                          </span>

                          {{ child.title }}
                        </a>
                        <div v-if="!child?.isSelected">
                          <context-menu
                            v-can="'list_folder_edit'"
                            :parentComponent="'listPanel'"
                            :list="item.children"
                            :clickedItem="child"
                            :contextMenu="contextMenu"
                            @remove-item="removeItem(child, item.children)"
                            @new-sub-folde="openNewSubFolderModal(child)"
                            @update-order="
                              updateOrder(
                                $event,
                                child,
                                item.children,
                                childIndex
                              )
                            "
                          >
                          </context-menu>
                        </div>
                      </div>
                    </li>
                  </draggable>
                </div>
              </div>
            </draggable>
          </div>
          <no-data v-else />
        </div>

        <!--        <div class="last-search-footer" v-if="list.length > 0">-->
        <!--          <button class="btn last-search-more-btn" type="button">بیشتر</button>-->
        <!--        </div>-->
      </div>
    </div>

    <div v-if="showModal">
      <new-list-modal
        :apiName="currentPageName"
        :selectedItem="selectedItem"
        :parentId="parentId"
        @close-modal="closeModal"
        @delete-item="updateList"
        @update-list="updateList"
      />
    </div>

    <div class="d-md-none hide-list-panel">
      <button
        name="button"
        type="button"
        class="toggle-mobile-nav"
        @click="$emit('hide-panel')"
      >
      <svg class="icon icon-chevron-double-right">
                  <use xlink:href="#icon-chevron-double-right"></use>
                </svg>
        <span class="collapse-text mr-2">بستن</span>
      </button>
    </div>
  </div>
</template>

<script>
import { listMixin } from "~/list/mixins/listMixin";
import { searchMixin } from "~/list/mixins/searchMixin";
import { dragDropMoveMixin } from "~/list/mixins/dragDropMoveMixin";

export default {
  props: ["items"],
  mixins: [searchMixin, listMixin, dragDropMoveMixin],
  emits: ["list-changed", "list-item-changed"],
  activated() {
    if (this.cached === false) {
      this.cached = Date.now();
    } else {
      // time diff since cache, in seconds
      const diff = (Date.now() - this.cached) / 1000;

      // if cache is older than 30 seconds, invalidate
      if (diff > 1800) {
        this.cached = false;
        this.getProjects();
      }
    }
  },
  mounted() {
    this.$refs.topheader.modetab = 2;
    this.$refs.topheader.state = 2;
    if (this.tq != "") {
      var item = this.tq;
      this.checkMultiword(item);
      this.$refs.topheader.setSearchLine(this.tq);
      this.$refs.content.setTextSearch(this.tq, this.countInPage);
      this.getQuery();
    }
  },
  deactivated() {
    // console.log("deactivated");
  },

  watch: {
    isReturnFromItemshowPageGetter(id) {
      this.getList(id);
    },
    // $route: {
    //   handler(route) {
    //     this.storeUserLastState(route.name);
    //   },
    //   nested: true,
    //   immediate: true,
    // },
  },

  data() {
    return {
      cached: false,
      currentPageName: "list",
      tq: this.q,
      filterUrl: "",
      loading: false,
      showSummary: false,
      countInPage: 10,
      currentItem: [],
      searchType: "",
      searchCode: "all",
      ismultword: false,
      iscode: false,
      page: 0,

      cloneItems: [],
      typingTimer: 0,
      showReplaceInput: false,
      doneTypingInterval: 1000,
      searchForm: {
        query: "",
      },
    };
  },

  methods: {
    sendQuery() {
      // todo: show loading.
      // todo: send query and show result.
      // todo: hide loading.

      clearTimeout(this.typingTimer);
      this.typingTimer = setTimeout(() => {
        // request data from api
      }, this.doneTypingInterval);
    },
    onKeyDown() {
      clearTimeout(this.typingTimer);
    },
    resetForm() {
      this.searchForm.query = "";
      this.searchForm.replaceWith = "";
      this.cloneItems = structuredClone(this.items);
    },
    
    searchTyping(type) {
      this.searchType = type;
    },
    searchCoding(code) {
      this.searchCode = code;
    },
    resetOptions() {
      this.page = 0;
      this.filterUrl = "";
      this.$refs.filterlist.resetFilter();
    },
    showfilter: function() {
      this.$refs.filterlist.showfilter();
    },
    checkMultiword(item) {
      this.ismultword = false;
      if (item == null || item == "") return;
      var ww = item.split(" ");
      this.iscode = /^\d+$/.test(item);
      if (this.iscode == false) this.ismultword = item.split(" ").length > 1;

      this.$refs.topheader.setOptions(this.ismultword, this.iscode);
    },
    searchStart: function(item) {
      if (item != null) {
        item = item.trim();
        this.tq = item;

        this.checkMultiword(item);
        this.$refs.content.setTextSearch(item, this.countInPage);
      }
      this.resetOptions();
      this.getQuery();
    },
    changePaging: function(item) {
      this.page = item;
      this.getQuery(true);
    },
    hideSummary: function() {
      this.showSummary = false;
    },
    changeCurrent: function(item) {
      if (item == this.currentItem) this.showSummary = !this.showSummary;
      else this.showSummary = true;
      this.currentItem = item;
      this.$refs.summary.setInfo(item);
    },
  },
};
</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;

  &.show-list-panel {
    right: 0 !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 {
  }
}
</style>
