<template>
  <div class="pages access-page p-3">
    <sub-header-with-select
      @open-form="toggleRolesPanel()"
      :showProjectSelect="$attrs.showProjectSelect"
      title="تنظیم دسترسی کاربران"
    >
      <!--      <button-->
      <!--          @click="toggleRolesPanel()"-->
      <!--          class="btn btn-outline-primary position-relative"-->
      <!--          type="button">-->
      <!--        اختصاص نقش جدید-->
      <!--      </button>-->
    </sub-header-with-select>

    <div class="pages-content d-flex">
      <div class="table-responsive">
        <table class="table table-borderless table-hover">
          <thead>
            <tr>
              <th colspan="12" class="px-0">
                <form class="table-search-form" role="search">
                  <div class="form-group">
                    <div class="input-group">
                      <div class="input-group-prepend">
                        <span class="input-group-text">
                          <svg
                            class=""
                            aria-hidden="true"
                            focusable="false"
                            data-prefix="fas"
                            data-icon="search"
                            role="img"
                            xmlns="http://www.w3.org/2000/svg"
                            viewBox="0 0 512 512"
                            data-fa-i2svg=""
                          >
                            <path
                              fill="currentColor"
                              d="M505 442.7L405.3 343c-4.5-4.5-10.6-7-17-7H372c27.6-35.3 44-79.7 44-128C416 93.1 322.9 0 208 0S0 93.1 0 208s93.1 208 208 208c48.3 0 92.7-16.4 128-44v16.3c0 6.4 2.5 12.5 7 17l99.7 99.7c9.4 9.4 24.6 9.4 33.9 0l28.3-28.3c9.4-9.4 9.4-24.6.1-34zM208 336c-70.7 0-128-57.2-128-128 0-70.7 57.2-128 128-128 70.7 0 128 57.2 128 128 0 70.7-57.2 128-128 128z"
                            ></path>
                          </svg>
                        </span>
                      </div>
                      <input
                        v-model="searchForm.query"
                        type="search"
                        required
                        class="form-control"
                        id="search-query"
                        placeholder="جستجو..."
                        name="search-query"
                        aria-label="جستجو در اسناد، عناوین و واژگان"
                        aria-describedby="basic-addon1"
                        size="50"
                      />
                      <div class="input-group-append">
                        <button
                          :class="{
                            'show-reset-btn': searchForm.query.length > 0,
                          }"
                          type="button"
                          class="input-group-text"
                          id="basic-addon1"
                        >
                          <i class="tavasi tavasi-Component-294--1"></i>
                        </button>
                      </div>
                    </div>
                  </div>
                </form>
              </th>
            </tr>
          </thead>
          <thead>
            <tr>
              <th scope="col">#</th>
              <th scope="col">نام</th>
              <th scope="col">نقش</th>
              <th scope="col">تاریخ ثبت نام</th>
              <th scope="col">عملیات</th>
            </tr>
          </thead>
          <tbody>
            <template v-if="userRoles.length">
              <tr
                v-for="({ user, ...item }, index) in userRoles"
                :class="{ active: item.active ?? false }"
                :key="index"
              >
                <th scope="row">{{ index + 1 }}</th>
                <td>
                  <div class="user-info">
                    <div class="user-info-avatar">
                      <img :src="userAvatar(user)" :alt="fullName(user)" />
                    </div>
                    <div class="user-info-details">
                      <p class="name">
                        {{ fullName(user) }}
                      </p>
                      <p class="username">
                        @{{ user.username ?? "بدون نام کاربری" }}
                      </p>
                    </div>
                  </div>
                </td>
                <td>
                  <span>{{ item.role_name ?? "--" }}</span>
                </td>
                <td>
                  <span
                    >از
                    {{ convertUnixToPersianDateTime(item.created_at) }}</span
                  >
                </td>
                <td>
                  <button
                    @click="toggleRolesPanel(index)"
                    title="ویرایش"
                    class="btn edit-btn"
                    data-bs-toggle="modal"
                    data-bs-target="#edit-paper"
                  >
                    <i class="tavasi tavasi-Component-242--1"></i>
                  </button>
                  <!--                <button @click="deleteItem(item.id)" title="حذف"-->
                  <!--                        class="btn delete-btn"-->
                  <!--                        type="button"-->
                  <!--                >-->
                  <!--                  <img class="" src="@assets/common/img/Component 295 – 1.svg" alt="حذف"/>-->
                  <!--                </button>-->
                </td>
              </tr>
            </template>
            <table-no-data v-else></table-no-data>
          </tbody>
        </table>
      </div>

      <div class="side-panel" v-if="showPanel">
        <div class="side-panel-header">
          <h6 class="">مدیریت نقش ها</h6>
        </div>

        <div class="side-panel-content">
          <!--          <div class="mb-5">-->
          <!--            <label for="role_id">انتخاب بخش</label>-->
          <!--            <select @change="getUserPermission()" name="role_id" id="role_id"-->
          <!--                    class="form-control text__14">-->
          <!--              <template v-if="sections.length">-->
          <!--                <option disabled :value="undefined" selected>انتخاب بخش</option>-->

          <!--                <option v-for="({project_id,section_title},index) in sections"-->
          <!--                        :key="index" :value="project_id">{{ section_title }}-->
          <!--                </option>-->
          <!--              </template>-->

          <!--              <option v-else :value="undefined" selected>بخشی ثبت نشده است.</option>-->
          <!--            </select>-->
          <!--          </div>-->

          <accordion v-if="user_id" :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"
                data-dismiss="modal"
              >
                بستن
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <Share @onCloseModal="showModal = false" v-if="showModal"></Share>
  </div>
</template>

<script>
import apis from "@apis/permitApi";
import { mapState } from "pinia";
import { useCommonStore } from "~/stores/commonStore";

export default {
  name: "UserAccessCustomization",
  components: {
    BreadCrumb: () => import("@components/global/BreadCrumb.vue"),
    Share: () => import("@components/admin/modal/Share.vue"),
    Accordion: () => import("@components/admin/components/Accordion.vue"),
  },
  computed: {
    ...mapState(useCommonStore,["projectGetter"]),
  },
  props: {
    items: {
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      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,
      },
    };
  },
  methods: {
    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() {},
    getUserRole() {
      ApiService.formData(apis.permissions.listUserRole, {
        project_id: this.projectGetter?.id,
      })
        .then((response) => {
          this.userRoles = response.data.data;
        })
        .catch((err) => {})
        .finally(() => {
          this.loading = false;
        });
    },

    save() {
      // actions
    },

    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;
      });
    },
    getSections() {
      return ApiService.formData(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);
    },
  },
  mounted() {
    this.getUserRole();
    // this.cloneItems = structuredClone(this.items);
  },
  watch: {
    projectGetter() {
      this.showPanel = false;
      this.getUserRole();
    },
  },
};
</script>

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