<template>
  <NuxtLayout name="default" :menu="adminMenu">
    <div class="pages role-section-page p-3">
      <SubHeaderWithSelect
        :enableNewButton="false"
        :showProjectSelect="$attrs.showProjectSelect"
        @open-form="toggleRolesPanel()"
        title="دسترسی های کاربران"
      >
      </SubHeaderWithSelect>

      <div class="pages-content">
        <template v-if="canView">
          <div class="container">
            <div class="row">
              <div class="col-12 col-md-8 mx-auto">
                <ul class="nav nav-tabs mb-3">
                  <li
                    v-for="({ id, title }, index) in roles"
                    :key="index"
                    :value="id"
                    class="nav-item"
                  >
                    <a
                      class="nav-link text-center"
                      :class="{ active: activeTabIndex == index }"
                      :href="title"
                      @click.prevent="onTabClick(id, index)"
                    >
                      {{ title }}
                    </a>
                  </li>
                </ul>

                <Accordion
                  class="role-permission"
                  canEdit="role-permission_edit"
                  :role_id="role_id"
                ></Accordion>
              </div>
            </div>
          </div>
        </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>
    </div>
  </NuxtLayout>
</template>

<script>
// import apis from "@apis/permitApi";
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";
// import { DEFAULT_CONFIG } from "vue-codemirror";
// import { mapGetters, mapMutations, mapActions } from "vuex";

export default {
  name: "rolePermission",
  setup() {
    definePageMeta({
      name: "rolePermission",
      layout: false,
    });
  },
  mounted() {
    this.checkPermisionBeforGetList();
  },
  watch: {
    projectGetter() {
      this.checkPermisionBeforGetList();
    },
  },
  components: {
    Accordion: defineAsyncComponent(() =>
      import("@/components/admin/components/Accordion.vue")
    ),
  },
  created() {
    this.httpService = useNuxtApp()["$http"];
  },
  data() {
    return {
      adminMenu: adminMenu,
      roles: [],
      httpService: {},
      collapseAll: false,
      role_id: undefined,
      roleSection: [],
      canView: false,
      fetchingData: false,
      activeTabIndex: 0,
    };
  },
  computed: {
    // ...mapGetters("permit", ["projectsGetter", "projectGetter"]),
    ...mapState(usePermitStore, ["projectGetter", "projectsGetter"]),
    projects() {
      return this.projectsGetter ?? [];
    },
    project_id: {
      get() {
        return this.projectGetter?.id;
      },
      set(newVal) {
        this.setProject(newVal);
      },
    },
  },
  methods: {
    // ...mapActions(["checkPermissions"]),

    // ...mapMutations("permit", ["SET_PROJECT"]),
    // ...mapActions("permit", ["getProjects"]),

    ...mapActions(useCommonStore, ["checkPermissions"]),
    ...mapActions(usePermitStore, ["SET_PROJECT"]),
    ...mapActions(usePermitStore, ["getProjects"]),

    onTabClick(id, index) {
      this.activeTabIndex = index;
      this.role_id = id;
    },
    async getRoles() {
      return await this.httpService
        .postRequest(permitUrl() + apis.roles.list, {
          project_id: this.projectGetter?.id,
        })
        .then((response) => {
          
          this.roles = response?.data;

          this.role_id =
            this.roles && this.roles[0] ? this.roles[0].id : undefined;
        });
    },
    checkPermisionBeforGetList() {
      if (this.fetchingData) return;
      this.fetchingData = true;

      this.checkPermissions({ permission: "role-permission_view", _this: this })
        .then(() => {
          if (this.projectGetter) {
            this.getRoles()
              .then(() => {
                this.canView = true;
                this.fetchingData = false;
              })
              .catch(() => {
                this.canView = false;
                this.fetchingData = false;
              });
          } else {
            this.getProjects().then(() => {
              this.getRoles()
                .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]);
        });
    },
    setProject(id) {
      // const id = +$ev.target.value;
      const result = this.projects.findIndex((item) => item.id === id);
      const project = this.projects[result];

      this.SET_PROJECT(project);
    },
  },
};
</script>