<template>
  <div class="row">
    <div class="col-12 py-3">
      <div class="d-flex align-items-center">
        <div class="col">
          <h3 class="m-0">
            {{ activeSchemaGetter?.label }}
          </h3>
        </div>
        <div class="col-auto">
          <router-link
            class="btn btn-primary"
            :to="{
              name: 'addDraft',
              key: activeSchemaGetter?.index_key,
            }"
          >
            <svg class="icon icon-Component-133--1">
              <use xlink:href="#icon-Component-133--1"></use>
            </svg>
            جدید
          </router-link>
        </div>
      </div>
    </div>
    <div class="col-12">
      <my-table
        :hasSearch="false"
        :fetchingData="fetchingData"
        :items="listDrafts"
        :tableActions="tableActions"
        :tableColumns="activeSchemaGetter?.table_columns"
        :paginationInfo="pagination"
        :sortingInfo="sorting"
        @edit-table-item="onEditTableItem"
        @delete-table-item="onDeleteTableItem"
        @on-linked-title-click="onLinkedTitleClick"
      />
    </div>
  </div>
</template>

<script>
import sidbarMenuDefault from "~/json/entity/json/entityMenu.json";
import sidbarMenuMajles from "~/json/entity/json/entityMenuMajles.json";
import { mapState, mapActions } from "pinia";
// import entityViewMixin from "~/entity/mixins/entityViewMixin.js";

import entityApi from "~/apis/entityApi";
import repoApi from "~/apis/repoApi";
import searchApi from "~/apis/searchApi";

/**
 * @vue-data {String} [readingMode="false"] - حالت مطالعه
 */
export default {
  beforeMount() {
    this.httpService = new HttpService(import.meta.env.VITE_BASE_URL);
  },
  mounted() {
    let schemaExist = typeof this.draftSchemaGetter == "object";

    if (!schemaExist) {
      this.getSchemas().then(() => {
        this.initData();
      });
    } else {
      this.initData();
    }

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

    // setDocumentTitle();
  },
  data() {
    return {
      tableActions: [
        {
          showOutside: true,
          show: true,
          icon: "tavasi tavasi-Component-242--1",
          title: "ویرایش",
          to: {
            name: "undefined",
          },
          selected: false,
          disabled: false,
          howToOpen: "",
          href: "",
          class: "edit-btn",
          action: "edit-table-item",
          // can: "subject-",
        },
        {
          showOutside: true,
          show: true,
          icon: "tavasi tavasi-Component-295--1",
          title: "حذف",
          to: {
            name: "undefined",
          },
          selected: false,
          disabled: false,
          howToOpen: "",
          href: "",
          class: "delete-btn",
          action: "delete-table-item",
        },
      ],
      pagination: {
        pages: 0,
        total: 0,
        page: 1,
        offset: 0,
        limit: 10,
      },
      sorting: {
        sortby: "created",
        sortorder: undefined, // asc | desc | none
      },
      listDrafts: [],
      currentDraft: {},
      activeSchemaGetter: [],
      httpService: undefined,
      fetchingData: false,
      sidbarMenuDefault: sidbarMenuDefault,
      sidbarMenuMajles: sidbarMenuMajles,
    };
  },
  computed: {
    ...mapState("entity", ["draftSchemaGetter"]),
    ...mapState(["isSidebarCollapsed", "currentUser"]),
    sidbarMenu() {
      if (isMajlesBuild()) return this.sidbarMenuMajles;
      else return this.sidbarMenuDefault;
    },
  },
  methods: {
    ...mapActions("entity", [
      "SET_ITEM_ENTITY",

      "draftSchemaSetter",
      "draftActiveSchemaSetter",
      "draftActiveStepSetter",
    ]),
    ...mapActions(["TOGGLE_PANEL"]),
    initData() {
      this.setActiveSchema();
      this.getDrafts();
    },
    setActiveSchema() {
      this.activeSchemaGetter = [];

      this.activeSchemaGetter = this.draftSchemaGetter.find(
        (item) => item.key == "list"
      );
    },

    async getSchemas() {
      let url = repoUrl() + entityApi.schema.list;

      return await this.httpService
        .postRequest(url, {
          organ: "majles",
          system: "edit",
        })
        .then((response) => {
          // console.log(response.data.edit);
          this.draftSchemaSetter(response.data.edit);

          let sch = response.data.edit.find((item) => item.key == "list");
          if (sch) this.draftActiveSchemaSetter(sch);
        })
        
    },
    getDrafts() {
      if (this.fetchingData) return;
      this.fetchingData = true;

      let url = repoUrl() + repoApi.entity.draftList;

      let key = this.activeSchemaGetter?.index_key ?? "dfqanon";
      url = url.replace("{{appname}}", buildName());
      url = url.replace("{{index_key}}", key);
      url = url.replace("{{sortKey}}", "lasttitle");
      url = url.replace("/{{filter}}", "");
      url = url.replace("{{offset}}", this.pagination.offset);
      url = url.replace("{{limit}}", this.pagination.limit);

      this.httpService.getRequest(url).then((res) => {
        this.listDrafts = res.hits.hits ?? [];

        const total = res.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.fetchingData = false;
      });
    },
    deleteEntity(index) {
      if (index < 0 || index >= this.listDrafts.length) return;
      this.currentDraft = this.listDrafts[index];

      if (!this.currentDraft || !this.currentDraft._id) return;

      let key = this.activeSchemaGetter?.index_key ?? "dfqanon";

      let url = repoUrl() + repoApi.entity.delete;
      url = url.replace("{{index_key}}", key);
      url = url.replace("{{entity_id}}", this.currentDraft._id);

      this.httpService
        .postRequest(url)
        .then((res) => {
          this.listDrafts = this.listDrafts.slice(index, 1);
          this.mySwalToast({
            html: res.data.message,
            icon: "success",
          });

          // this.getListSpecial(this.entity_type, this.listType);
          // this.updateListSpecial()
        })
        .catch((err) => {
          // this.mySwalToast({
          //   title: "خطا!!!",
          //   html: err.message,
          //   icon: "error",
          // });
        });
    },

    onLinkedTitleClick(data) {
      this.activeRowItem = data.rowItem;
      // let index = data.index;
      // let item = this.listDrafts[index];

      this.$router.push({
        name: "editDraft",
        params: {
          id: this.activeRowItem._id,
          key: this.activeSchemaGetter?.index_key,
        },
      });
    },

    onEditTableItem(index) {
      if (index < 0 || index >= this.listDrafts.length) return;
      this.currentDraft = this.listDrafts[index];

      this.$router.push({
        name: "editDraft",
        params: {
          id: this.currentDraft._id,
          key: this.activeSchemaGetter?.index_key,
        },
      });
    },
    onDeleteTableItem(index) {
      if (index < 0 || index >= this.listDrafts.length) return;
      this.currentDraft = this.listDrafts[index];

      if (this.currentDraft?._source?.islock) {
        this.mySwalToast({
          title: "ممنوع!!!",
          html: "این مورد بخاطر ثبت نهایی قفل شده است و امکان حذف ندارد",
          icon: "error",
        });
        return;
      }

      this.mySwalConfirm({
        title: "هشدار!!!",
        html: `از حذف اطلاعات جاری اطمینان دارید؟ `,
        icon: "warning",
      }).then((result) => {
        if (result.isConfirmed) {
          this.deleteEntity(index);
        }
      });
    },

    /**
     * تغییر وضعیت نمایش منوی سایدبار.
     */
    toggleSidebarMenu() {
      this.$store.commit("TOGGLE_SIDEBAR_MENU");
    },

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

      this.pagination.offset = this.pagination.page * paging.limit;
      this.pagination.limit = paging.limit;
      this.pagination.page = paging.pageNumber;
    },
    sortChanged(sorting) {
      this.resetPagination();
      this.sorting = sorting;
    },
  },


};
</script>
<style scoped lang="scss"></style>