<template>
  <NuxtLayout name="default" :menu="adminMenu">
    <div class="pages">
      <sub-header
        myClass="mt-0 mb-3"
        :hasViewMode="false"
        :showDetailsPanel="false"
        title="فهرست فرم‌ها"
        @show-details="newForm"
      ></sub-header>

      <div class="pages-content ps-1">
        <template v-if="canView">
          <my-table
            height="calc(100vh - 15em)"
            :isDraggable="false"
            :items="items"
            :fetchingData="fetchingData"
            :tableColumns="tableColumns"
            :tableActions="tableActions"
            :paginationInfo="pagination"
            :sortingInfo="sorting"
            @delete-table-item="deleteItem"
            @edit-table-item="editItem"
            @select-list-columns="selectListColumnsEdit"
            @show-details="showDetails"
            @page-changed="pageChanged"
            @page-limit-changed="pageLimitChanged"
            @sort-changed="sortChanged"
            @on-linked-title-click="onLinkedTitleClick"
          />
        </template>
        <no-data v-else>
          <the-content-loading v-if="fetchingData"></the-content-loading>

          <div v-else class="d-flex justify-content-center align-items-center">
            <div
              class="alert alert-warning d-flex justify-content-center align-items-center"
            >
              <span
                class="tavasi tavasi-warning-circle color-inherit ms-1 text__32"
              ></span>
              عدم دسترسی
            </div>
          </div>
        </no-data>

        <FormShow
          v-if="shwoPreviewForm"
          :selectedItem="rowItem"
          :tableColumns="tableColumns"
          @edit-item="formShowEditItem"
          @close-form-show="closeFormShow"
        ></FormShow>
      </div>
    </div>
  </NuxtLayout>
</template>
<script>
import keyValueApi from "~/apis/keyValueApi";
import adminMenu from "~/json/admin/json/menu.json";
// import HttpService from "@services/httpService";
import tableActions from "~/json/admin/json/formListTableAction";
// import { mapGetters, mapMutations, mapActions } from "vuex";
import { mapState, mapActions } from "pinia";
import { defineAsyncComponent } from "vue";
import { useCommonStore } from "~/stores/commonStore";
import { usePermitStore } from "~/stores/permitStore";

export default {
  name: "formList",
  setup() {
    definePageMeta({
      name: "formList",
      layout: false,
    });
  },
  beforeMount() {
    this.httpService = useNuxtApp()["$http"];
  },
  mounted() {
    this.checkPermisionBeforGetList();
  },
  watch: {
    // if user clicked on the subheader component new button,
    getPanelStatus() {
      this.newForm();
    },
  },
  data() {
    return {
      adminMenu: adminMenu,
      canView: true,
      rowItem: {},
      shwoPreviewForm: false,
      httpService: undefined,

      sorting: {
        sortby: "created",
        sortorder: undefined, // asc | none
      },
      pagination: {
        pages: 0,
        total: 0,
        page: 1,
        offset: 0, // page * per_page
        limit: 10, //per_page
      },

      tableColumns: [
        { key: "value", title: "عنوان", width: "2", isLink: true },
        { key: "text", title: "توضیحات", width: "4" },
      ],
      tableActions: tableActions,
      fetchingData: false,
      buttonLoading: false,
      items: [],
    };
  },
  computed: {
    ...mapState(useCommonStore, ["getPanelStatus"]),
  },
  methods: {
    // ...mapMutations(["TOGGLE_PANEL"]),
    ...mapActions(useCommonStore, ["TOGGLE_PANEL"]),
    ...mapActions(useCommonStore, ["checkPermissions"]),
    // ...mapActions(["checkPermissions"]),
    checkPermisionBeforGetList() {
      this.checkPermissions({ permission: "forms_list", _this: this })
        .then(() => {
          this.getForms()
            .then(() => {
              this.canView = true;
            })
            .catch(() => {
              this.canView = false;
            })
            .finally(() => {
              this.fetchingData = false;
            });
        })
        .catch(() => {
          this.canView = false;
        });
    },
    onLinkedTitleClick({ rowItem, tableColumn }) {
      this.formShowEditItem(rowItem);
    },
    /*
       summary: redirect to selecting table columns page.

       @fires when user clicked on the its icon in the context menu dropdown.
       @param {index} String index of form in the forms array.

       @return void.
    */
    selectListColumnsEdit(index) {
      const formId = this.items[index].id;
      this.$router.push({
        name: "selectListColumnsEdit",
        params: { id: formId },
      });
    },
    /*
       summary: get list of the forms.

       @fires when mount hook executed.

       @return void.
    */
    async getForms() {
      if (this.fetchingData) return;
      this.fetchingData = true;

      const formData = {
        isown: 3,

        type: 1,
        ...this.sorting,
        ...this.pagination,
      };
      let url = keyValueUrl() + keyValueApi.forms.list;
      return await this.httpService
        .postRequest(url, formData)
        .then((response) => {
          this.items = response.data;
          this.pagination = { ...this.pagination, ...response.pagination };
        });
    },
    resetPagination() {
      this.pagination = {
        pages: 0,
        total: 0,
        page: 1,
        offset: 0,
        limit: 10,
      };
    },
    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.getForms();
    },
    pageLimitChanged(paging) {
      this.resetPagination();
      this.pagination.limit = paging.limit;

      this.getForms();
    },
    sortChanged(sorting) {
      // keep limit status.
      // reset page and offset values.
      this.pagination.page = this.pagination.offset = 0;
      this.sorting = sorting;

      this.getForms();
    },
    deleteItem(index) {
      if (this.buttonLoading) return;
      this.buttonLoading = true;

      const formData = {
        id: this.items[index].id,
      };
      let url = this.keyValueMicroServiceName + keyValueApi.forms.delete;
      mySwalConfirm({
        title: "هشدار!!!",
        html: "از حذف این مورد مطمئن هستید؟",
      }).then((result) => {
        if (result.isConfirmed) {
          this.httpService
            .postRequest(url, formData)
            .then((response) => {
              this.getForms();
            })

            .finally(() => (this.buttonLoading = false));
        }
      });
    },
    /*
       summary: edit item

       description:
       called from the form show panel.

       @fires when clicked on the form show edit button.

       @param {form} Object form object.

       @return void.
    */
    formShowEditItem({ id }) {
      this.$router.push({ name: "editForm", params: { id } });
    },
    /*
       summary: edit item

       description:
       called from the forms table.

       @fires when clicked on the forms table edit button.

       @param {formIndex} Number form index in the forms array.

       @return void.
    */
    editItem(formIndex) {
      const formId = this.items[formIndex].id;
      this.$router.push({ name: "editForm", params: { id: formId } });
    },
    newForm() {
      this.$router
        .push({ name: "newForm" })
        .then(() => this.TOGGLE_PANEL(false));
    },
    showDetails({ rowItem, show }) {
      this.rowItem = rowItem;
      this.shwoPreviewForm = true;
    },
    closeFormShow() {
      this.shwoPreviewForm = false;
    },
  },
  components: {
    // FormShow: () => import("@forms/forms/FormShow.vue"),
    FormShow: defineAsyncComponent(() =>
      import("@/components/admin/components/FormShow.vue")
    ),
  },
};
</script>

<style lang="scss"></style>
