<template>
  <div>
    <!-- <header>
      <the-navbar></the-navbar>
    </header>
    <the-sidebar :menu="menu"></the-sidebar> -->

    <main class="pages-content-container">
      <div class="pages-content mt-4 mt-lg-0">
        <div class="p-3" :class="{ 'd-flex': showPanel }">
          <div v-if="canView">
            <my-table
              :tableActions="tableActions"
              height="calc(100vh - 17em)"
              :hasSearch="true"
              maxHeight="calc(100dvh - 5em)"
              :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"
            >
              <template #tableHeaderActions>
                <button
                  v-if="!showPanel"
                  @click.prevent="openCreatePanel()"
                  class="btn btn-primary"
                  type="button"
                >
                  ایجاد
                </button>
              </template>
            </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 ml-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 mr-auto"
                type="button"
              >
                x
              </button>
            </div>

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

<script>
import apis from "~/apis/permitApi";
import { mapState, mapActions } from "pinia";

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

export default {
  beforeMount() {
    this.httpService = new HttpService(
      import.meta.env.VITE_BASE_URL + loginUrl()
    );
  },
  mounted() {
    this.checkPermisionBeforGetList();
  },
  // watch: {
  //   projectGetter() {
  //     this.showPanel = false;
  //     this.checkPermisionBeforGetList();
  //   },
  // },
  data() {
    return {
      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,
    };
  },

  methods: {
    ...mapState(["isSidebarCollapsed"]),

    ...mapActions(["checkPermissions"]),
    checkPermisionBeforGetList() {
      if (this.fetchingData) return;
      this.fetchingData = true;

      this.checkPermissions({ _this: this, permission: "modifications_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(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;

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

          this.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,
      };

      this.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;
              });

              this.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;
    },
  },

};
</script>
<style scoped lang="scss">
.side-panel-content {
  min-width: 19em;
}
</style>
