<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 />

    <div class="home-list__header pt-3 pb-0">
      <div class="flex-grow-1">
        <form
          class="search-form 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 mr-1"-->
              <!--                @change="getList()"-->
              <!--              >-->
              <!--                <option-->
              <!--                  v-can="'subject_view'"-->
              <!--                  v-for="project in projects"-->
              <!--                  :key="project.id"-->
              <!--                  :value="project.id"-->
              <!--                >-->
              <!--                  {{ project.title }}-->
              <!--                </option>-->
              <!--              </select>-->

              <div class="context-menu-dropdown">
                <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"
                      @click.prevent="showReplaceInput = !showReplaceInput"
                      type="button"
                    >
                      <i class="tavasi tavasi-Component-78--9---2"
                        ><span class="path1"></span><span class="path2"></span
                      ></i>
                      جستجو
                    </button>
                    <button
                      v-can="'subject_new'"
                      data-toggle="modal"
                      data-target="#list-modal"
                      @click.prevent="openModal()"
                      class="dropdown-item text-right"
                      type="button"
                    >
                      <!-- <span class="tavasi tavasi-add"></span> -->
                      <span class="tavasi tavasi-Component-133--1"></span>
                      پوشه جدید
                    </button>
                  </div>
                </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">
        <div class="last-search-content h-100" @scroll="loadMore">
          <div v-if="list.length">
            <div class="meta-list mb-3 prev-level" v-if="meta.length">
              <!--              <span style="font-size: 1.1rem;" class="tavasi tavasi-Component-71&#45;&#45;1 ml-2"></span>-->
              <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>
            <!-- mehdi -->
            <div class="select-export-container" v-if="list?.length">
              <div class="dropdown">
                <button
                  class="btn btn-outline-light border-0 dropdown-toggle"
                  type="button"
                  data-toggle="dropdown"
                  aria-expanded="false"
                >
                  <span class="tavasi tavasi-excel-file-2 ml-1"></span>
                </button>
                <div class="dropdown-menu">
                  <button
                    class="dropdown-item"
                    type="button"
                    :disabled="fetchingDataForExport"
                    @click="exportJsonToExcel('current')"
                    value="current"
                  >
                    جاری
                  </button>
                  <button
                    class="dropdown-item"
                    type="button"
                    :disabled="fetchingDataForExport"
                    @click="exportJsonToExcel('all')"
                    value="all"
                  >
                    همه
                  </button>
                </div>
              </div>
            </div>
            <!-- mehdi -->
            <div
              :id="item.id"
              v-for="(item, index) in list"
              :key="item.title"
              class="item"
            >
              <draggable
                handle=".my-handle"
                group="people"
                @add="onDrop"
                @choose="handleChoose"
                @unchoose="handleUnChoose"
                @change="handleChange"
                :list="list"
              >
                <div
                  class="d-flex position-relative"
                  :class="{ 'is-selected': item?.isSelected }"
                >
                  <rename-form
                    v-if="
                      item?.editMode &&
                      item?.parentComponent === 'subjectPanel' &&
                      !isGuest
                    "
                    :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 class="my-handle">
                        <svg
                          v-if="item.children?.length"
                          class="icon icon-Component-154--22 color-costom ml-1"
                        >
                          <use xlink:href="#icon-Component-154--22"></use>
                        </svg>
                        <svg
                          v-else
                          class="icon icon-Component-133--1 color-costom ml-1"
                        >
                          <use xlink:href="#icon-Component-133--1"></use>
                        </svg>
                      </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 || item.children.length === 0"
                          class="tavasi tavasi-Component-149--3 ml-1"
                        ></i>
                        <!--                  <i v-if="item.children === 0" class="tavasi tavasi-Component-149&#45;&#45;3"></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 && !isGuest">
                      <!-- v-can="'list_edit'" -->
                      <context-menu
                        :parentComponent="'subjectPanel'"
                        :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>
                <ul v-if="Array.isArray(item.children)" class="children">
                  <li
                    class="position-relative"
                    v-for="(child, childIndex) in item.children"
                    :key="child.title"
                  >
                    <rename-form
                      v-if="
                        child?.editMode &&
                        child?.parentComponent === 'subjectPanel' &&
                        !isGuest
                      "
                      :title="child.title"
                      :loading="loading"
                      @closeForm="child.editMode = false"
                      @saveChanges="editItem($event, child, item.children)"
                    ></rename-form>
                    <div v-else>
                      <a
                        @click.prevent="getItems(child, childIndex)"
                        :href="child.title"
                        class="title"
                        :title="child.title"
                      >
                        <span class="my-handle">
                          <svg
                            v-if="child.children === 0"
                            class="icon icon-Component-149--3 ml-1"
                          >
                            <use xlink:href="#icon-Component-149--3"></use>
                          </svg>

                          <!-- <i
                          v-if="child.children === 0"
                          class="tavasi tavasi-Component-149--3 ml-1"
                        ></i> -->

                          <svg
                            v-else
                            class="icon icon-Component-360--2 text__14 ml-1"
                          >
                            <use xlink:href="#icon-Component-360--2"></use>
                          </svg>
                          <!-- <i
                          v-else
                          class="tavasi tavasi-Component-360--58 text__14 ml-1"
                        >
                          <span class="path1"></span>
                          <span class="path2"></span>
                        </i> -->
                        </span>
                        {{ child.title }}
                      </a>
                      <div v-if="!child?.isSelected && !isGuest">
                        <context-menu
                          :parentComponent="'subjectPanel'"
                          :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>
                </ul>
              </draggable>
            </div>
          </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 && !isGuest">
      <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="s12 icon-chevron-double-lg-right">
          <use
            href="assets/common/img/icons.svg#chevron-double-lg-right"
          ></use>
        </svg>
        <span class="collapse-text mr-2">بستن</span>
      </button>
    </div>
  </div>
</template>

<script>
import apis from "~/apis/listApi";

import { listMixin } from "~/list/mixins/listMixin";
import { searchMixin } from "~/list/mixins/searchMixin";
import { dragDropMoveMixin } from "~/list/mixins/dragDropMoveMixin";
import { mapState } from "pinia";

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();
      }
    }
  },
  deactivated() {
    // console.log("deactivated");
  },
  computed: {
    ...mapState(["isGuest"]),
  },
  watch: {
    isReturnFromItemshowPageGetter(id) {
      this.getList(id);
    },
    // $route: {
    //   handler(route) {
    //     this.storeUserLastState(route.name);
    //   },
    //   nested: true,
    //   immediate: true,
    // },
  },
  data() {
    return {
      cached: false,

      subjects: [],
      listTypeId: 0,
      currentPageName: "subject",
    };
  },
  methods: {
    async storeUserLastState(route) {
      let payLoad = {
        lastRouteName: route,
        lastRouteUrl: route,
        list: {
          subjects: {
            sorting: this.sorting,
            pagination: this.pagination,
            project: this.selectedProjectGetter,
            item: this.selectedItemGetter,
            listId: this.listIdGetter,
            list: this.listGetter,
          },
        },
      };
      return await this.storeState(payLoad);
    },
    getProjects() {
      this.checkPermissions({ permission: "subject_view", _this: this })
        .then(() => {
          const payload = {
            isown: 3,
            sortby: "created",
            offset: 0,
            limit: 100,
            type: 3, // موضوع
          };

          ApiService.formData(apis.projects.list, payload).then((res) => {
            const firstProject = res.data.data[0];
            firstProject.meta = JSON.parse(firstProject.meta);
            // console.log(firstProject.table_columns);
            firstProject.table_columns = JSON.parse(firstProject.table_columns);

            this.SET_SELECTED_PROJECT(firstProject);

            this.$emit("list-changed", {
              // listId: undefined,
              // projectId: this.subjectProject.id,
            });

            this.projects = res.data.data;

            this.getList();
            this.$emit("can-view", true);
          });
        })
        .catch(() => {
          this.$emit("can-view", false);
        });
    },
    getList(parent = 0) {
      const payload = {
        projectid: this.selectedProjectGetter?.id,
        parent: parent,
        sortby: "id",
        offset: 0,
        limit: 100,
        listtype: this.listTypeId,
      };

      let self = this;

      ApiService.formData(apis.subject.list, payload).then((res) => {
        self.list = res.data.data;
        self.meta = res.data?.meta ?? [];

        self.$emit("list-changed", {
          subjectId: parent,
          listTypeId: self.listTypeId,
        });

        if (parent == 0) {
          self.SET_LIST_ID(self.list[0].id);
        } else {
          self.SET_LIST_ID(parent);
        }

        self.SET_LIST(self.list[0]);
        self.getListItem(self.list[0].id, 0);
        self.switchActive(self.list[0]);

        // if (res.data.meta)
        //   this.meta = res.data.meta.filter((item, index) => index > 0);
      });
    },
    addItemToList(itemId, listId) {
      const payload = {
        itemid: itemId,
        listid: listId,
        listtype: this.listTypeId,
        projectid: this.selectedProjectGetter?.id,
      };

      ApiService.formData(apis.subject.add, payload).then((res) => {
        // this.getList()

        this.mySwalToast({
          title: "تبریک",
          html: res.data.message,
          icon: "success",
        });
      });
    },
    editItem(newTitle, subject, subjectArray) {
      if (this.loading) return;
      this.loading = true;

      const model = {
        title: newTitle,
        subjectid: subject.id,
        projectid: this.selectedProjectGetter?.id,
        // ,newparent: subject.parent ? subject.parent : 0, // نیاز نیست
      };

      ApiService.formData(apis.subject.edit, model)
        .then((res) => {
          subject.editMode = false;

          const resultIndex = subjectArray.findIndex(
            (item) => subject.id === item.id
          );

          if (resultIndex > -1) {
            this.$set(subjectArray[resultIndex], "title", newTitle);
          }

          this.mySwalToast({
            title: "موفق",
            html: res.data.message,
            icon: "success",
          });
        })
        .catch((err) => {
          this.mySwalToast({
            title: "خطا!!!",
            html: err?.message,
            icon: "error",
          });
        })
        .finally(() => (this.loading = false));
    },

    // onDrop(ev, list) {
    //   const itemId = ev.item["_underlying_vm_"]["id"];
    //   const listId = list.id;

    //   this.addItemToList(itemId, listId);
    // },
    // onEnd(ev) {
    // },
  },

};
</script>

<style scoped lang="scss">
.my-handle {
  color: #ccc;
}
.menu-bar__content {
  position: static;
  flex: 1 1 100%;
  max-width: 305px;
  width: auto;
  &.show-list-panel {
    right: 0 !important;
  }
}

.home-list__content {
  /*max-height: calc(100vh - 12em);*/
  height: calc(100vh - 8em);
  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
.select-export-container {
  position: relative;
  top: -5px;
  left: 12rem;
  //lefr: 0px;
}
//mehdi
</style>
