<template>
  <div class="wrapper detail-page">
    <TopHeader
      ref="topheader"
      @searchStart="searchStart"
      @showfilter="showfilter"
      @searchType="searchTyping"
      @="searchCoding"
    ></TopHeader>

    <Content
    :pagination="pagination"
      @changeCurrent="changeCurrent"
      @changePage="changePaging"
      ref="content"
    ></Content>

    <filter-list-search @filterUpdate="filterUpdate" ref="filterlist"></filter-list-search>
    <Summary
      ref="summary"
      :meets="meets"
      @hideSummary="hideSummary"
      v-show="showSummary"
    >
    </Summary>
    <!-- <ChartTree>
    </ChartTree> -->
  </div>
</template>

<script>
// import axios from "axios";
import TopHeader from "~/search/view/layout/Top.vue";
import FilterListSearch from "~/search/view/layout/FilterListSearch.vue";
import Content from "~/search/view/pages/TermContent.vue";
import Summary from "~/search/view/layout/TermSummary.vue";
import LogService from "~/services/log.service";
import {mapState} from "pinia";

//
// const API = axios.create({
//     //baseURL: 'http://2.182.155.188',
//     baseURL: import.meta.env.VITE_API_SEARCH,
// })

export default {
  props: ["q"],
  name: "Term",
  data() {
    return {
      meets: [],
      tq: this.q,
      filterUrl: "",
      loading: false,
      showSummary: false,
      countInPage: 10,
      currentItem: [],
      searchType: "",
      searchCode: "all",
      ismultword: false,
      iscode: false,
      page: 0,
      pagination: {
        page: 1,
        pages: 0,
        total: 0,
        offset: 0, // page * per_page
        limit: 10, //per_page
      },
    };
  },
  computed:{
    ...mapState(["currentUser"])
  },

  mounted() {
    this.$refs.topheader.modetab = 3;
    this.$refs.topheader.state = 2;
    if (this.tq != "") {
      var item = this.tq;
      this.checkMultiword(item);
      this.$refs.topheader.setSearchLine(this.tq);
      this.$refs.content.setTextSearch(this.tq, this.countInPage);
      this.getQuery();
    }
  },
  methods: {
    searchTyping(type) {
      this.searchType = type;
    },
    searchCoding(code) {
      this.searchCode = code;
    },
    resetOptions() {
      this.page = 0;
      this.filterUrl = "";
      this.$refs.filterlist.resetFilter();
    },
    showfilter: function() {
      this.$refs.filterlist.showfilter();
    },
    checkMultiword(item) {
      this.ismultword = false;
      if (item == null || item == "") return;
      var ww = item.split(" ");
      this.iscode = /^\d+$/.test(item);
      if (this.iscode == false) this.ismultword = item.split(" ").length > 1;

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

        this.checkMultiword(item);
        this.$refs.content.setTextSearch(item, this.countInPage);
      }
      this.resetOptions();
      this.getQuery();
    },
    changePaging: function(item) {
      this.pagination = item;
      this.getQuery(true);
    },
    hideSummary: function() {
      this.showSummary = false;
    },
    changeCurrent(item) {

      if (item == this.currentItem) this.showSummary = !this.showSummary;
      else this.showSummary = true;
      this.currentItem = item;
     


      var vm = this;
      this.loading = true;
      var suburl = "/monir/search/term/items/";

      ApiService.getRequest(
        suburl +
          this.page +
          "/" +
          item.doc_count +
          "/q=" +
          item.key +
          this.filterUrl
      )
        .then((response) => {
          vm.loading = false;

          // if (title == this.currentItem) this.showSummary = !this.showSummary;
          // else this.showSummary = true;

          // this.showSummary = true;
          this.meets = response.data.hits.hits;

          // this.$refs.summary.setInfo(response.data.hits.hits);
        })
        .catch((error) => {
          vm.loading = false;
          vm.$alert(error);
        });
    },
    filterUpdate: function(filter) {
      this.filterUrl = filter;
      // history.pushState(null, '', '/list' + '/q='+ this.tq+ filter);
      this.$router.push({
        name: "TermResult",
        query: { q: this.tq + filter },
      });
      this.page = 0;
      this.getQuery(false, true);
    },

    // typeNormal : جستجوی عادی
    // typeAnd : جستجوی عطفی
    // typePhrase : جستجوی عبارتی

    getQuery: function(pageOnly = false, filteronly = false) {
      var vm = this;
      this.loading = true;
      var suburl = "/monir/search/term/";
      if (this.ismultword) {
        if (this.searchType == "typeAnd") suburl = "/monir/search/term/and/";
        else if (this.searchType == "typePhrase")
          suburl = "/monir/search/term/phrase/";
      }

      ApiService.getRequest(
        suburl +
        this.pagination.offset +
          "/" +
          this.pagination.limit +
          "/q=" +
          this.tq +
          this.filterUrl
      )
        .then((response) => {
          vm.loading = false;
          if (pageOnly) {
            this.$refs.content.setAnswer(
              response.data.aggregations.branch.buckets
            );
          } else if (filteronly) {
            this.$refs.topheader.setCount(
              response.data.hits.total.value,
              response.data.hits.total.relation
            );
            this.$refs.content.setAnswer(
              response.data.aggregations.branch.buckets,
              response.data.hits.total.value,
              response.data.hits.total.relation
            );
          } else {
            this.$refs.topheader.setCount(
              response.data.hits.total.value,
              response.data.hits.total.relation
            );
            this.$refs.content.setAnswer(
              response.data.aggregations.branch.buckets,
              response.data.hits.total.value,
              response.data.hits.total.relation
            );
            response.data.aggregations.branch.buckets = [];
            this.$refs.filterlist.setAnswer(response.data.aggregations);
          }

             const total = response.data.hits.total.value;
        const pages = Math.ceil(total / this.pagination.limit);
        const pagination = {
          total: total,
          pages: pages == 0 ? 1 : pages
        }

        this.pagination = { ...this.pagination, ...pagination };
          LogService.index(this.currentUser,vm.tq, vm.page, vm.filterUrl, response.data.took);
        })
        .catch((error) => {
          vm.loading = false;
          vm.$alert(error);
        });
    },
  },
};
</script>
