<template>
  <div>
    <div class="mb-5">
      <select
        name="project_id"
        id="project_id"
        v-model="project_id"
        class="form-control text__14"
      >
        <option class="text-black-50" disabled :value="undefined" selected>
          {{ $t("ProjectSelection") }}
        </option>

        <option
          v-for="(project, index1) in projects"
          :key="index1"
          :value="project.id"
        >
          {{ project.title }}
        </option>
      </select>
    </div>
    <div class="accordion" id="permission-accordion">
      <div
        v-for="(item, key, index) in groupbyList"
        :key="index"
        class="card border-0"
      >
        <div class="card-header border-bottom-0 p-0" :id="'heading' + index">
          <button
            class="btn btn-link btn-block has-indicator"
            type="button"
            data-bs-toggle="collapse"
            :data-bs-target="'#collapse' + index"
            :aria-expanded="!collapseAll"
            :class="{ collapsed: collapseAll }"
            :aria-controls="'collapse' + index"
          >
            {{ key }}
          </button>
        </div>
        <div
          :id="'collapse' + index"
          class="collapse"
          :class="{ show: !collapseAll }"
          :aria-labelledby="'heading' + index"
          data-parent="#permission-accordion"
        >
          <div class="card-body">
            <ul class="list-group list-group-flush">
              <li
                :key="index"
                v-for="(action, index2) in groupItems(key)"
                class="list-group-item text__14"
              >
                <div class="form-check d-flex align-items-center">
                  <input
                    v-can.checkbox="canEdit"
                    @change.prevent="changePermission(action)"
                    class="form-check-input"
                    type="checkbox"
                    value=""
                    :checked="action.check"
                    :value="action.check"
                    :id="'role-' + index2"
                  />
                  <label class="form-check-label mt-2" :for="'role-' + index">
                    {{ action.action_title }}
                  </label>
                </div>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

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

export default {
  props: {
    user_id: {
      type: Number,
      default: undefined,
    },
    role_id: {
      type: Number,
      default: undefined,
    },
    canEdit: {
      type: String,
      default(val) {},
    },
  },
  data() {
    return {
      listUserPermission: [],
      collapseAll: false,
      grouplist: [],
      groupbyList: {},
      roles: [],
      httpService: {},
    };
  },
  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);
      },
    },
  },
  mounted() {
    this.getRoles();
  },
  created() {
    this.httpService = useNuxtApp()["$http"];
  },
  methods: {
    // ...mapMutations("permit", ["SET_PROJECT"]),
    // ...mapActions("permit", ["getProjects"]),
    ...mapActions(usePermitStore, ["SET_PROJECT"]),
    ...mapActions(usePermitStore, ["getProjects"]),
    getRoles() {
      const payload = {
        user_id: this.user_id,
        role_id: this.role_id,
        project_id: this.projectGetter?.id,
      };

      const { listUserPermission, listRolePermission } = apis.permissions;
      const url = this.user_id ? listUserPermission : listRolePermission;

      this.httpService.postRequest(permitUrl() + url, payload).then(({ data }) => {
        
        this.listUserPermission = data;
        this.groupbyList = this.groupBy(data, "section_title");
      });
    },
    toggleRolesPanel() {},
    groupBy(arrayToGroup, key) {
      return arrayToGroup.reduce(function (previousValue, currentValue) {
        (previousValue[currentValue[key]] =
          previousValue[currentValue[key]] || []).push({
          action_title: currentValue.action_title,
          check: currentValue.check,
          section_title: currentValue.section_title,
          section_id: currentValue.id,
          section_user_id: currentValue?.section_user_id,
          section_role_id: currentValue?.section_role_id,
        });
        return previousValue;
      }, {});
    },
    groupItems(section_title) {
      return this.groupbyList[section_title];
    },
    changePermission(action) {
      action.check
        ? this.deletePermission(action)
        : this.addOrUpdatePermission(action);
    },
    addOrUpdatePermission(action) {
      const payload = {
        user_id: this.user_id,
        role_id: this.role_id,
        project_id: this.projectGetter?.id,
        section_id: action.section_id,
        state: 0,
        section_user_id: action.section_user_id ?? undefined,
        section_role_id: action.section_role_id ?? undefined,
      };

      const {
        addOrEditUserPermission,
        addOrEditRolePermission,
        addOrEditLoginRolePermission,
      } = apis.permissions;

      let url = this.user_id
        ? addOrEditUserPermission
        : addOrEditRolePermission;

      // حالت دسترسی تشویقی
      if (this.role_id === -1) url = addOrEditLoginRolePermission;

      this.httpService.postRequest(url, payload).then(({ data }) => {
        mySwalToast({
          title: "تبریک",
          html: data.message,
          icon: "success",
        });
        this.getRoles();
        // action.check = true;
      });
    },
    deletePermission(action) {
      const payload = {
        project_id: this.projectGetter?.id,
        id: action.section_user_id ?? undefined,
      };

      if (action.section_role_id) payload.id = action.section_role_id;

      const { deleteUserPermission, deleteRolePermission } = apis.permissions;
      const url = this.user_id ? deleteUserPermission : deleteRolePermission;

      this.httpService.postRequest(url, payload).then(({ data }) => {
        mySwalToast({
          title: "تبریک",
          html: data.message,
          icon: "success",
        });
        this.getRoles();
        // action.check = 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);
      this.getRoles();
    },
  },

  watch: {
    role_id() {
      this.getRoles();
    },
    user_id() {
      this.getRoles();
    },
  },
};
</script>

<style lang="scss" scoped>
.role-permission {
  .form-check {
    padding-right: 0;
  }
  .form-check-input {
    margin-left: 1em;
    margin-top: 0em !important;

    &::before {
      content: "";
      right: unset;
      top: unset;
    }
  }
}
</style>
