<template>
  <NuxtLayout name="default" :menu="adminMenu">
    <div class="main-users">
      <!-- <header>
        <the-navbar></the-navbar>
      </header> -->
      <!-- <the-sidebar :menu="menu"></the-sidebar> -->

      <main class="pages-content-container">
        <div class="pages-content mt-lg-0">
          <div :class="{ 'd-flex': showPanel }">
            <div v-if="canView">
              <my-table
                :tableActions="tableActions"
                height="calc(100vh - 17em)"
                :hasSearch="true"
                :paginationInfo="pagination"
                :sortingInfo="sorting"
                :items="users"
                :fetchingData="fetchingData"
                :tableColumns="tableColumns"
                :totalPages="pagination.pages"
                @search="searchGroups"
                @reset-form="searchUsers"
                @delete-table-item="deleteItem"
                @edit-table-item="toggleUsersPanel"
                @page-changed="pageChanged"
                @page-limit-changed="pageLimitChanged"
                @sort-changed="sortChanged"
              >
                <slot name="tableHeaderActions">
                  <button
                    v-if="!showPanel"
                    @click.prevent="openCreatePanel()"
                    class="btn btn-primary add-user-btn"
                    type="button"
                  >
                    ایجاد
                  </button>
                  <span
                    v-if="!showPanel"
                    @click.prevent="openCreatePanel()"
                    class="add-user-svg"
                    type="button"
                  >
                    <svg class="icon icon-Component-133--1">
                      <use xlink:href="#icon-Component-133--1"></use>
                    </svg>
                  </span>
                </slot>
              </my-table>
            </div>
            <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 mx-5" v-if="showPanel">
              <div class="side-panel-header d-flex mb-3 pb-3 border-bottom">
                <h6 class="m-0">مدیریت کاربران</h6>

                <button
                  @click.prevent="toggleUsersPanel(undefined)"
                  class="btn btn-outline-primary me-auto"
                  type="button"
                >
                  x
                </button>
              </div>

              <div class="side-panel-content">
                <NewUserForm
                  :parentLoading="loading"
                  :userData="selectedItemClone"
                  @on-pass-by-emit="save"
                ></NewUserForm>
              </div>
            </div>
          </div>
        </div>
      </main>
    </div>
  </NuxtLayout>
</template>

<script>
import apis from "~/apis/permitApi";
import { mapState, mapActions } from "pinia";
import adminMenu from "~/json/admin/json/menu.json";
import { defineAsyncComponent } from "vue";
import { useCommonStore } from "~/stores/commonStore";
import { usePermitStore } from "~/stores/permitStore";

// import menu from "~/json/admin/json/menu.json";

export default {
  name: "adminUsers",
  setup() {
    definePageMeta({
      name: "adminUsers",
      layout: false,
    });
  },
  beforeMount() {
    //   this.httpService = new HttpService(
    //     import.meta.env.VITE_BASE_URL + loginUrl()
    //   );
    this.httpService = useNuxtApp()["$http"];
    // this.httpService + loginUrl();
  },
  mounted() {
    this.checkPermisionBeforGetList();
  },
  // watch: {
  //   projectGetter() {
  //     this.showPanel = false;
  //     this.checkPermisionBeforGetList();
  //   },
  // },
  data() {
    return {
      adminMenu: adminMenu,
      // menu: menu,
      firstTimeSearching: false,
      httpService: undefined,
      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",
        },
        {
          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",
        },
      ],
      canView: false,
      fetchingData: false,
      tableColumns: [
        {
          isLink: true,
          key: "name",
          title: "نام",
          width: "2",
        },
        {
          isLink: true,
          key: "lastname",
          title: "نام خانوادگی",
          width: "2",
        },
        {
          key: "username",
          title: "نام کاربری",
          width: "2",
        },
        {
          key: "email",
          title: "ایمیل",
          width: "2",
        },
        {
          key: "is_active",
          title: "فعال",
          width: "2",
        },
        {
          key: "admin",
          title: "مدیر",
          width: "2",
        },
        {
          key: "mobile",
          title: "موبایل",
          width: "2",
        },
        {
          key: "date_c",
          title: "ایجاد",
          width: "2",
        },
        {
          key: "last-signed-int",
          title: "آخرین ورود",
          width: "2",
        },
      ],
      pagination: {
        page: 1,
        pages: 0,
        total: 0,
        offset: 0,
        limit: 10,
      },
      sorting: {
        sortby: "name",
        sortorder: "asc", // asc | desc | none
      },
      users: [],
      loading: false,
      showPanel: false,
      selectedItemClone: undefined,

      prevSelectedItemIndex: undefined,
    };
  },
  computed: {
    ...mapState(usePermitStore, ["projectGetter"]),
    ...mapState(useCommonStore, ["isSidebarCollapsed"]),
    // ...mapState(["isSidebarCollapsed"]),
  },
  methods: {
    // ...mapActions(["checkPermissions"]),
    ...mapActions(useCommonStore, ["checkPermissions"]),
    checkPermisionBeforGetList() {
      if (this.fetchingData) return;
      this.fetchingData = true;

      this.checkPermissions({ _this: this, permission: "users_view" })
        .then(() => {
          this.getUsers()
            .then(() => {
              this.canView = true;
              this.fetchingData = false;
            })
            .catch(() => {
              this.canView = false;
              this.fetchingData = false;
            });
        })
        .catch(() => {
          this.canView = false;
          this.fetchingData = false;
        });
    },
    async searchUsers(query = "") {
      this.resetPagination();

      let url = apis.users.search;
      url = url.replace("{{offset}}", this.pagination.offset);
      url = url.replace("{{limit}}", this.pagination.limit);
      url = url.replace("{{sortby}}", this.sorting.sortby);
      url = url.replace("{{sortorder}}", this.sorting.sortorder);

      // removing '/' before query if query is empty.
      if (query) url = url.replace("{{query}}", query);
      else url = url.replace("/{{query}}", query);

      return await this.httpService.getRequest(url).then((res) => {
        this.users = res.data;
        this.pagination = { ...this.pagination, ...res.pagination };
      });
    },
    async getUsers() {
      let url = apis.users.list;

      url = url.replace("{{offset}}", this.pagination.offset);
      url = url.replace("{{limit}}", this.pagination.limit);
      url = url.replace("{{sortby}}", this.sorting.sortby);
      url = url.replace("{{sortorder}}", this.sorting.sortorder);

      return await this.httpService.getRequest(loginUrl() + url).then((res) => {
       
        this.users = res.data;
        this.pagination = { ...this.pagination, ...res.pagination };
      });
    },
    save(formData = undefined) {
      if (this.loading) return;
      this.loading = true;

      const url = formData.id ? apis.users.update : apis.users.create;

      this.httpService
        .postRequest(url, formData)
        .then((res) => {
          this.getUsers().then(() => {
            this.loading = false;
          });

          mySwalToast({
            html: res.message,
          });

          this.showPanel = false;
          this.resetForm();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    deleteItem(index) {
      if (this.loading) return;
      this.loading = true;

      let userId = this.users[index].id;
      const payload = {
        id: userId,
      };

      mySwalConfirm({
        title: "هشدار",
        html: "هشدار!!!!",
        icon: "warning",
      }).then((result) => {
        if (result.isConfirmed) {
          this.httpService
            .postRequest(apis.users.delete, payload)
            .then((res) => {
              this.getUsers().then(() => {
                this.loading = false;
                this.showPanel = false;
              });

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

      this.getUsers();
    },
    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.getUsers();
    },
    sortChanged(sorting) {
      this.pagination.page = this.pagination.offset = 0;
      this.sorting = sorting;

      this.getUsers();
    },
    openCreatePanel() {
      this.selectedItemClone = undefined;
      this.showPanel = true;
    },
    toggleUsersPanel(index = undefined) {
      if (index !== undefined) {
        if (this.prevSelectedItemIndex !== undefined)
          this.users[this.prevSelectedItemIndex].active = false;

        this.prevSelectedItemIndex = index;
        this.$set(this.users[index], "active", true);
        this.selectedItemClone = structuredClone(this.users[index]);

        this.showPanel = true;
      } else {
        this.resetForm();
      }
    },
    resetForm() {
      this.selectedItemClone = undefined;
      this.showPanel = false;
    },
  },
  components: {
    NewUserForm: defineAsyncComponent(() =>
       import("@/components/admin/components/NewUserForm.vue")
     ),
  },
};
</script>
<style scoped lang="scss">
.side-panel-content {
  min-width: 19em;
}
</style>