<template>
  <NuxtLayout name="default" :menu="adminMenu">
    <div class="pages section-page px-3 pb-0 pt-2">
      <sub-header-with-select
        canCreate="sections_new"
        @open-form="toggleRolesPanel"
        :showProjectSelect="$attrs.showProjectSelect"
        :title="$t('Sections')"
      >
      </sub-header-with-select>

      <div class="pages-content pb-0 pt-2">
        <the-content-loading v-if="fetchingData"></the-content-loading>

        <template v-if="canView">
          <my-table
            :tableActions="tableActions"
            height="auto"
            maxHeight="calc(100vh - 15em)"
            class="my-table"
            ref="sectionsTable"
            :hasSearch="false"
            :paginationInfo="pagination"
            :sortingInfo="sorting"
            :items="sections"
            :fetchingData="fetchingData"
            :tableColumns="tableColumns"
            :totalPages="pagination.pages"
            @delete-table-item="deleteItem"
            @edit-table-item="toggleRolesPanel"
            @page-changed="pageChanged"
            @page-limit-changed="pageLimitChanged"
            @sort-changed="sortChanged"
          ></my-table>
        </template>
        <no-data v-else>
          <p class="text-center p-3">
            <span class="tavasi tavasi-warning-circle"></span>
          </p>
        </no-data>

        <div class="side-panel" v-if="showRoles">
          <div class="panel-form-header">
            <h6 class="">{{ $t("DepartmentManagement") }}</h6>
          </div>

          <div class="side-panel-content">
            <form class="form" role="section" @submit.prevent="save()">
              <div class="form-group">
                <label for="section_title">{{ $t("SectionTitle") }}</label>
                <input
                  type="text"
                  class="form-control"
                  id="section_title"
                  name="section_title"
                  v-model="selectedItemClone.section_title"
                />
              </div>

              <div class="form-group">
                <label for="action_title">{{ $t("ActionTitle") }} </label>
                <input
                  type="text"
                  class="form-control"
                  id="action_title"
                  name="action_title"
                  v-model="selectedItemClone.action_title"
                />
              </div>

              <div class="form-group">
                <label for="section_tag"> {{ $t("SectionTag") }}</label>
                <input
                  type="text"
                  dir="ltr"
                  class="form-control"
                  id="section_tag"
                  name="section_tag"
                  v-model="selectedItemClone.section_tag"
                />
              </div>

              <div class="form-group">
                <label for="action_tag"> {{ $t("ActionTag") }}</label>
                <input
                  type="text"
                  dir="ltr"
                  class="form-control"
                  id="action_tag"
                  name="action_tag"
                  v-model="selectedItemClone.action_tag"
                />
              </div>

              <div class="side-panel-footer mt-4">
                <div>
                  <button
                    type="submit"
                    class="btn btn-outline-primary"
                    :disabled="loading"
                    @click.prevent="save()"
                  >
                    <the-button-loading v-if="loading"></the-button-loading>
                    {{ $t("Submit") }}
                  </button>
                  <button
                    :disabled="loading"
                    @click.prevent="showRoles = false"
                    type="button"
                    class="btn btn-default"
                    data-dismiss="modal"
                  >
                    {{ $t("Cancel") }}
                  </button>
                </div>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </NuxtLayout>
</template>
<script>
import apis from "~/apis/permitApi";
import adminMenu from "~/json/admin/json/menu.json";
import { defineAsyncComponent } from "vue";
import { mapActions, mapState } from "pinia";
import { useCommonStore } from "~/stores/commonStore";
import { usePermitStore } from "~/stores/permitStore";

export default {
  name: "sections",
  setup() {
    definePageMeta({
      name: "sections",
      layout: false,
    });
  },
  mounted() {
    this.checkPermisionBeforGetList();
  },
  created() {
    this.httpService = useNuxtApp()["$http"];
  },
  watch: {
    projectGetter() {
      this.checkPermisionBeforGetList();
    },
    getPanelStatus() {
      this.toggleRolesPanel();
    },
  },
  data() {
    return {
      adminMenu: adminMenu,
      tableActions: [
        {
          showOutside: true,
          show: true,
          icon: "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: "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",
        },
      ],
      httpService: {},
      canView: false,
      fetchingData: false,
      changeDetectionCounter: 1,
      sections: [],
      loading: false,
      showRoles: false,
      showBackButton: false,
      selectedItemClone: {
        action_tag: "",
        action_title: "",
        section_tag: "",
        section_title: "",
        project_id: undefined,
        id: undefined,
      },
      prevSelectedItemIndex: undefined,
      sorting: {
        sortby: "",
        sortorder: "", // asc | desc
      },
      pagination: {
        page: 1,
        pages: 0,
        total: 0,
        offset: 0, // page * per_page
        limit: 10, //per_page
      },
      fetchingData: false,
      tableColumns: [
        {
          isLink: true,
          key: "section_title",
          title: this.$t("Title"),
          // title: "عنوان",
          width: "2",
        },
        {
          key: "action_title",
          title: this.$t("Action"),
          //  "فرایند",
          width: "2",
        },
        {
          key: "section_tag",
          title: this.$t("SectionTag"),
          //  "برچسب بخش",
          width: "4",
        },
        {
          key: "action_tag",
          title: this.$t("ActionTag"),
          // "برچسب فرایند",
          width: "4",
        },
      ],
    };
  },
  computed: {
    ...mapState(usePermitStore, ["projectGetter"]),
    ...mapState(useCommonStore, ["getPanelStatus"]),
  },
  methods: {
    ...mapActions(useCommonStore, ["checkPermissions"]),
    ...mapActions(usePermitStore, ["SET_PROJECT"]),

    async getSections() {
      this.fetchingData = true;
      const payload = {
        project_id: this.projectGetter?.id,
        isown: 3,
        ...this.sorting,
        ...this.pagination,
      };
      let url = permitUrl() + apis.sections.list;
      return await this.httpService
        .postRequest(url, payload)
        .then((res) => {
          this.sections = res.data;
          this.pagination = { ...this.pagination, ...res.pagination };
        })

        .finally(() => {
          this.fetchingData = false;
          this.changeDetectionCounter++;
        });
    },
    save() {
      const url = this.selectedItemClone.id
        ? apis.sections.edit
        : apis.sections.add;

      this.httpService
        .postRequest(permitUrl() + url, this.selectedItemClone)
        .then((res) => {
          this.getSections();

          mySwalToast({
            title: "تبریک",
            html: "اطلاعات با موفقیت ذخیره شد.",
            icon: "success",
          });

          this.showRoles = false;
          this.resetForm();
        });
    },

    deleteItem(index) {
      let sectionId = this.sections[index].id;

      const data = {
        project_id: this.projectGetter?.id,
        id: sectionId,
      };

      mySwalConfirm({
        title: "هشدار",
        html: "از حذف این بخش مطمئن هستید؟",
        icon: "warning",
      }).then((result) => {
        if (result.isConfirmed) {
          this.httpService
            .postRequest(permitUrl() + apis.sections.delete, data)
            .then((res) => {
              this.getSections();

              mySwalToast({
                title: "تبریک",
                html: "بخش با موفقیت حذف گردید.",
                icon: "success",
              });
            });
        }
      });
    },
    updateList() {
      this.resetPagination();
      this.getSections();
    },
    resetPagination() {
      this.pagination = {
        pages: 0,
        total: 0,
        page: 1,
        offset: 0,
        limit: 10,
      };
    },
    pageLimitChanged(paging) {
      this.resetPagination();
      this.pagination.limit = paging.limit;

      this.getSections();
    },
    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.getSections();
    },
    sortChanged(sorting) {
      // keep limit status.
      // reset page and offset values.

      this.pagination.page = this.pagination.offset = 0;
      this.sorting = sorting;

      this.getSections();
    },
    toggleRolesPanel(index = undefined) {
      if (index !== undefined) {
        if (this.prevSelectedItemIndex !== undefined)
          this.sections[this.prevSelectedItemIndex].active = false;

        this.prevSelectedItemIndex = index;
        this.sections[index].active = true;

        this.selectedItemClone = this.sections[index];
      } else this.resetForm();

      this.showRoles = true;
    },
    resetForm() {
      this.selectedItemClone = {
        id: undefined,
        action_tag: "",
        action_title: "",
        section_tag: "",
        section_title: "",
        project_id: this.projectGetter?.id,
      };
    },
    checkPermisionBeforGetList() {
      if (this.fetchingData) return;
      this.fetchingData = true;

      this.checkPermissions({ permission: "sections_view", _this: this })
        .then(() => {
          console.info("then");

          if (this.projectGetter) {
            this.getSections()
              .then(() => {
                this.canView = true;
                this.fetchingData = false;
              })
              .catch(() => {
                this.canView = false;
                this.fetchingData = false;
              });
          } else {
            console.info("getProjects");

            this.getProjects().then(() => {
              this.getSections()
                .then(() => {
                  this.canView = true;
                  this.fetchingData = false;
                })
                .catch(() => {
                  this.canView = false;
                  this.fetchingData = false;
                });
            });
          }
        })
        .catch((err) => {
          console.info(err);

          this.canView = false;
          this.fetchingData = false;
        });
    },
    async getProjects() {
      return await this.httpService
        .postRequest(permitUrl() + apis.projects.list)
        .then((res) => {
          console.log(
            "🚀 ~ returnawaitthis.httpService.postRequest ~ res:",
            res
          );
          this.SET_PROJECT(res.data[0]);
        });
    },
  },
  components: {
    // BreadCrumb: () => import("@components/BreadCrumb.vue"),
    // SubHeaderWithSelect: defineAsyncComponent(() =>
    //   import("@/components/global/SubHeaderWithSelect.vue")
    // ),
  },
};
</script>
