<template>
  <NuxtLayout name="default" :menu="adminMenu">
    <div class="pages user-role px-3 pb-0 pt-2">
      <sub-header-with-select
        canCreate="user-permission_new"
        @open-form="showShareModal()"
        :showProjectSelect="$attrs.showProjectSelect"
        title="کاربران"
      >
      </sub-header-with-select>

      <div class="pages-content d-flex pb-0 pt-2">
        <template v-if="canView">
          <my-table
            :tableActions="tableActions"
            height="auto"
            maxHeight="calc(100vh - 15em)"
            class="my-table"
            ref="userRolesTable"
            :hasSearch="false"
            :paginationInfo="pagination"
            :sortingInfo="sorting"
            :items="userRoles"
            :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>
          <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>
        <div class="side-panel" v-if="showPanel">
          <div class="side-panel-header">
            <h6 class="">مدیریت نقش ها</h6>
          </div>

          <div class="side-panel-content">
            <Accordion
              class="role-permission"
              canEdit="user-permission_edit"
              :user_id="user_id"
            ></Accordion>
            <div class="side-panel-footer mt-4">
              <div></div>
              <div>
                <button
                  @click.prevent="showPanel = false"
                  type="button"
                  class="btn btn-primary text-white"
                >
                  بستن
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <base-modal
        v-if="showModal"
        @close="closeModal"
        :showHeaderCloseButton="true"
        modalSize="modal-lg"
        :modalTitle="modalTitle"
        maxHeight="30em"
        :showDeleteButton="false"
      >
        <Share
          @update-user-role="updateUserRole"
          :roles="roles"
          :item="[]"
        ></Share>
      </base-modal>
    </div>
  </NuxtLayout>
</template>

<script>
// import apis from "@apis/permitApi";
// import { mapGetters, mapMutations, mapActions } from "vuex";
// import Share from "@apis/modal/Share.vue";
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: "UserPermission",
  setup() {
    definePageMeta({
      name: "UserPermission",
      layout: false,
    });
  },
  created() {
    this.httpService = useNuxtApp()["$http"];
  },
  mounted() {
    this.checkPermisionBeforGetList();
    this.getRoles();
    // this.cloneItems = structuredClone(this.items);
  },
  // watch: {
  // projectGetter() {
  // this.showPanel = false;
  // this.checkPermisionBeforGetList();
  // },
  // },
  props: {
    items: {
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      adminMenu: adminMenu,
      httpService: {},
      modalTitle: "اختصاص نقش به کاربر",
      tableActions: [
        {
          showOutside: true,
          show: true,
          icon: "Component-242--1",
          title: "ویرایش",
          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: "حذف",
          to: {
            name: "undefined",
          },
          selected: false,
          disabled: false,
          howToOpen: "",
          href: "",
          class: "delete-btn",
          action: "delete-table-item",
          can: "item-list_delete",
        },
      ],
      pagination: {
        page: 1,
        pages: 0,
        total: 0,
        offset: 0, // page * per_page
        limit: 10, //per_page
      },
      sorting: {
        sortby: "id",
        sortorder: "asc", // asc | desc
      },
      tableColumns: [
        {
          isLink: true,
          key: "full_name",
          title: "نام",
          width: "2",
        },
        {
          key: "role_name",
          title: "نقش",
          width: "2",
        },
        {
          key: "created_at",
          title: "تاریخ ثبت نام",
          width: "4",
        },
      ],
      canView: false,
      fetchingData: false,

      roles: [],
      section_user_id: undefined,
      section_role_id: undefined,

      user_id: undefined,
      role_id: undefined,
      loading: false,
      showPanel: false,
      userRoles: [],
      sections: [],
      selectedItem: {},

      showModal: false,
      typingTimer: 0,
      doneTypingInterval: 1000,
      collapseAll: false,
      editMode: false,

      searchForm: {
        query: "",
        replaceWith: "",
        wholeWord: false,
      },
    };
  },
  computed: {
    // ...mapGetters("permit", ["projectGetter"]),
    ...mapState(usePermitStore, ["projectGetter"]),
  },
  methods: {
    // ...mapActions(["checkPermissions"]),
    // ...mapMutations("permit", ["SET_PROJECT"]),
    ...mapActions(useCommonStore, ["checkPermissions"]),
    ...mapActions(usePermitStore, ["SET_PROJECT"]),

    updateUserRole(payload) {
      const formData = {
        ...payload,
        ...{ project_id: this.projectGetter?.id },
      };

      this.httpService
        .postRequest(permitUrl() + apis.roleUser.AddRoleUser, formData)
        .then((response) => {
          mySwalToast({
            title: "تبریک",
            html: response.data.message,
            icon: "success",
          });

          this.getUserRole();
        })
        .catch((err) => {
          mySwalToast({
            title: "خطا",
            html: err.response.data.message ?? err.message,
            icon: "error",
          });
        })
        .finally(() => {
          $("#share-modal").modal("hide");
          setTimeout(() => {
            this.showModal = true;
          }, 500);

          this.loading = false;
        });
    },
    getUserPermission() {
      this.user_id = this.selectedItem.user.id;
    },

    fullName(user) {
      if (user.name && user.lastname) return user.name + " " + user.lastname;
      else if (user.name && !user.lastname) return user.name;
      else if (!user.name && user.lastname) return user.lastname;
      return "بدون نام";
    },
    deleteItem(index) {
      const item = this.userRoles[index];

      var vm = this;
      mySwalConfirm({
        title: "هشدار!!!",
        html: "از حذف این مورد مطمئن هستید؟",
      }).then((result) => {
        if (result.isConfirmed) {
          this.httpService
            .postRequest(permitUrl() + apis.permissions.deleteUserRole, {
              project_id: vm.projectGetter?.id,
              id: item.id,
            })
            .then((response) => {
              vm.getUserRole();
            })
            .catch((err) => {
              vm.mySwalToast({
                title: "خطا",
                html: err.response.data.message ?? err.message,
                icon: "error",
              });
            })
            .finally(() => {
              vm.loading = false;
            });
        }
      });
    },
    async getUserRole() {
      const payload = {
        project_id: this.projectGetter?.id,
        isown: 3,
        ...this.sorting,
        ...this.pagination,
      };
      return await this.httpService
        .postRequest(permitUrl() + apis.permissions.listUserRole, payload)
        .then((response) => {
          this.userRoles = response.data;

          this.userRoles.forEach((item, key) => {
            item["role_name"] =
              item["role_name"] && item["role_name"] != 0
                ? item["role_name"]
                : "نقش حذف شده";

            this.userRoles[key] = {
              ...this.userRoles[key],
              ...{
                full_name: this.userRoles[key].user.full_name,
                user_id: this.userRoles[key].user.user_id,
              },
            };

            this.userRoles[key].created_at = convertUnixToPersianDateTime(
              item.created_at
            );
          });

          this.pagination = { ...this.pagination, ...response.pagination };
        })
        .catch((err) => {
          mySwalToast({
            title: "خطا",
            html: err.response.message ?? err.message,
            icon: "error",
          });
        })
        .finally(() => {
          this.loading = false;
        });
    },

    save() {
      // actions
    },

    showShareModal() {
      this.getRoles().then(() => {
        this.showModal = true;

        // setTimeout(() => {
        //   $("#share-modal").modal("show");
        // }, 500);
      });
    },
    closeModal() {
      this.showModal = false;
    },
    updateList() {
      this.resetPagination();
      this.getUserRole();
    },
    resetPagination() {
      this.pagination = {
        pages: 0,
        total: 0,
        page: 1,
        offset: 0,
        limit: 10,
      };
    },
    pageLimitChanged(paging) {
      this.resetPagination();
      this.pagination.limit = paging.limit;

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

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

      this.getUserRole();
    },

    toggleRolesPanel(userRolesIndex = 0) {
      this.getSections().then((res) => {
        this.sections = res.data.data;
        this.role_id = this.userRoles[userRolesIndex].role_id ?? undefined;
        this.user_id = this.userRoles[userRolesIndex].user_id ?? undefined;
      });

      this.showPanel = true;
    },
    async getSections() {
      return await this.httpService.postRequest(
        permitUrl() + apis.sections.list,
        {
          project_id: this.projectGetter?.id,
        }
      );
    },

    collapseAllPanels() {
      this.collapseAll = true;
    },
    expandAllPanels() {
      this.collapseAll = false;
    },

    sendQuery() {
      // todo: show loading.
      // todo: send query and show result.
      // todo: hide loading.

      clearTimeout(this.typingTimer);
      this.typingTimer = setTimeout(() => {
        this.highLight();
      }, this.doneTypingInterval);
    },
    onKeyDown() {
      clearTimeout(this.typingTimer);
    },
    async getRoles() {
      return await this.httpService
        .postRequest(permitUrl() + apis.roles.list, {
          project_id: this.projectGetter?.id,
        })
        .then((res) => {
          this.roles = res.data;
        });
    },
    checkPermisionBeforGetList() {
      if (this.fetchingData) return;
      this.fetchingData = true;

      this.checkPermissions({ permission: "user-permission_view", _this: this })
        .then(() => {
          if (this.projectGetter) {
            this.getUserRole()
              .then(() => {
                this.canView = true;
                this.fetchingData = false;
              })
              .catch(() => {
                this.canView = false;
                this.fetchingData = false;
              });
          } else {
            this.getProjects().then(() => {
              this.getUserRole()
                .then(() => {
                  this.canView = true;
                  this.fetchingData = false;
                })
                .catch(() => {
                  this.canView = false;
                  this.fetchingData = false;
                });
            });
          }
        })
        .catch(() => {
          this.canView = false;
          this.fetchingData = false;
        });
    },
    async getProjects() {
      return await this.httpService
        .postRequest(permitUrl() + apis.projects.list)
        .then((res) => {
          this.SET_PROJECT(res.data[0]);
        });
    },
  },
  components: {
    // BreadCrumb: () => import("@components/BreadCrumb.vue"),
    // Accordion: () => import("@components/Accordion.vue"),
    // SubHeaderWithSelect: defineAsyncComponent(() =>
    //   import("@/components/global/SubHeaderWithSelect.vue")
    // ),
    // TheContentLoading: defineAsyncComponent(() =>
    //   import("@/components/global/TheContentLoading.vue")
    // ),
    // MyTable: defineAsyncComponent(() =>
    //   import("@/components/global/MyTable.vue")
    // ),
    // NoData: defineAsyncComponent(() =>
    //   import("@/components/global/NoData.vue")
    // ),
    Share: defineAsyncComponent(() =>
      import("@/components/admin/modal/Share.vue")
    ),
    Accordion: defineAsyncComponent(() =>
      import("@/components/admin/components/Accordion.vue")
    ),
    // ShareModal: Share,
  },
};
</script>

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