<template>
  <NuxtLayout name="search-layout" :menu="sidbarMenu">
    <div class="container-fluid">
      <div class="row border-bottom header-height main-page__content-header">
        <div
          class="col-12 order-1 order-lg-1 col-lg-3 d-flex justify-content-start"
        >
          <div
            class="d-flex position-relative align-items-center"
            v-if="searchChartSchemaGetter?.length"
          >
            <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>
            <label for="repositories-desktop" class="ms-2 no-wrap">
              بانک داده
            </label>

            <USelectMenu
              v-model="dataBankSelectValue"
              :options="searchChartSchemaGetter"
              placeholder="انتخاب فهرست"
              @update:model-value="onSelectNavigation"
            >
            </USelectMenu>

            <!-- 
            <multiselect
              :allow-empty="false"
              :searchable="true"
              :close-on-select="true"
              :show-labels="false"
              label="label"
              track-by="key"
              placeholder="انتخاب فهرست"
              :value="searchChartActiveSchemaGetter"
              :options="searchChartSchemaGetter"
              @select="onSelectNavigation"
              :hide-selected="false"
              :max-height="200"
              id="repositories-desktop"
            >
            </multiselect> -->
          </div>
        </div>
        <div
          class="col-12 order-2 order-lg-1 col-lg-7 d-flex align-items-end justify-content-center"
        >
          <div class="nav-tabs-container nav-tabs border-bottom-0">
            <ul class="nav">
              <li
                class="nav-item desktop"
                v-for="(navItem, index) in searchChartActiveSchemaGetter?.items"
                :key="index"
              >
                <button
                  :title="navItem.label"
                  type="button"
                  @click.prevent="updateCategoryList(navItem, index)"
                  class="btn nav-link"
                  :class="{
                    active: searchChartActiveTabGetter?.key == navItem.key,
                  }"
                >
                  {{ navItem.label }}
                </button>
              </li>
              <li
                class="nav-item mobile tabs-more-btn d-md-none"
                v-if="searchChartActiveSchemaGetter?.items?.length > 3"
              >
                <div class="dropdown">
                  <button
                    class="btn"
                    type="button"
                    id="dropdownMenuButton"
                    data-bs-toggle="dropdown"
                    aria-haspopup="true"
                    aria-expanded="false"
                  >
                    <svg class="icon icon-Component-81--1">
                      <use xlink:href="#icon-Component-81--1"></use>
                    </svg>
                  </button>
                  <div
                    class="dropdown-menu"
                    aria-labelledby="dropdownMenuButton"
                  >
                    <a
                      class="dropdown-item"
                      @click.prevent="updateCategoryList(navItem, index)"
                      v-for="(
                        navItem, index
                      ) in searchChartActiveSchemaGetter?.items"
                      :key="index"
                      :class="{
                        active: searchChartActiveTabGetter?.key == navItem.key,
                      }"
                      >{{ navItem.label }}</a
                    >
                  </div>
                </div>
              </li>
            </ul>
          </div>
        </div>
      </div>

      <div class="row">
        <div class="col">
          <div
            class="d-flex pt-1 pb-2 justify-content-center custom-filter-container"
          >
            <div
              v-if="searchChartActiveTabGetter?.chartBase"
              class="d-flex align-items-center"
            >
              <label
                for="choose-filter"
                class="d-none d-lg-inline label-change no-wrap ms-1"
                >{{ searchChartActiveTabGetter?.chartBase?.label }}</label
              >
              <USelectMenu
                v-model="schemaFilters"
                :options="searchChartActiveTabGetter?.chartBase?.items"
                :placeholder="searchChartActiveTabGetter?.chartBase?.label"
                @update:model-value="changeFilter"
              >
              </USelectMenu>

              <!-- <multiselect
                :searchable="true"
                :close-on-select="true"
                :show-labels="false"
                label="label"
                track-by="key"
                :placeholder="searchChartActiveTabGetter?.chartBase?.label"
                v-model="schemaFilters"
                :options="searchChartActiveTabGetter?.chartBase?.items"
                @select="changeFilter"
                :hide-selected="false"
                :max-height="200"
                openDirection="rtl"
                id="chart-base"
              >
                <label slot="noResult">موردی پیدا نشد.</label>
              </multiselect> -->
            </div>
            <div
              v-if="searchChartActiveTabGetter?.chartType"
              class="d-flex align-items-center"
            >
              <label
                for="filter-chart"
                class="d-none d-lg-inline me-2 label-change no-wrap ms-1"
                >{{ searchChartActiveTabGetter?.chartType?.label }}:</label
              >
              <USelectMenu
                v-model="pieModel"
                :options="searchChartActiveTabGetter?.chartBase?.items"
                :placeholder="searchChartActiveTabGetter?.chartType?.label"
                @update:model-value="changeChart"
              >
              </USelectMenu>

              <!-- <multiselect
                :allow-empty="false"
                :searchable="true"
                :close-on-select="true"
                :show-labels="false"
                label="chartName"
                track-by="chartkey"
                :placeholder="searchChartActiveTabGetter?.chartType?.label"
                v-model="pieModel"
                :options="searchChartActiveTabGetter?.chartType?.items"
                @select="changeChart"
                :hide-selected="false"
                :max-height="200"
                id="chart-type"
              >
              </multiselect> -->
            </div>
          </div>
        </div>
      </div>

      <div class="row">
        <div
          class="col-8 col-lg-3 filter-list-container"
          :class="{ expanded: 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>
          <chart-filter-list
            v-if="showInCharts"
            :key="componentCounter"
            :listFilter="listFilter"
            :activeTabGetter="searchChartActiveSchemaGetter"
            @hide-panel="showToggleListPanel()"
            @changeAmplify="onChangeAmplify"
            @changeType="onChangeType"
            @changeCode="onChangeCode"
            @filterUpdate="filterUpdate"
          ></chart-filter-list>
        </div>
        <div class="col">
          <div v-if="canView">
            <ChartContent
              :activeTabGetter="searchChartActiveSchemaGetter"
              :schemaFilters="schemaFilters"
              :selectedCategory="schemaFilters?.key"
              :dataChart="dataChart"
              :chartComponentName="chartComponentName"
              class="ChartContent"
            ></ChartContent>
          </div>
          <no-data v-else>
            <p class="text-center p-3">عدم دسترسی</p>
          </no-data>
        </div>
      </div>
    </div>
  </NuxtLayout>
</template>

<script>
import { mapState, mapActions } from "pinia";
import searchApis from "@search/apis/searchApi";
import chartType from "@search/json/search/json/chart.json";

import sidbarMenuDefault from "@search/json/search/json/menu.json";
import sidbarMenuMin from "@search/json/search/json/sidbarMenuMin.json";

import tableActions from "@search/json/search/json/listTableContextMenu";
import { useSearchStore } from "@search/stores/searchStore";

export default {
  name: "searchChart",

  setup() {
    useHead({
      title: import.meta.env.VITE_ENTITY_PAGE_TITLE,
      meta: [{ name: "description", content: "My page description" }],
      bodyAttrs: {
        class: import.meta.env.VITE_SEARCH_PAGE_TITLE,
      },
    });
    definePageMeta({
      layout: false,
      name: "searchChart",
    });
  },

  mounted() {
    let schemaExist =
      this.searchChartActiveTabGetter && this.searchChartSchemaGetter;

    if (schemaExist) {
      this.dataBankSelectValue = this.searchChartActiveSchemaGetter;
      this.schemaFilters = this.searchChartActiveTabGetter?.chartBase?.items[0];
      this.pieModel = this.searchChartActiveTabGetter?.chartType?.items[0];

      // when component load, setting default chart component to load based on the active tab.
      this.chartComponentName = this.searchChartActiveTabGetter.componentName;

      this.intiChartData();
    } else this.getSchemas();

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

    if (this.searchChartActiveTabGetter?.key == "tree-graph") {
      this.showInCharts = false;
    } else {
      this.showInCharts = true;
    }
  },
  data() {
    return {
      dataBankSelectValue: {},
      searchingState: false,

      showFilter: false,
      listFilter: [],
      dataChart: [],
      chartComponentName: chartType[0].componentName,
      pieModel: undefined,
      schemaFilters: undefined,
      listAmplify: [],
      // addressBarUrl: null,

      viewMode: "table",
      tableTitle: "  فهرست کدهای تقیح 51 گانه  /  آمار، برنامه و بودجه ",
      changePageFilter: "",

      lastSearchInListMode: true,
      showfilterCategory: true,
      activeListItem: undefined,
      treeLists: "",
      filterUrl: "",
      page: 0,
      activeTab: "",
      // activeTab: null,
      fetchingDataForExport: false,
      componentCounter: 1,
      selectedNavigationIndex: undefined,
      selectedNavigation: undefined,
      navigationOptions: [],
      fields: [],
      statusPag: "",
      fieldOne: null,
      fieldTwo: null,
      fieldThree: null,

      listPanelSorting: undefined,
      listPanelSorting: undefined,

      tableActions: tableActions,
      showListPanel: false,
      showInCharts: true,
      currentPageName: "list",

      sidbarMenuDefault: sidbarMenuDefault,
      sidbarMenuMin: sidbarMenuMin,

      canView: true,
      pagination: {
        pages: 0,
        total: 0,
        page: 1,
        offset: 0,
        limit: 10,
      },
      fetchingData: false,
      sorting: {
        sortby: "id",
        sortorder: "asc", // asc | desc
      },
      colors: [
        "#5470C6",
        "#d44646",
        "#008b8b",
        "#3BA272",
        "#FC8452",
        "#9A60B4",
        "#EA7CCC",
        "#F59F00",
        "#ddc4b0",
        "#73C0DE",
        "#b333ad",
        "#e86c6b",
        "#39cfed",
      ],
      currentIndex: 0,
    };
  },
  computed: {
    ...mapState(useCommonStore, [
      "currentUser",
      "organNameGetter",
      "isSidebarCollapsed",
    ]),
    ...mapState(useSearchStore, [
      "searchChartSchemaGetter",
      "searchChartActiveSchemaGetter",
      "searchChartActiveTabGetter",
    ]),

    getTableColumns() {
      let subjectIndex = this.fields.findIndex(
        (item) => item.name == "subject"
      );
      this.subjectItemState = false;
      this.subjectTitle = "";
      if (
        subjectIndex >= -1 &&
        this.listGetter != undefined &&
        subjectIndex == this.listGetter.length - 1
      ) {
        this.subjectItemState = true;
        this.subjectTitle = this.listGetter[subjectIndex]?.key;
        return this.selectedProjectGetter?.table_columns_subject;
      }
      return this.selectedProjectGetter?.table_columns;
    },
    repoUrl() {
      return import.meta.env.VITE_REPO + "/";
    },
    sidbarMenu() {
      if (isMajlesBuild()) return this.sidbarMenuMin;
      else return this.sidbarMenuDefault;
    },
  },
  methods: {
    ...mapActions(useSearchStore, [
      "SET_SELECTED_PROJECT",
      "SET_LIST",
      
      "searchChartActiveSchemaSetter",
      "searchChartSchemaSetter",
      "searchChartActiveTabSetter",
    ]),
    intiChartData() {
      if (
        this.searchChartActiveTabGetter?.key == "tree-graph"
        // ||
        // this.searchChartActiveTabGetter?.key == "Large-tree-map"
      ) {
        this.getListInTree();
      } else this.getChartData();
    },
    async getListInTree() {
      const payload = {
        parent: 0,
        sortby: "id",
        projectid: this.schemaFilters?.id,
        listtype: 0,
        limit: 100,
        listtype: 0,
      };
      let url = searchApis.chart.tree;
      try {
        const { $api } = useNuxtApp();
        const res = await $api(url, {
          baseURL: import.meta.env.VITE_REPO_BASE_URL,
          method: "POST",
          body: payload,
        });

        this.mainList = res.data;
        this.dataChart = [
          {
            key_filter: this.schemaFilters?.key_filter,
            projectId: this.schemaFilters?.id,
            name: this.schemaFilters?.label,
            children: this.ConvertDataToTree(this.mainList),
            item: "Root",
            id: "0",
            disabled: true,
            pid: "Root",
            opened: true,
            selected: false,
            text: "Root",
            label: {
              backgroundColor: "#ee6666",
            },
            itemStyle: {
              color: "#ee6666",
            },
          },
        ];
      } catch (err) {}
    },
    getNextColor() {
      // Get the color at the current index
      const color = this.colors[this.currentIndex];

      // Update the index to the next color
      this.currentIndex = (this.currentIndex + 1) % this.colors.length;

      return color;
    },
    ConvertDataToTree(list) {
      var finalList = [];
      list.forEach((element) => {
        const color = this.getNextColor();
        finalList.push({
          value: 0,
          item: element,
          value: element.title,
          name: element.title,
          text: element.title,
          id: element.id,
          pid: element.parent,
          collapsed: true,
          children: [],
          // children: element.children > 0 ? [1] : [],
          label: {
            backgroundColor: color,
          },
          itemStyle: {
            color: color,
          },
        });
      });
      return finalList;
    },
    // Basic data for all charts
    async getChartData() {
      let key = this.searchChartActiveSchemaGetter?.key;
      let url = this.makeApiUrl(key);

      // let otherParams = "";
      // if (this.addressBarUrl) otherParams = this.addressBarUrl;
      // url = url + otherParams

      try {
        const { $api } = useNuxtApp();
        const res = await $api(url);

        this.listFilter = res.aggregations ?? undefined;
        if (
          this.chartComponentName == "HiChartPie" ||
          this.chartComponentName == "HiChartXy"
        ) {
          this.preparePieAndLineData(res);
        } else if (this.chartComponentName == "MyTimeLine") {
          this.dataChart = res.result;
        } else this.dataChart = res.data;
      } catch (err) {
        this.dataChart = [];
      }
    },

    changeChart(e) {
      if (e.chartName == "دایره ای") {
        this.chartComponentName = "HiChartPie";
        this.pieModel = e;
        this.getChartData();
      } else if (e.chartName == "میله ای") {
        this.chartComponentName = "HiChartXy";
        this.pieModel = e;
        this.getChartData();
      }
    },
    changeFilter() {
      this.intiChartData();
    },
    // Set url for getChartData()
    makeApiUrl(type) {
      if (this.chartComponentName == "MyTimeLine") {
        let url = repoUrl() + searchApis.chart.timeline;

        url = url.replace("{{appname}}", buildName());
        url = url.replace("{{index_key}}", type);

        if (this.filterUrl?.length) {
          url += "/" + this.filterUrl;
        }
        return url;
      } else if (
        this.chartComponentName == "HiChartPie" ||
        this.chartComponentName == "HiChartXy"
      ) {
        let url = repoUrl() + searchApis.chart.xy;
        url = url.replace("{{appname}}", buildName());
        url = url.replace("{{index_key}}", type);
        if (this.schemaFilters?.key)
          url = url.replace("{{field_key}}", this.schemaFilters?.key);
        else url = url.replace("/{{field_key}}", "");

        if (this.filterUrl?.length) {
          url += "/" + this.filterUrl;
        }

        return url;
      } else if (
        this.chartComponentName == "largeTreeMapChart" ||
        this.chartComponentName == "HiChartTreegraph"
      ) {
        let url = "";
        let filter = "";
        if (this.filterUrl?.length) {
          filter += this.filterUrl;
        }

        url = searchApis.chart.chartTreeMap;
        url = url.replace("{{chart_key}}", this.schemaFilters?.key);
        // url = url.replace("{{chart_key}}", this.schemaFilters?.key_filter);
        if (filter) url = url.replace("{{filter}}", filter);
        else url = url.replace("/{{filter}}", "");

        return url;
      } else {
        let field_key = this.navigationItem.name;
        let url = repoUrl() + searchApis.chart.xy;
        url = url.replace("{{appname}}", buildName());
        url = url.replace("{{index_key}}", type);
        url = url.replace("{{field_key}}", field_key);

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

        if (this.filterUrl?.length) {
          url += "/" + this.filterUrl;
        }

        return url;
      }
    },
    // Set data for charts
    preparePieAndLineData(res) {
      // this.dataTreeMap = res.data ?? undefined;
      this.dataChart = res.aggregations.result.buckets.map((item) => {
        return {
          name: item.key,
          y: item.doc_count,
        };
      });

      if (res.aggregations.result.sum_other_doc_count > 0) {
        this.dataChart.push({
          name: "-سایر-",
          y: res.aggregations.result.sum_other_doc_count,
        });
      }
    },

    canSee(keyName) {
      if (this.currentUser?.user_level > 1) return true;
      return this.userPermisionGetter.includes(keyName);
    },
    onChangeAmplify(data) {
      this.amplifyIndex = data;
      this.changeAmplify();
    },
    onChangeType(data) {
      this.searchType = data;
      this.changeType();
    },
    onChangeCode(data) {
      this.searchCode = data;
      this.changeCode();
    },
    switchViewMode(mode) {
      this.viewMode = mode;
    },
    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;
      }
    },
    updateTitle(list) {
      this.tableTitle = list.title;
    },
    updateCategoryList(navItem, index) {
      if (navItem.key == "tree-graph") {
        this.showInCharts = false;
      } else {
        this.showInCharts = true;
      }
      this.searchChartActiveTabSetter(navItem);
      this.chartComponentName = navItem.componentName ?? "HiChartPie";
      this.schemaFilters = navItem?.chartBase?.items[0] ?? undefined;
      this.pieModel = navItem?.chartType?.items[0] ?? undefined;

      // this.activeTab = navItem;
      // if (navItem.label == "پایش زمانی") {
      //   this.chartComponentName = "MyTimeLine";
      // }
      // else if (navItem.label == "دسته‌ای")
      //   this.chartComponentName = "HiChartPie";
      // else if (navItem.label == "درختی موضوعی")
      //   this.chartComponentName = "largeTreeMapChart";
      // else if (navItem.label == "تجمیعی موضوعی")
      //   this.chartComponentName = "HiChartTreegraph";

      // if (this.chartComponentName == "HiChartTreegraph") this.getListInTree();
      // else this.getChartData();
      this.intiChartData();
    },

    listChanged(tags) {
      let res = [];
      tags.split(",").forEach((e) => {
        let i = e.lastIndexOf("_");
        if (i != -1) {
          res.push(e.substring(0, i));
        }
      });
      this.setFilterNavigate(res);
    },
    setFilterNavigate(value = []) {
      this.filterNavigate = value;
    },
    filterUpdate: function (filter) {
      this.filterUrl = filter;
      this.page = 0;

      this.getChartData();

      // if (this.searchingState) this.getQuery(false, true);
      // else this.getDefaultByFilter();
    },

    async getSchemas(item) {
      try {
        const { $api } = useNuxtApp();
        const res = await $api(searchApis.schema.list, {
          baseURL: repoUrl(),
          method: "POST",
          body: {
            organ: this.organNameGetter,
            system: "navigateChart",
            build_state: buildState(),
          },
        });

        this.searchChartSchemaSetter(res.data.navigateChart);
        this.searchChartActiveSchemaSetter(res.data.navigateChart[0]);
        this.searchChartActiveTabSetter(res.data.navigateChart[0].items[0]);

        this.dataBankSelectValue = this.searchChartActiveSchemaGetter;

        this.getChartData();
      } catch (err) {}
    },
    //mehdi
    AddToFolder(text) {
      if (this.selectedProjectGetter.lists.length) {
        if (text == "positionOne") {
          let myString = this.selectedProjectGetter.lists[0].items;
          let myArray1 = myString.split(",");
          let myArray2 = this.selectedProjectGetter.items;
          let myArray3 = [];
          for (let i = 0; i < myArray1.length; i++) {
            for (let j = 0; j < myArray2.length; j++) {
              if (myArray1[i] === myArray2[j].name) {
                myArray3.push(myArray2[j]);
                break;
              }
            }
          }
          this.fieldOne = myArray3[0];
          this.fieldTwo = myArray3[1];
          this.fieldThree = myArray3[2];
          setTimeout(() => {
            this.onComboChanged();

            this.componentCounter++;
          }, 300);
        } else if (text == "positionTow") {
          let myString = this.selectedProjectGetter.lists[1].items;
          let myArray1 = myString.split(",");
          let myArray2 = this.selectedProjectGetter.items;
          let myArray3 = [];
          for (let i = 0; i < myArray1.length; i++) {
            for (let j = 0; j < myArray2.length; j++) {
              if (myArray1[i] === myArray2[j].name) {
                myArray3.push(myArray2[j]);
                break;
              }
            }
          }
          this.fieldOne = myArray3[0];
          this.fieldTwo = myArray3[1];
          this.fieldThree = myArray3[2];
          setTimeout(() => {
            this.onComboChanged();

            this.componentCounter++;
          }, 300);
        } else {
          let myString = this.selectedProjectGetter.lists[2].items;
          let myArray1 = myString.split(",");
          let myArray2 = this.selectedProjectGetter.items;
          let myArray3 = [];
          for (let i = 0; i < myArray1.length; i++) {
            for (let j = 0; j < myArray2.length; j++) {
              if (myArray1[i] === myArray2[j].name) {
                myArray3.push(myArray2[j]);
                break;
              }
            }
          }
          this.fieldOne = myArray3[0];
          this.fieldTwo = myArray3[1];
          this.fieldThree = myArray3[2];
          setTimeout(() => {
            this.onComboChanged();

            this.componentCounter++;
          }, 300);
        }
      }
    },

    openNavigationFilter(item) {
      // if (item == 1) {
      //   this.$refs.pags.classList.add("position1");
      //   this.$refs.pags.classList.remove("position2");
      // } else {
      //   this.$refs.pags.classList.add("position2");
      //   this.$refs.pags.classList.remove("position1");
      // }
      // this.$refs.navigationFilter.classList.remove("d-none");
    },
    statusPag2($event) {
      this.statusPag = $event;
      // if(this.statusPag=3){
      //   this.showtextpag=false;
      // }else if (this.statusPag=2){
      //   this.showtextpag=true;
      // }
      switch (this.statusPag) {
        case (this.statusPag = 2):
          this.$refs.pags.classList.add("position1");
          this.$refs.pags.classList.remove("position2");
          break;
        case (this.statusPag = 1):
          this.$refs.pags.classList.add("position2");
          this.$refs.pags.classList.remove("position1");
          break;
      }
    },
    isShowPag(event) {
      // this.$refs.navigationFilter.classList.add("d-none");
      // this.$refs.navigationFilter.classList.remove("position2");
    },

    //mehdi

    exportJsonToExcel(evt) {
      if (evt === "current") {
        convertJsonToExcelUsingPlugin(
          this.filterColumns(this.listItem, this.getTableColumns),
          this.listGetter[this.listGetter.length - 1].key
        ).finally(() => {
          this.fetchingDataForExport = false;
        });
      } else if (evt === "all") {
        if (this.pagination.total > 500) {
          this.mySwalConfirm({
            title: "خطا!!!",
            html: "حداکثر تعداد قابل خروجی گرفتن، 500 مورد می باشد.لطفا با مدیریت تماس بگیرید.",
          }).then((result) => {
            this.getAllListItemForExport(500)
              .then((response) => {
                convertJsonToExcelUsingPlugin(
                  this.filterColumns(response.hits.hits, this.getTableColumns),
                  this.listGetter[this.listGetter.length - 1].key
                )
                  .then(() => {})
                  .finally(() => {
                    this.fetchingDataForExport = false;
                  });
              })

              .finally(() => {
                this.fetchingDataForExport = false;
              });
          });
        } else {
          this.getAllListItemForExport()
            .then((response) => {
              convertJsonToExcelUsingPlugin(
                this.filterColumns(response.hits.hits, this.getTableColumns),
                this.listGetter[this.listGetter.length - 1].key
              )
                .then(() => {})
                .finally(() => {
                  this.fetchingDataForExport = false;
                });
            })

            .finally(() => {
              this.fetchingDataForExport = false;
            });
        }
      }
    },
    filterColumns(listItem, columns) {
      let clonedItems = structuredClone(listItem);
      let clonedColumns = structuredClone(columns);
      let filteredItems = [];

      clonedItems.forEach((item, index) => {
        let filterObject = {};

        clonedColumns.forEach((j) => {
          filterObject[j.title] = item[j.key];
        });

        filteredItems[index] = filterObject;
      });
      return filteredItems;
    },
    async getAllListItemForExport(maxAmount = undefined) {
      if (this.fetchingDataForExport) return;
      this.fetchingDataForExport = true;

      let url =
        repoUrl() +
        searchApis.navigation.reportItem +
        `/${this.searchChartActiveSchemaGetter?.index_name}`;

      url += `/${this.sorting.sortby}/${this.sorting.sortorder}`;
      url += `/0/${maxAmount ?? this.pagination.total}/`;

      if (this.listGetter && this.listGetter.length) {
        if (this.listGetter.length <= this.fields.length) {
          for (let i = 0; i < this.listGetter.length; i++) {
            url += `${this.fields[i].name}=${this.listGetter[i].key}`;
            if (i != this.listGetter.length - 1) url += "&";
          }
        }
      }

      try {
        const { $api } = useNuxtApp();
        const res = await $api(url, {
          baseURL: repoUrl(),
          method: "POST",
          body: {
            organ: this.organNameGetter,
            system: "navigateChart",
            build_state: buildState(),
          },
        });
        return res;
      } catch (err) {}
    },

    async updateOrder({ rowItem, newOrder }) {
      const res = rowItem.subject.filter(
        (item) => item.title == this.listGetter[this.listGetter.length - 1].key
      );

      const payload = {
        id: rowItem.id_store,
        subject_id: res[0].id,
        subject_title: res[0].title,
        subject_order: +newOrder,
      };

      const url = repoUrl() + searchApis.subject.order;

      try {
        const { $api } = useNuxtApp();
        const res = await $api(searchApis.schema.list, {
          baseURL: repoUrl(),
          method: "POST",
          body: payload,
        });

        this.mySwalToast({
          title: res.message,
          html: "",
        });
      } catch (err) {}
    },
    async getComboList() {
      if (this.fetchingData) return;
      this.fetchingData = true;

      let url = repoUrl() + searchApis.navigation.list;
      url = url.replace("~/entity", this.searchChartActiveSchemaGetter?.key);

      try {
        const { $api } = useNuxtApp();
        const res = await $api(url, {
          baseURL: repoUrl(),
        });

        this.navigationOptions = res.data;

        this.navigationOptions[0].meta = JSON.parse(
          this.navigationOptions[0].meta
        );
        this.navigationOptions[0].table_columns = JSON.parse(
          this.navigationOptions[0].table_columns
        );
        this.navigationOptions[0].table_columns_subject = JSON.parse(
          this.navigationOptions[0].table_columns_subject
        );

        this.SET_SELECTED_PROJECT(this.navigationOptions[0]);
        this.fetchingData = false;
      } catch (err) {
        this.fetchingData = false;
      }
    },

    onSelectNavigation(evt) {
      // this.fieldOne = null;
      // this.fieldTwo = null;
      // this.fieldThree = null;
      // this.SET_LIST([]);
      // this.listItem = [];
      // this.fields = [];

      // if (typeof evt?.meta == "string") {
      //   try {
      //     evt.meta = JSON.parse(evt.meta);
      //     evt.table_columns = JSON.parse(evt.table_columns);
      //     evt.table_columns_subject = JSON.parse(evt.table_columns_subject);
      //   } catch (e) {}
      // }

      // this.selectedNavigation = evt;
      // this.searchChartSchemaSetter();
      // this.searchChartActiveTabSetter();
      this.searchChartActiveSchemaSetter(evt);

      this.getChartData();

      // this.$nextTick(() => {
      // this.componentCounter++;
      // });
    },
    onComboChanged() {
      this.SET_LIST([]);
      this.listItem = [];
      const vm = this;
      setTimeout(() => {
        vm.fields = [vm.fieldOne, vm.fieldTwo, vm.fieldThree].filter(
          (item) => item != null
        );
        vm.componentCounter++;
      }, 300);
    },
    toggleSidebarMenu() {
      this.$store.commit("TOGGLE_SIDEBAR_MENU");
    },
    showToggleListPanel() {
      this.showListPanel = !this.showListPanel;
    },
    searchInTable() {},

    getChartListItems() {
      const payload = {
        projectid: this.selectedProjectGetter?.id,
        item_state: this.selectedProjectGetter?.item_state,
        ...this.sorting,
        ...this.pagination,
      };

      const url =
        this.currentPageName == "list"
          ? listApis.item.listNotRel
          : listApis.item.subjectNotRel;

      ApiService.formData(url, payload)
        .then((res) => {
          this.listItem = res.data.data;
          this.pagination = { ...this.pagination, ...res.data.pagination };
        })
        .catch((err) => {
          handleErrors(err);

          // this.mySwalToast({
          //   title: response.data.message,
          //   html: "",
          //   text: "لطفا با پشتیبانی تماس بگیرید.",
          //   icon: "error",
          // });
        });
    },
  },
};
</script>

<style lang="scss">
.custom-filter-container {
  @media screen and (min-width: 575px) {
    background-color: rgba(0, 0, 0, 0.05);
  }

  .multiselect {
    // width: 16em;
    // border: 2px solid rgb(127, 170, 170) !important;
    border-radius: 0.5em;

    @media screen and (max-width: 575px) {
      .multiselect__tags {
        font-size: 0.8rem;
      }
    }
  }
}
</style>
<style scoped lang="scss">
.main-page__content-header {
  background: linear-gradient(to top, #fcfcfc 0%, #eee 90%);
  padding-top: 1em;
}
.multiselect {
  width: 12em;
  white-space: nowrap;
}
.header-height {
  height: 4em;
}
.nav-tabs-container {
  display: flex;
  justify-content: center;
}
.label-change {
  width: auto;
  // min-width: 5em;
  margin-bottom: 0em;
}

@media (max-width: 575.98px) {
  li.desktop:nth-child(n + 3) {
    display: none;
  }

  .dropdown-menu {
    a.dropdown-item:nth-child(-n + 2) {
      display: none;
    }
  }
  .header-height {
    height: 6em;
  }
}
@media only screen and (min-width: 576px) and (max-width: 767.98px) {
  li.desktop:nth-child(n + 4) {
    display: none;
  }
  .dropdown-menu {
    a.dropdown-item:nth-child(-n + 3) {
      display: none;
    }
  }
  .header-height {
    height: 6em;
  }
  .filter-list-container {
    padding-top: 0.5em;
    position: fixed;

    z-index: 9;
    width: auto;

    .main-filter {
      display: none;
    }
    .mobile-mode {
      display: flex;
      justify-content: flex-end;

      .btn {
        border-radius: 50%;
        // font-size: 0.7rem;
        width: 2.5em;
        height: 2.5em;
        box-shadow: 0px 0px 7px 1px #eee;
        display: flex;
        justify-content: center;
        align-items: center;
        transform: translateX(1.5em);
        background-color: #eee;

        &:hover {
          filter: brightness(0.8);
        }
      }
    }

    &.expanded {
      top: 0;
      bottom: 0;
      background: #fff;
      justify-content: center;
      box-shadow: -1px 0px 7px 1px #eee;

      .main-filter {
        display: block;
      }
    }
  }
}
@media only screen and (min-width: 768px) and (max-width: 991.98px) {
  .header-height {
    height: 6em;
  }
}
@media only screen and (min-width: 992px) and (max-width: 1199.98px) {
}
@media (min-width: 1200px) {
}
</style>
