<template>
  <ResearchLayout :menu="menu">
    <section class="myResearches" :class="{ expanded: !isSidebarCollapsed }">
      <div class="container-fluid">
        <div class="row align-items-end border-bottom">
          <div class="col-12 pt-3">
            <div class="row align-items-center mb-3">
              <div class="col col-lg-auto order-1">
                <div class="d-flex align-items-center">
                  <button
                    name="button"
                    type="button"
                    class="toggle-mobile-nav dropdown-hamburger d-md-none"
                    @click.prevent="toggleSidebarMenu()"
                  >
                    <span class="sr-only">باز کردن منوی کنار</span>
                    <svg class="s18" data-testid="sidebar-icon">
                      <use href="assets/common/img/icons.svg#sidebar"></use>
                    </svg>
                  </button>

                  <NuxtLink
                    :to="{
                      name: 'defaultRoute',
                    }"
                    classes="btn me-3"
                  >
                    <img
                      :src="logo"
                      :alt="appLongTitle()"
                      class="img-fluid logo"
                      style="max-width: 3.3em"
                    />
                  </NuxtLink>
                </div>
              </div>

              <div class="col-12 col-lg-6 order-3 order-lg-2">
                <div class="search-container">
                  <div
                    class="input-group"
                    @keyup="keyupdiv"
                    style="box-shadow: 0 1px 3px rgba(23, 23, 23, 0.24)"
                  >
                    <!-- <VMenu class="my-vmenu">
                      <div class="input-group-prepend">
                        <button
                          type="button"
                          @click.prevent="showAdvancedSearch"
                          title="جستجوی پیشرفته"
                          class="btn"
                        >
                          پیشرفته؟
                        </button>
                      </div>

                      <slot name="popper">
                        <div
                          class="my-tooltip-content"
                          v-html="
                            getHtmlTooltip2(
                              'research',
                              'research_advance',
                              'TKVLBY8BPd2Jp_XrBZq0'
                            )
                          "
                        ></div>
                      </slot>
                    </VMenu> -->

                    <input
                      type="text"
                      v-model="textSearch"
                      @keyup.enter="slmSearchStart()"
                      @click="showHisory()"
                      class="form-control"
                      id="research"
                      placeholder="جستجو در تمام تحقیقات"
                      autocomplete="off"
                      ref="searchinput"
                      @focus="inputfocused = true"
                      @blur="inputfocused = false"
                      v-focus
                    />
                    <div class="input-group-append">
                      <button
                        v-tooltip="'جستجو در خاصیت(فیلد) ویژه'"
                        class="btn dropdown-toggle"
                        type="button"
                        data-bs-toggle="dropdown"
                        aria-haspopup="true"
                        aria-expanded="false"
                      >
                        <!-- <span class="navItemlabel">
                        {{ domainActiveGetter?.label }}
                      </span> -->
                      </button>
                      <div class="dropdown-menu">
                        <button
                          v-for="(navItem, index) in searchDomain"
                          :key="index"
                          type="button"
                          class="dropdown-item"
                          @click.prevent="setSelectedNavItem(navItem)"
                        >
                          {{ navItem.label }}
                        </button>
                      </div>

                      <button
                        v-tooltip="'جستجو در خاصیت(فیلد) ویژه'"
                        @click.prevent="slmSearchStart()"
                        class="btn btn-primary search-icon"
                      >
                        <svg class="icon icon-Component-198--1">
                          <use xlink:href="#icon-Component-198--1"></use>
                        </svg>
                      </button>
                    </div>

                    <div
                      v-if="showItem == 3 && listAutocomplate.length"
                      class="search-page__result"
                      :class="{
                        show: listAutocomplate.length,
                      }"
                      v-click-outside="onClickOutside"
                    >
                      <ul ref="aut_ul">
                        <li v-for="(item, i) in listAutocomplate" :key="i">
                          <a @click.prevent="selectAutocomplate(item.text)">
                            <span
                              class="text__14"
                              v-html="getHighlight(item.text)"
                            ></span>
                          </a>
                        </li>
                      </ul>
                    </div>

                    <div
                      v-if="showItem == 1"
                      class="search-page__result"
                      :class="{
                        show: historySearch.length,
                      }"
                      v-click-outside="onClickOutside"
                    >
                      <div>
                        <div class="scrollbar">
                          <ul ref="his_ul">
                            <li v-for="(item, i) in historySearch" :key="i">
                              <a @click="selectHistorySearch(item)">
                                <img
                                  src="assets/common/img/Component 359 – 2.svg"
                                  alt=""
                                />
                                <span class="text__14">{{ item }}</span>
                              </a>
                              <a @click="removeHistorySearch(i)" class="close">
                                <svg class="icon icon-Component-294--1">
                                  <use
                                    xlink:href="#icon-Component-294--1"
                                  ></use>
                                </svg>
                              </a>
                            </li>
                          </ul>
                        </div>
                      </div>
                    </div>

                    <div
                      v-show="showItem == 2"
                      :class="{ show: showItem == 2 }"
                      class="search-page__filters"
                    >
                      <!-- <form action="">
                      <div class="item">
                        <input
                          type="checkbox"
                          name="doc-priority"
                          id="doc-priority"
                          v-model="setRankCheck"
                        />
                        <label for="doc-priority" class="text__14"
                          >جستجو با اولویت متن اسناد</label
                        >
                      </div>
                      <div class="item">
                        <input
                          type="checkbox"
                          name="search-in"
                          id="search-in"
                        />
                        <label for="search-in" class="text__14"
                          >جستجو فقط در
                        </label>
                        <div class="select">
                          <select name="" id="">
                            <option
                              value=""
                              v-for="(item, i) in setListItems"
                              :key="i"
                            >
                              {{ item }}
                            </option>
                          </select>
                          <span class="drop-down">
                            <img
                              src="assets/common/img/Path 13419.svg"
                              alt=""
                            />
                          </span>
                        </div>
                      </div>
                    </form> -->
                    </div>
                  </div>
                </div>
              </div>
              <div class="col-auto col-lg order-2 order-lg-3">
                <div class="d-flex justify-content-end" v-if="!isMajlesBuild">
                  <user-avatar-dropdown class="">
                    <NuxtLink
                      :to="{ name: 'searchAbout' }"
                      class="dropdown-item"
                      >درباره ما</NuxtLink
                    >
                    <NuxtLink
                      :to="{ name: 'searchConnect' }"
                      class="dropdown-item"
                      >تماس با ما</NuxtLink
                    >
                  </user-avatar-dropdown>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="row">
          <div
            v-if="showButton"
            class="circle--button"
            @click.prevent="changeHideFilter(0)"
            ref="circle"
          >
            <svg
              class="s12 icon-chevron-double-lg-left"
              data-testid="chevron-double-lg-left-icon"
            >
              <use
                href="assets/common/img/icons.svg#chevron-double-lg-left"
              ></use>
            </svg>
          </div>

          <div
            class="col-8 col-lg-2 filter-list-container"
            :class="{ expanded: showFilter }"
            ref="showFilter"
          >
            <div class="mobile-mode">
              <button class="btn" @click.prevnet="showFilter = !showFilter">
                <svg
                  v-if="showFilter"
                  class="icon icon-chevron-double-right ms-1"
                >
                  <use xlink:href="#icon-chevron-double-right"></use>
                </svg>
                <svg v-else class="icon icon-chevron-double-left">
                  <use xlink:href="#icon-chevron-double-left"></use>
                </svg>
                <!-- بستن فیلتر -->
              </button>
            </div>
            <ResearchFilterList
              v-if="researchSchemaGetter"
              @filterUpdate="filterUpdate"
              @changeHideFilter="changeHideFilter($event)"
              ref="filterlist"
              :lastSearchInListMode="lastSearchInListMode"
              :changePageFilter="changePageFilter"
              :activeTabGetter="researchSchemaGetter[0]"
              class="filterList"
            ></ResearchFilterList>

            <!-- <AdvancedSearch
            v-if="researchSchemaGetter && researchSchemaGetter[0].advance"
            v-show="hideAdvancedSearch"
            @searchStart="slmSearchStart($event)"
            @closeAdvancedSearch="closeAdvancedSearch"
            @set-query-advanced="setQueryAdvanced($event)"
          ></AdvancedSearch> -->
          </div>

          <div class="col">
            <div v-if="!showNoAnswer()">
              <!-- <component
                :key="reRender"
                :is="contentComponentName"
                :listAnswer="listAnswer"
                :summeryKeys="['content', 'mindex', 'mintro']"
                :pagination="pagination"
                :tq="textSearch"
                @changeCurrent="changeCurrent"
                @changePage="changePaging"
                @researchModalHandler="researchModalHandler"
                @updateForDeleteResearch="getQueryForResearch()"
                ref="content"
              ></component> -->
              <MyContent
                :key="reRender"
                :pagination="pagination"
                :viewMode="'list'"
                @changePage="changePaging"
                :schemaItems="myActiveSchema?.search_content"
                :items="listAnswer"
                ref="content"
                @ModalHandler="researchModalHandler"
                @SubjectForm="SubjectFormHandler"
                @updateForDeleteResearch="getQueryForResearch()"
                @delete="deleteFormHandle"
              >
              </MyContent>
            </div>
            <no-data v-else>
              <div class="d-flex justify-content-center align-items-center">
                <div
                  class="alert alert-warning d-flex flex-column justify-content-center"
                >
                  <div class="mb-3">پاسخی برای جستجوی شما یافت نشد.</div>
                  <div class="mb-3" v-if="textSearch">
                    <label>عبارت جستجو :</label>
                    <strong> {{ textSearch }}</strong>
                  </div>
                  <div class="mb-3" v-if="filterUrl">
                    <label>فیلتر :</label>
                    <strong> {{ filterUrl }}</strong>
                  </div>
                  <div class="mb-3" v-if="domain_lable">
                    <label>دامنه :</label>
                    <strong> {{ domain_lable }}</strong>
                  </div>
                  <div class="mb-3">
                    <label>نوع جستجو :</label>
                    <strong> {{ searchType_lable }}</strong>
                  </div>
                </div>
              </div>
            </no-data>
            <base-modal-v2
              v-if="showModal"
              @close="closeBaseModal"
              :showHeaderCloseButton="true"
              :hasFooter="false"
              :modalTitle="modalTitle"
              width="750px"
              height="463px"
              overflow="hidden"
              :showSaveButton="true"
              :showCloseButton="true"
              :showDeleteButton="false"
            >
              <slot> {{ modalTitle }}</slot>

              <slot name="body">
                <component
                  :is="slotComponentName"
                  :valueModal="valueModalResearch"
                  @closeAfterSaving="closeAfterSaving"
                  height="100%"
                ></component>
              </slot>
            </base-modal-v2>
          </div>
          <div
            v-if="showSummary"
            class="col-8 col-lg-3 summary-container"
            :class="{ expanded: showSummary }"
          >
            <component
              ref="summary"
              :currentItem="currentItem"
              :page="page"
              :is="summaryComponentName"
              @hideSummary="hideSummary"
            ></component>
          </div>
        </div>
      </div>
    </section>
  </ResearchLayout>
</template>

<script>
import searchLineMixin from "@research/mixins/research/searchLineMixin.js";
import { mapActions, mapState } from "pinia";
import researchApi from "@research/apis/researchApi";
import sidbarMenu from "@research/json/research/menu.json";

import { useResearchStore } from "@research/stores/researchStore";
import { useSearchStore } from "@research/stores/searchStore";
import { useCommonStore } from "~/stores/commonStore";
import { useAuthStore } from "~/stores/authStore";

export default {
  name: "myResearches",
  setup() {
    definePageMeta({
      layout: false,
      name: "myResearches",
    });
  },
  mixins: [searchLineMixin],
  watch: {
    $route: {
      handler: function (to, from) {
        // this.getSchemas();
        this.setInputText(to.query.q);
        this.state = 2;

        setTimeout(() => {
          if (this.textSearch != undefined && this.textSearch != "") {
            this.searchStart(this.textSearch);
          } else {
            this.getDefaultByFilter();
            // if (this.$refs.content) {
            //   this.$refs.content?.$el.classList.add("component");
            //   this.$refs.content.$el.style.right += 17 + "%";
            // }
          }
        }, 500);
      },
    },

    topRepeatInListMode(navItem) {
      if (navItem == true) {
        setTimeout(() => {
          this.$refs.dropdownSortlist.classList.remove("opacity");
          // this.$refs.circle.classList.remove("opacity");
          this.againsetlist(this.lists);
        }, 100);
      } else {
        setTimeout(() => {
          this.$refs.dropdownSortlist.classList.add("opacity");
          // this.$refs.circle.classList.add("opacity");
        }, 100);
      }
    },
    researchActiveSchemaGetter(newVal) {
      if (newVal?.domain) {
        // this.setSearchDomain(newVal);
      }
    },
  },
  beforeMount() {
    // this.httpService = new HttpService(import.meta.env.VITE_REPO_BASE_URL);
  },
  created() {
    this.httpService = useNuxtApp()["$http"];
  },
  async mounted() {
    this.logo = (await logoPhoto()).default;

    this.researchActiveSchemaSetter(this.myActiveSchema);
    // let schemaExist = this.searchActiveTabGetter && this.searchSchemaGetter;
    if (this.researchActiveSchemaGetter?.domain) {
      // this.setSearchDomain(this.researchActiveSchemaGetter);
    }

    if (window.outerWidth < 992) {
      this.$store.commit("TOGGLE_SIDEBAR_MENU");
    }

    if (this.researchSchemaGetter.length == 0) this.getSchemas();

    this.modetab = 0;
    this.state = 2;
    // }
    if (this.$route.query.q) {
      this.setInputText(this.$route.query.q);
    }
    setTimeout(() => {
      if (this.textSearch != undefined && this.textSearch != "") {
        this.searchStart(this.textSearch);
      } else {
        // this.getDefaultByFilter();
        this.getQueryForResearch();
        // if (this.$refs.content) {
        //   this.$refs.content?.$el.classList.add("component");
        //   this.$refs.content.$el.style.right += 17 + "%";
        // }
      }
    }, 500);
    // ++this.rerenderChart;
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.handleResize);
    window.removeEventListener("load", this.handleResize);
  },
  data() {
    return {
      logo: "",
      showModal: false,
      modalTitle: null,
      slotComponentName: null,
      valueModalResearch: {},
      // Restored from searchLineMixin
      typingTimer: 0,
      doneTypingInterval: 500,
      listAutocomplate: [],
      historySearch: [],
      searchDomain: [],
      showItem: 0,
      inputfocused: false,

      listAnswer: [],
      showFilter: false,
      showDropdown: false,
      showDropdownNavigateList: false,
      navigateListPart2: [],
      navigateListItem: "",
      // httpService: undefined,
      listChangeItem: "",
      showListPanel: false,
      showSearchLine: true,
      state: 2,
      modetab: 0,
      totalCount: 0,
      typeCount: "",
      ismultiWord: false,
      iscode: false,
      listAmplify: [],
      filterNavigate: [],
      amplifyIndex: -1,
      number: 0,

      showfilterCategory: true,
      activeListItem: undefined,
      treeLists: "",

      total_answer: 0,
      showButton: false,
      showSummary: false,
      windowWidth: window?.innerWidth,
      topRepeatInListMode: true,
      activeSortItem: undefined,
      changePageFilter: "",
      httpService: {},
      lastSearchInListMode: true,
      searchingState: false,
      meets: [],
      textSearch: "",
      domain_key: "",
      domain_lable: "",
      filterUrl: "",
      loading: false,
      showSummary: false,
      showTermSummary: false,
      countInPage: 10,
      currentItem: [],
      searchCode: "all",
      searchTab: "searchResult",
      searchType: "typeNormal",
      searchType_lable: "عادی",
      ismultword: true,
      iscode: false,
      reRender: 1,
      hideAdvancedSearch: false,
      page: 0,
      setQuery: "",
      textAmplify: "",
      liSelected: null,
      lists: "",
      pagination: {
        page: 1,
        pages: 0,
        total: 0,
        offset: 0, // page * per_page
        limit: 10, //per_page
      },
    };
  },
  computed: {
    ...mapState(useSearchStore, [
      "domainActiveGetter",
      "searchActiveTabGetter",
      "searchSchemaGetter",
    ]),
    ...mapState(useResearchStore, [
      "researchSchemaGetter",
      "researchActiveSchemaGetter",
    ]),
    ...mapState(useCommonStore, [
      "selectedlists",
      "organNameGetter",
      "isSidebarCollapsed",
    ]),
    ...mapState(useAuthStore, ["currentUser"]),

    myActiveSchema() {
      return this.researchSchemaGetter?.find((item) => {
        return item.key == "research";
      });
    },
    contentComponentName(key) {
      // if (key == "qanon") return "ResearchContent";
      // else if (key == "mqanon" || key == "nqanon") return "MajlesQanonContent";
      // else if (key == "qqanon") return "MajlesQavaninContent";
      // else if (key == "mqsection") return "MajlesSectionContent";
      // else if (key == "mashruh") return "MajlesMashruhContent";
      // else if (key == "term") return "TermContent";
      // else if (key == "emamain") return "EmamainContent";
      // else if (key == "nesha") return "NeshaContent";
      // else if (key == "qasection") return "MajlesQaSectionContent";

      return "ResearchContent";
    },

    summaryComponentName() {
      let key = this.searchActiveTabGetter?.key;
      if (key == "term") return "TermSummary";
      return "Summary";
    },

    isAdmin() {
      return this.currentUser.user_level > 1;
    },
    hasVectorSearch() {
      let key = this.searchActiveTabGetter?.key;
      return key == "mqsection" || key == "qasection";
    },
    navigateList() {
      return this.searchSchemaGetter;
    },
    menu() {
      return sidbarMenu;
    },
  },
  methods: {
    // ...mapActions(["TOGGLE_SIDEBAR_MENU"]),
    ...mapActions(useCommonStore, ["TOGGLE_SIDEBAR_MENU"]),
    ...mapActions(useSearchStore, [
      "searchActiveTabSetter",
      "domainActiveSetter",
    ]),
    ...mapActions(useResearchStore, [
      "researchActiveSchemaSetter",
      "researchSchemaSetter",
    ]),
    deleteFormHandle(event) {
      this.mySwalConfirm({
        title: "هشدار!!!",
        html: `از حذف <b>${event.item._source.text_subject}</b> اطمینان دارید؟ `,
        icon: "warning",
      }).then((result) => {
        if (result.isConfirmed) {
          let url = this.repoMicroServiceName + researchApi.research.deleteItem;
          url = url.replace(
            "{{index_key}}",
            this.researchActiveSchemaGetter?.key
          );
          url = url.replace("{{id}}", event.item._id);
          this.httpService.postRequest(url).then((res) => {
            this.mySwalToast({
              html: res.message,
            });
            setTimeout(() => {
              this.getQueryForResearch();
            }, 1000);
          });
        }
      });
    },
    SubjectFormHandler(event) {
      this.openBaseModal("SubjectForm", "موضوع زنی");
      let cloneItem = structuredClone(event);
      cloneItem = { ...event._source, _id: event._id };

      this.SET_SELECTED_ITEM(cloneItem);
    },
    getSchemas() {
      let url = repoUrl() + "schema";
      this.httpService
        .postRequest(url, {
          organ: "public",
          system: "research",
          build_state: buildState(),
        })
        .then((response) => {
          console.log("🚀 ~ .then ~ response:", response);
          this.researchSchemaSetter(response.data.dataset);
          let ActiveSchema = "";

          ActiveSchema = this.researchSchemaGetter?.find((item) => {
            return item.key == "research";
          });
          this.researchActiveSchemaSetter(ActiveSchema);
          // this.getData();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    closeAfterSaving() {
      this.closeBaseModal();
      setTimeout(() => {
        this.getQueryForResearch("default");
      }, 1000);
    },
    researchModalHandler(event) {
      this.openBaseModal("ResearchFishModal", event.itemSchema.title);
      this.valueModalResearch = event;
    },
    openBaseModal(componentName, title) {
      this.showModal = true;
      this.slotComponentName = componentName;
      this.modalTitle = title;
    },
    closeBaseModal() {
      setTimeout(() => {
        this.showModal = false;
      }, 500);
    },

    toggleSidebarMenu() {
      this.TOGGLE_SIDEBAR_MENU();
    },
    // setSearchDomain(value) {
    //   this.searchDomain = [{ label: "همه", key: "all" }];
    //   this.searchDomain = [...this.searchDomain, ...value.domain.domain];
    //   if (!this.domainActiveGetter) {
    //     if (isMajlesBuild()) this.domainActiveSetter(this.searchDomain[1]);
    //     else this.domainActiveSetter(this.searchDomain[0]);
    //   }
    // },
    keyupdiv(event) {
      if (this.showItem == 0 || this.showItem == 2) return;

      var el = this.showItem == 1 ? this.$refs["his_ul"] : this.$refs["aut_ul"];

      if (this.inputfocused && event.which === 38) {
        this.liSelected = el.firstChild;
        this.liSelected.classList.add("selected");
        this.liSelected.focus();
        return;
      }
      var next = null;
      if (event.which === 40) {
        if (this.liSelected) {
          this.liSelected.classList.remove("selected");
          next = this.liSelected.nextSibling;
          if (next) {
            this.liSelected = next.classList.add("selected");
          } else {
            this.liSelected = el.firstChild;
            this.liSelected.classList.add("selected");
          }
          this.liSelected.focus();
        } else {
          this.liSelected = el.firstChild;
          this.liSelected.classList.add("selected");
          this.liSelected.focus();
        }
      } else if (event.which === 38) {
        if (this.liSelected) {
          this.liSelected.classList.remove("selected");
          next = this.liSelected.prevSibling;
          if (next) {
            this.liSelected = next.classList.add("selected");
          } else {
            this.liSelected = el.lastChild;
            this.liSelected.classList.add("selected");
          }
          this.liSelected.focus();
        } else {
          this.liSelected = el.lastChild;
          this.liSelected.classList.add("selected");
          this.liSelected.focus();
        }
      }
    },
    slmSearchStart() {
      this.liSelected = null;
      this.showItem = 0;
      this.addHistorySearch(this.textSearch);

      let tt = myEncodeQuery(this.textSearch);
      // if (emited) this.$emit("searchStart", tt);
      this.searchStart(tt);
    },
    setInputText(text) {
      this.textSearch = myEncodeQuery(text);
    },
    showHisory() {
      setTimeout(() => {
        if (this.textSearch == "") this.showItem = 1;
        else {
          this.showItem = 0;
          this.liSelected = null;
        }
      }, 100);
    },
    setSelectedNavItem(navItem) {
      this.domainActiveSetter(navItem);
      this.slmSearchStart();
    },
    onClickOutside() {
      if (this.showItem == 1) {
        this.showItem = 0;
        this.liSelected = null;
      }
    },

    handleResize() {
      return window.outerWidth < 992;

      // if (this.windowWidth < 990) {
      //   this.$store.commit("TOGGLE_SIDEBAR_MENU");
      // }
    },

    changeHideFilter(event) {
      if (event === 0) {
        this.$refs.axis.classList.remove("hiden");
        this.$refs.showFilter.classList.toggle("d-none");

        this.showButton = false;
        this.showFilter = true;
      } else if (event === 1) {
        this.$refs.axis.classList.add("hiden");
        this.$refs.showFilter.classList.toggle("d-none");
        this.showButton = true;
        this.showFilter = false;
      }
    },

    searchCoding() {
      this.slmSearchStart();
    },
    resetOptions() {
      this.page = 0;
      this.filterUrl = "";
      this.$refs.filterlist?.resetFilter();
    },
    showfilter: function () {
      this.$refs.filterlist?.showfilter();
    },
    checkMultiword(query_string) {
      this.ismultword = true;
      if (query_string == null || query_string == "") return;
      var ww = query_string.split(" ");
      this.iscode = /^\d+$/.test(query_string);

      this.setOptions(this.ismultword, this.iscode);
    },
    setOptions(isMulti, isCode = false) {
      this.ismultiWord = isMulti;
      if (this.ismultiWord == false) this.searchType = "typeNormal";
      this.iscode = isCode;
    },

    searchStart(query_string = null) {
      if (query_string != null && query_string != "") {
        //console.log(query_string);
        query_string = query_string.trim();
        this.setInputText(query_string);
        this.checkMultiword(query_string);

        if (this.topRepeatInListMode)
          this.$refs?.content?.setTextSearch(query_string, this.countInPage);

        this.resetOptions();
        this.getQueryForResearch("filter");
      } else {
        this.setInputText("");
        this.searchingState = false;
        this.getQueryForResearch("default");
      }

      if (this.textSearch != "") {
        history.pushState(
          {},
          document.title,
          "/research" + "/?q=" + myEncodeQuery(this.textSearch)
        );
      } else history.pushState({}, document.title, "/research");
    },
    setQueryAdvanced(query) {
      this.initText(query);
      // if (this.$refs.topheader) {
      //   this.$refs.topheader.setSearchLine(query);
      // }
    },
    changePaging(item) {
      this.pagination = item;

      if (this.searchingState) this.getQueryForResearch("filter");
      else this.getQueryForResearch("default");
    },
    hideSummary: function () {
      this.showSummary = false;
      // this.showTermSummary = false;
    },
    changeCurrent: function (item) {
      this.showSummary = false;
      // if (this.$route.name == "termResult") {
      //   this.changeCurrentTerm(item);
      // }
      // if (item == this.currentItem) this.showSummary = !this.showSummary;
      // else this.showSummary = true;
      this.$nextTick(() => {
        this.showSummary = true;
      });

      this.currentItem = item;
      if (this.$refs.summary) this.$refs.summary.setInfo(item);
    },

    filterUpdate(filter) {
      this.filterUrl = filter;
      this.page = 0;
      if (filter) this.getQueryForResearch("filter");
      else this.getQueryForResearch("default");
    },

    getQueryForResearch(position = "default") {
      this.loading = true;

      let query = "";
      let text = myEncodeQuery(this.textSearch);
      if (text?.length != 0) {
        this.domain_key = this.domainActiveGetter?.key;
        if (this.domain_key && this.domain_key != "all") {
          this.domain_lable = this.domainActiveGetter?.label;
          query =
            "q=" + encodeURIComponent("#") + this.domain_lable + " " + text;
        } else {
          query = "q=" + text;
        }
      }

      let filter = this.filterUrl;
      if (this.textAmplify != undefined && this.textAmplify != "") {
        filter += "&o_am=" + this.textAmplify;
      }

      let url = researchApi.research?.listDefault;
      url = url.replace("{{user_id}}", this.currentUser?.user_id);
      url = url.replace("{{offset}}", this.pagination?.offset);
      url = url.replace("{{limit}}", this.pagination?.limit);

      if (query ? query : "" || filter ? filter : "")
        url = url + "/" + query + filter;
      this.httpService
        .getRequest(repoUrl() + url)
        .then((response) => {
          this.searchingState = true;
          this.$refs.filterlist?.setAnswer(response.aggregations);
          this.lists = response.hits.hits;
          this.listAnswer = response.hits.hits;

          this.loading = false;

          this.total_answer = response.hits.total.value;

          const total = response.hits.total.value;
          this.total_answer = total;
          const pages = Math.ceil(total / this.pagination.limit);
          const pagination = {
            total: total,
            pages: pages == 0 ? 1 : pages,
          };
          this.pagination = { ...this.pagination, ...pagination };
        })
        .catch((error) => {
          this.loading = false;
          this.searchingState = false;
          // vm.$alert(error);
        });
    },

    againsetlist(list) {
      this.$refs.content?.setAnswer(
        // this.lists.data.aggregations.branch.buckets,
        this.lists.data.hits.hits,
        this.lists.data.hits.total.value,
        this.lists.data.hits.total.relation
      );
      this.$refs.filterlist?.setAnswer(this.lists.data.aggregations);
    },

    resetPagination() {
      this.pagination = {
        pages: 0,
        total: 0,
        page: 1,
        offset: 0,
        limit: 10,
      };
    },
    closeAdvancedSearch() {
      this.hideAdvancedSearch = false;
    },
    showAdvancedSearch() {
      if (this.hideAdvancedSearch) {
        this.hideAdvancedSearch = false;
      } else {
        this.hideAdvancedSearch = true;
      }
    },
    showNoAnswer() {
      if (this.searchingState) {
        return this.total_answer == 0;
      }
      return false;
    },
    canSee(keyName) {
      if (this.currentUser?.user_level > 1) return true;
      return this.userPermisionGetter?.includes(keyName);
    },
    myEncodeQuery(text) {
      if (!text) return "";
      //text = JSON.stringify(text);
      let ch1 = encodeURIComponent("#");
      let ch3 = encodeURIComponent("\\");
      let ch4 = encodeURIComponent("&");
      text = text.replaceAll("#", ch1);
      text = text.replaceAll("&", ch4);
      text = text.replaceAll("/", "\\");
      text = text.replaceAll("\\", ch3);
      // text = text.replaceAll(".", '%2E');
      return text;
    },
    myEncodeQuery(text) {
      //text = JSON.stringify(text);
      if (!text) return "";

      let ch1 = encodeURIComponent("#");
      let ch3 = encodeURIComponent("\\");

      text = text.replaceAll(ch1, "#");
      text = text.replaceAll(ch3, "\\");
      return text;
    },
    getHtmlTooltip2(section, key, id) {
      let res = "";
      let link = "";
      if (id) link = location?.origin + "/pages/help/" + section + "/" + id;

      if (section == "research") {
        if (key == "research_advance") {
          res = `<p class="mb-2">برای یافتن بهترین پاسخ، روش جستجو را تعیین می‌کند</p>`;
        } else if (key == "search_sort") {
          res = `<p class="mb-2">ترتیب نمایش فهرست قبل و بعد از جستجو را تعیین می کند</p>`;
        } else if (key == "search_advance") {
          res = `<p class="mb-2">امکانات ویژه جهت جستجو در ویژگی های همراه متن در اختیار می گذارد </p>`;
        }
      }

      if (section == "entity") {
      }

      if (res != "" && link != "")
        res += `<a class="btn btn-link" target="_blank" href="${link}"> بیشتر ... </a>`;

      return res;
    },
    initText(item) {
      this.textSearch = item;
    },

    getHighlight(item) {
      var find = this.textSearch;
      var text = item.replaceAll(find, "<b>" + find + "</b>");
      return text;
    },
    selectHistorySearch(item) {
      this.textSearch = item;
      this.searchStart(this.textSearch);
    },
    addHistorySearch(newSearch = "") {
      if (newSearch == "") {
        return;
      }
      var index = this.historySearch.indexOf(newSearch);
      if (index != -1) {
        this.historySearch.splice(index, 1);
      }

      this.historySearch.unshift(newSearch);
      this.saveHistorySearch();
    },
    removeHistorySearch(x) {
      this.historySearch.splice(x, 1);
      this.saveHistorySearch();
    },
    saveHistorySearch() {
      const parsed = JSON.stringify(this.historySearch);
      window.localStorage.setItem([HISTORY_SEARCH_RECENT], parsed);
    },
  },
  components: {
    ResearchLayout: defineAsyncComponent(() =>
      import("@research/layouts/ResearchLayout.vue")
    ),
    ResearchFilterList: defineAsyncComponent(() =>
      import("@research/components/research/components/ResearchFilterList.vue")
    ),
    MyContent: defineAsyncComponent(() =>
      import("@search/components/search/MyContent.vue")
    ),
    ResearchFishModal: defineAsyncComponent(() =>
      import("@research/components/research/components/ResearchFishModal.vue")
    ),
    AdvancedSearch: defineAsyncComponent(() =>
      import("@research/components/research/components/AdvancedSearch.vue")
    ),
    SubjectForm: defineAsyncComponent(() =>
      import("@research/components/research/components/SubjectForm.vue")
    ),

    // MyContent: () => import("@search/components/search/MyContent.vue"),
    // ResearchFishModal: () =>
    //   import("@research/components/research/components/ResearchFishModal.vue"),
    // FilterList: () => import("@research/components/FilterList.vue"),
    // FilterListSearch: () => import("@search/view/layout/FilterListSearch.vue"),
    // AdvancedSearch: () =>
    //   import("@research/components/research/components/AdvancedSearch.vue"),
    // SubjectForm: () =>
    //   import("@research/components/research/components/SubjectForm.vue"),
  },
};
</script>
<style scoped lang="scss">
.v-popper--theme-dropdown {
  display: flex;

  .v-popper__inner {
    .my-tooltip-content {
      color: white;
      background-color: black;
      padding: 1em;
    }
  }
}
</style>
