<template>
  <NuxtLayout name="default" :menu="adminMenu">
    <div>
      <Multiselect
        :allow-empty="false"
        :searchable="true"
        :close-on-select="true"
        :show-labels="false"
        :value="value"
        :options="options"
        class="multi mb-2"
        @select="select"
        label="label"
        track-by="key"
        placeholder="دسته"
        :hide-selected="false"
        :max-height="200"
        :max-width="200"
      >
      </Multiselect>
      <my-table
        height="auto"
        maxHeight="calc(100vh - 9em)"
        class="my-table"
        ref="sectionsTable"
        :hasSearch="false"
        :tableActions="tableActions"
        :items="sections"
        :tableColumns="tableColumns"
        :paginationInfo="pagination"
        :totalPages="pagination.pages"
        @delete-table-item="deleteItem"
        @edit-table-item="editTableItem"
        @page-changed="pageChanged"
        @page-limit-changed="pageLimitChanged"
        @sort-changed="sortChanged"
      >
        <!-- :fetchingData="fetchingData" :totalPages="pagination.pages"
      @delete-table-item="deleteItem" @edit-table-item="toggleRolesPanel"
      @page-changed="pageChanged" @page-limit-changed="pageLimitChanged"
      @sort-changed="sortChanged" -->
        <!-- :paginationInfo="pagination"
      :sortingInfo="sorting -->
      </my-table>
      <base-modal
        v-if="openSubjectForm"
        modalSize="modal-lg"
        :hasFooter="false"
        @close="closeModal"
      >
        <component
          :is="slotComponentName"
          :editList="editList"
          @close="closeModal"
        ></component>
      </base-modal>
    </div>
  </NuxtLayout>
</template>
<script>
import settingsApi from "~/apis/settingsApi";
import adminMenu from "~/json/admin/json/menu.json";
import { mapState, mapActions } from "pinia";
import searchApi from "~/apis/searchApi";
import { useStorage } from "@vueuse/core";
import { useCommonStore } from "~/stores/commonStore";

export default {
  name: "guidesList",
  setup() {
    definePageMeta({
      name: "guidesList",
      layout: false,
    });
  },
  computed: {
    ...mapState(useCommonStore, ["organNameGetter","helpSchemaGetter"]),

    // ...mapState(["organNameGetter"]),

    myActiveSchema() {
      return this.helpSchemaGetter?.find((item) => {
        return item.key == "help";
      });
    },
  },
  mounted() {
    let localStoageHelpSchema = useStorage("settingSchema", undefined).value;

    if (localStoageHelpSchema) {
      let helpSchema = JSON.parse(localStoageHelpSchema);
      this.helpSchemaSetter(helpSchema);
      this.options = this.myActiveSchema?.category;
      this.value = this.myActiveSchema?.category[0];
    } else {
      this.getSchemas();
    }
    this.getList();
  },
  data() {
    return {
      adminMenu: adminMenu,
      options: [{ name: "جستجو" }, { name: "محتوا" }, { name: "مطالعه" }],
      httpService: undefined,
      value: "",
      editList: "",
      slotComponentName: "",
      modalTitle: "",
      openSubjectForm: false,
      listSections: [],
      sections: [],
      tableActions: [
        {
          showOutside: true,
          show: true,
          icon: "tavasi tavasi-Component-242--1",
          title: this.$t("Edit"),
          to: {
            name: "undefined",
          },
          selected: false,
          disabled: false,
          howToOpen: "",
          href: "",
          class: "edit-btn",
          action: "edit-table-item",
          can: "item-info_edit",
        },
        {
          showOutside: true,
          show: true,
          icon: "tavasi tavasi-Component-295--1",
          title: this.$t("Delete"),
          to: {
            name: "undefined",
          },
          selected: false,
          disabled: false,
          howToOpen: "",
          href: "",
          class: "delete-btn",
          action: "delete-table-item",
          can: "item-list_delete",
        },
      ],
      tableColumns: [
        {
          isLink: true,
          key: "title",
          title: "عنوان سوال",
          width: "1",
        },
        {
          key: "description",
          title: "توضیحات",
          width: "6",
        },
      ],
      pagination: {
        page: 1,
        pages: 0,
        total: 0,
        offset: 0,
        limit: 10,
      },
      sorting: "",
    };
  },
  beforeMount() {
    // this.httpService = new HttpService(import.meta.env.VITE_REPO_BASE_URL);
    this.httpService = useNuxtApp()["$http"];
  },
  methods: {
    // ...mapActions("search", ["helpSchemaSetter"]),
    ...mapActions(useCommonStore, ["helpSchemaSetter"]),
    openModal(componentName, title) {
      this.openSubjectForm = true;
      this.slotComponentName = componentName;
      this.modalTitle = title;
      setTimeout(() => {
        $("#meta-item-modal").modal(
          { backdrop: "static", keyboard: false },
          "show"
        );
      }, 500);
    },
    closeModal() {
      $("#base-modal").modal({
        show: false,
      });

      setTimeout(() => {
        this.openSubjectForm = false;
        this.getList();
      }, 1000);
    },
    editTableItem(item) {
      this.editList = this.listSections[item];
      this.openModal("editModalItem", "فیلتر ها");
    },
    deleteItem(item) {
      mySwalConfirm({
        title: "هشدار!!!",
        html: "تمامی اطلاعات  پاک خواهد. آیا مطمئن هستید؟ ",
      }).then((result) => {
        if (result.isConfirmed) {
          var id = this.listSections[item]?._id;
          let url = settingsApi.help.delete;
          url = url.replace("{{id}}", id);
          this.httpService.postRequest(repoUrl() + url).then((response) => {
            mySwalToast({
              title: "با موفقیت حذف شد",
              // html: response.data.message,
              icon: "success",
            });
            this.getList();
          });
        }
      });
    },
    getList() {
      let url = settingsApi.help.list;
      url = url.replace("{{key_option}}", this.value?.key);
      url = url.replace("{{offset}}", this.pagination?.offset);
      url = url.replace("{{limit}}", this.pagination?.limit);
      this.httpService.getRequest(repoUrl() + url).then((response) => {
        let list = response.hits?.hits;
        this.listSections = list;
        if (this.sections.length >= 0) this.sections = [];
        // this.sections = response.hits.hits;
        list.forEach((element) => {
          this.sections.push(element?._source.meta);
        });

        const total = response.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 };

        // this.pagination = { ...this.pagination, ...response.pagination };
      });
    },
    getSchemas() {
      this.httpService
        .postRequest(repoUrl() + searchApi.schema.list, {
          organ: this.organNameGetter,
          system: "setting",
          build_state: buildState(),
        })
        .then((response) => {
          this.helpSchemaSetter(response.data?.setting);
          this.options = this.myActiveSchema?.category;
          this.value = this.myActiveSchema?.category[0];
          // this.options = response;
        });
    },
    select(e) {
      this.value = e;
      this.getList();
    },

    resetPagination() {
      this.pagination = {
        pages: 0,
        total: 0,
        page: 1,
        offset: 0,
        limit: 10,
      };
    },
    pageLimitChanged(paging) {
      this.resetPagination();
      this.pagination.limit = paging?.limit;

      this.getList();
    },
    pageChanged(paging) {
      let page = paging.pageNumber;
      page -= 1;
      this.pagination.offset = page * paging.limit;
      this.pagination.limit = paging.limit;
      this.pagination.page = paging.pageNumber;

      this.getList();
    },
    sortChanged(sorting) {
      this.pagination.page = this.pagination.offset = 0;
      this.sorting = sorting;

      this.getList();
    },
  },
};
</script>
<style scoped>
.multi {
  width: 200px;
  border: 2px solid rgb(127, 170, 170);
  border-radius: 0.5rem;
}
</style>