<template>
  <section
    class="myResearches position-relative"
    :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="/" classes="btn me-3">
                  <img
                    :src="logo"
                    alt="هم فهمی"
                    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">
                <!-- @keyup="keyupdiv" -->
                <div
                  class="input-group"
                  style="box-shadow: 0 1px 3px rgba(23, 23, 23, 0.24)"
                >
                  <VMenu class="my-vmenu d-flex align-items-center">
                    <div class="input-group-prepend">
                      <button
                        type="button"
                        @click.prevent="showAdvancedSearch"
                        title="جستجوی پیشرفته"
                        class="btn"
                      >
                        پیشرفته؟
                      </button>
                    </div>

                    <template #popper>
                      <div
                        class="my-tooltip-content"
                        v-html="
                          getHtmlTooltip2(
                            'research',
                            'research_advance',
                            'TKVLBY8BPd2Jp_XrBZq0'
                          )
                        "
                      ></div>
                    </template>
                  </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 d-flex">
                    <button
                      v-tooltip="'جستجو در خاصیت(فیلد) ویژه'"
                      class="btn dropdown-toggle"
                      type="button"
                      data-bs-toggle="dropdown"
                      aria-haspopup="true"
                      aria-expanded="false"
                    >
                      <span class="navItemlabel">
                        {{ researchDomainActiveGetter?.label }}
                      </span>
                    </button>
                    <div class="dropdown-menu">
                      <template>
                        <button
                          v-for="(navItem, index) in searchDomain"
                          :key="index"
                          type="button"
                          class="dropdown-item"
                          @click.prevent="setSelectedNavItem"
                        >
                          {{ navItem.label }}
                        </button>
                      </template>
                    </div>

                    <button
                      v-tooltip="'جستجو در خاصیت(فیلد) ویژه'"
                      @click.prevent="slmSearchStart()"
                      class="btn btn-primary search-icon"
                      style="color: #fff"
                    >
                      <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="{ path: 'about-us' }" class="dropdown-item"
                    >درباره ما</NuxtLink
                  >
                  <NuxtLink :to="{ path: 'connect-us' }" 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 d-lg-none">
            <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"
                class="filterList"
              ></ResearchFilterList> -->

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

        <div class="col">
          <template v-if="!showNoAnswer()">
            <component
              :key="reRender"
              :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'"
              @changeCurrent="changeCurrent"
              @changePage="changePaging"
              :schemaItems="myActiveSchema"
              :items="listAnswer"
              ref="content"
              @ModalHandler="researchModalHandler"
              @updateForDeleteResearch="getQueryForResearch()"
            >
            </MyContent>
          </template>
          <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"
          >
            <template v-slot:default> {{ modalTitle }}</template>

            <template v-slot:body>
              <component
                :is="slotComponentName"
                :valueModal="valueModalResearch"
                @closeAfterSaving="closeAfterSaving"
                height="100%"
              ></component>
            </template>
          </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>
</template>

<script lang="ts">
import apis from "~/apis/researchApi";
import apis2 from "~/apis/searchApi";
import { useResearchStore } from "../stores/researchStore";
import {clearBodyClass} from "@manuals/utilities"

import { useCommonStore } from "~/stores/commonStore";
import { useSearchStore } from "~/stores/searchStore";
import { useAuthStore } from "~/stores/authStore";
import { mapActions, mapState } from "pinia";
import type { Pagination } from "~/types/commonTypes";
import type {
  domain,
  researchQuery,
  researchSchemaRes,
} from "~/types/researchTypes";

import monirMenu from "~/json/research/json/menu.json";

export default {
  watch: {
    // getPanelStatus(status) {
    // if (status) this.openForm();
    // else this.closeModal();
    // },
    // $route: {
    //   handler: function () {},
    //   deep: true,
    //   immediate: true,
    // },
    // $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();
        }, 100);
      } else {
        setTimeout(() => {
          this.$refs.dropdownSortlist.classList.add("opacity");
          // this.$refs.circle.classList.add("opacity");
        }, 100);
      }
    },
    researchActiveSchemaGetter(newVal) {
      if (newVal?.domain) {
        this.setSearchDomain(newVal);
      }
    },
    // listIdGetter(newId) {
    //   this.filterBy(this.selectedFilter);
    // },
  },
  meta: {
    title: import.meta.env.VITE_CHAT_PAGE_TITLE,
    metaTags: [
      {
        name: "description",
        content: "The about page of our example app.",
      },
      {
        property: "og:description",
        content: "The about page of our example app.",
      },
    ],
  },

  // beforeCreate() {
  // ApiService.init(import.meta.env.VITE_LIST_BASE_URL);
  // },
  beforeMount() {
    this.sidebarMenuSetter(monirMenu);
    clearBodyClass();
  },
  mounted() {
    document.title = import.meta.env.VITE_RESEARCH_PAGE_TITLE;

    this.TOGGLE_PANEL(false);
    this.setBodyClass(import.meta.env.VITE_RESEARCH_SYSTEM);

    if (this.researchSchemaGetter) {
      this.loading = false;
      // this.getData();
    } else {
      this.getSchemas();
    }

    // this.researchActiveSchemaSetter(this.myActiveSchema);

    // if (this.researchActiveSchemaSetter?.domain?.domain) {
    //   this.setSearchDomain(this.researchActiveSchemaGetter.domain.domain);
    // }

    if (window.outerWidth < 992) {
      this.TOGGLE_SIDEBAR_MENU();
    }

    this.modetab = 0;
    this.state = 2;
    // }
    if (this.$route.query.q) {
      this.setInputText(this.$route.query.q as string);
    }
    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;
    const HISTORY_SEARCH_RECENT = "historysearchrecent";
    if (window.localStorage.getItem(HISTORY_SEARCH_RECENT)) {
      try {
        this.historySearch = JSON.parse(
          window.localStorage.getItem(HISTORY_SEARCH_RECENT) as string
        );
      } catch (e) {
        window.localStorage.removeItem(HISTORY_SEARCH_RECENT);
      }
    }
    // logoPhoto().then((img) => {
    //   this.logo = img;
    // });
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.handleResize);
    window.removeEventListener("load", this.handleResize);
  },
  destroyed() {
    clearBodyClass();
  },
  data() {
    return {
      userLastStateIsLoaded: true,
      modalComponentName: "",
      actionMode: 1,
      logo: "",
      routeName: this.buildName,
      showListPanel: false,
      showModal: false,
      modalTitle: "",
      slotComponentName: "",
      valueModalResearch: {},
      // Restored from searchLineMixin
      typingTimer: 0,
      doneTypingInterval: 500,
      listAutocomplate: [],
      historySearch: [],
      searchDomain: [] as domain[],
      inputfocused: false,

      listAnswer: [] as researchQuery[],
      showFilter: false,
      showDropdown: false,
      showDropdownNavigateList: false,
      navigateListPart2: [],
      navigateListItem: "",
      listChangeItem: "",
      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: "",

      lastSearchInListMode: true,
      searchingState: false,
      meets: [],
      textSearch: "" as string,
      domain_key: "" as string | undefined,
      domain_lable: "" as string | undefined,
      filterUrl: "",
      loading: false,
      showTermSummary: false,
      countInPage: 10,
      currentItem: [],
      searchCode: "all",
      searchTab: "searchResult",
      searchType: "typeNormal",
      searchType_lable: "عادی",
      ismultword: true,
      reRender: 1,
      hideAdvancedSearch: false,
      page: 0,
      setQuery: "",
      textAmplify: "",
      liSelected: {},
      lists: {},
      pagination: {
        page: 1,
        pages: 0,
        total: 0,
        offset: 0, // page * per_page
        limit: 10, //per_page
      },
      showItem: 0,
      listFilter: [],
    };
  },
  computed: {
    navTitle() {
      return import.meta.env.VITE_TITLE;
    },
    // sidbarMenu() {
    //   if (isMajlesBuild()) return this.majlesMenu;
    //   else return this.monirMenu;
    // },
    ...mapState(useSearchStore, [
      "searchActiveTabGetter",
      "searchSchemaGetter",
    ]),
    ...mapState(useResearchStore, [
      "researchSchemaGetter",
      "researchActiveSchemaGetter",
      "researchDomainActiveGetter",
    ]),
    ...mapState(useAuthStore, ["currentUser"]),
    ...mapState(useCommonStore, [
      "selectedlists",
      "organNameGetter",
      "isSidebarCollapsed",
      "userPermisionGetter",
    ]),

    myActiveSchema() {
      return this.researchSchemaGetter?.find((item) => {
        return item.key == "research";
      });
    },
    // contentComponentName(key:string) {
    // 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;
    },
  },

  methods: {
    ...mapActions(useCommonStore, [
      "setBodyClass",
      "TOGGLE_PANEL",
      "TOGGLE_SIDEBAR_MENU",
      "sidebarMenuSetter",
    ]),
    ...mapActions(useResearchStore, [
      "researchSchemaSetter",
      "researchActiveSchemaSetter",
      "researchDomainActiveSetter",
    ]),
    ...mapActions(useSearchStore, [
      "searchActiveTabSetter",
      
    ]),

    async getSchemas() {
      // this.httpService
      //   .postRequest("schema", {
      //     organ: "public",
      //     system: "research",
      //     build_state: this.buildState,
      //   })
      //   .then((response) => {
      //     this.researchSchemaSetter(response.data.dataset);
      //     // this.getData();
      //   })
      //   .finally(() => {
      //     this.loading = false;
      //   });

      try {
        const { $api } = useNuxtApp();
        const data: researchSchemaRes = await $api(apis2.schema.list, {
          baseURL: import.meta.env.VITE_REPO_BASE_URL,
          method: "POST",
          body: {
            organ: "public",
            system: "research",
            build_state: buildState(),
          },
        });
        this.researchSchemaSetter(data.data.dataset);
        // this.list = data.hits.hits;
      } catch (err) {
      }
    },

    toggleSidebarMenu() {
      this.TOGGLE_SIDEBAR_MENU();
    },
    showToggleListPanel() {
      this.showListPanel = !this.showListPanel;
      // this.$refs["chat-list-panel"].showMainpag = true;
    },

    closeAfterSaving() {
      this.closeBaseModal();
      setTimeout(() => {
        this.getQueryForResearch("default");
      }, 1000);
    },
    researchModalHandler(event: Event) {
      this.openBaseModal("ResearchFishModal", (event as any).itemSchema.title);
      this.valueModalResearch = event;
    },
    openBaseModal(componentName: string, title: string) {
      this.showModal = true;
      this.slotComponentName = componentName;
      this.modalTitle = title;
    },
    closeBaseModal() {
      setTimeout(() => {
        this.showModal = false;
      }, 500);
    },
    setSearchDomain(value: domain[]) {
      this.searchDomain = [...this.searchDomain, ...value];

      if (!this.researchDomainActiveSetter) {
        if (buildName() === "majles") {
          this.researchDomainActiveSetter(this.searchDomain[1] as domain);
        } else {
          this.researchDomainActiveSetter(this.searchDomain[0] as domain);
        }
      }
    },

    // keyupdiv(event: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 as any).which === 38) {
    //     this.liSelected = el.firstChild;
    //     this.liSelected.classList.add("selected");
    //     this.liSelected.focus();
    //     return;
    //   }
    //   var next = null;
    //   if ((event as any).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 as any).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 = this.myEncodeQuery(this.textSearch);
      // if (emited) this.$emit("searchStart", tt);
      this.searchStart(tt);
    },
    setInputText(text: string) {
      this.textSearch = this.myDncodeQuery(text);
    },
    showHisory() {
      setTimeout(() => {
        if (this.textSearch == "") this.showItem = 1;
        else {
          this.showItem = 0;
          // this.liSelected = null;
        }
      }, 100);
    },
    setSelectedNavItem(event: Event) {
      this.researchDomainActiveSetter(event as any);
      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: number) {
      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: string | null) {
      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 = true, isCode = false) {
      this.ismultiWord = isMulti;
      if (this.ismultiWord == false) this.searchType = "typeNormal";
      this.iscode = isCode;
    },

    searchStart(query_string: 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=" + this.myEncodeQuery(this.textSearch)
        );
      } else history.pushState({}, document.title, "/research");
    },
    setQueryAdvanced(query: string) {
      this.initText(query);
      // if (this.$refs.topheader) {
      //   this.$refs.topheader.setSearchLine(query);
      // }
    },
    changePaging: function (item: Pagination) {
      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: string) {
      this.filterUrl = filter;
      this.page = 0;
      if (filter) this.getQueryForResearch("filter");
      else this.getQueryForResearch("default");
    },

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

      let query = "";
      let text = this.myEncodeQuery(this.textSearch);
      if (text?.length != 0) {
        this.domain_key = this.researchDomainActiveGetter?.key;
        if (this.domain_key && this.domain_key != "all") {
          this.domain_lable = this.researchDomainActiveGetter?.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 = apis.research.listDefault;
      url = url.replace("{{user_id}}", this.currentUser.user_id);
      url = url.replace(
        "{{offset}}",
        this.pagination.offset as unknown as string
      );
      url = url.replace(
        "{{limit}}",
        this.pagination.limit as unknown as string
      );
      // if (query ? query : "" || filter ? filter : "")
      //   url = url + "/" + query + filter;
      if ((query ? query : "") || (filter ? filter : "")) {
        url = url + "/" + (query || "") + (filter || "");
      }
      try {
        const { $api } = useNuxtApp();
        const data: resModelThree = await $api(url, {
          baseURL: import.meta.env.VITE_REPO_BASE_URL,
          method: "GET",
        });
        this.searchingState = true;
        this.setAnswer(data.aggregations);
        this.lists = data.hits.hits as researchQuery[];
        this.listAnswer = data.hits.hits;

        this.loading = false;

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

        const total = data.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 (err) {
        this.loading = false;
        this.searchingState = false;
      }
    },
    setAnswer: function (list: []) {
      // console.log(list)
      this.listFilter = list;
      this.reRender++;
    },
    againsetlist() {
      // 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: string) {
      if (this.currentUser?.user_level > 1) return true;
      return this.userPermisionGetter?.includes(keyName);
    },
    myEncodeQuery(text: string) {
      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;
    },
    myDncodeQuery(text: string) {
      //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: string, key: string, id: string) {
      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: string = "") {
      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: number) {
      this.historySearch.splice(x, 1);
      this.saveHistorySearch();
    },
    saveHistorySearch() {
      const HISTORY_SEARCH_RECENT = "historysearchrecent";
      const parsed = JSON.stringify(this.historySearch);
      window.localStorage.setItem(HISTORY_SEARCH_RECENT, parsed);
    },
  },
};
</script>

<style lang="scss">
@import "~/assets/research/scss/research.scss";
.v-popper--theme-dropdown {
  display: flex;

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