<script>
import LoadingButton from "@/components/LoadingButton.vue";
import ZohoSearch from "@/components/ZohoSearch.vue";
import { permissionsHandler } from "@/helpers/permissions-handler";
export default {
  name: "Departments",
  components: { LoadingButton, ZohoSearch },
  mixins: [permissionsHandler],
  data: () => ({
    departments: [],
    newDepartment: {},
    modal: null,
    selectedRow: {},
    leader: {},
  }),
  created() {
    this.$http.get("departments").then((response) => {
      this.departments = response.data.rows;
    });
  },
  mounted() {
    this.modal = new bootstrap.Modal(
      document.getElementById("department-modal"),
      {}
    );
  },
  methods: {
    selectUser(user) {
      if (user) {
        this.newDepartment.leader_id = user.id;
      }
    },
    handleSave() {
      this.$http
        .post(
          "departments/store",
          this.$helper.generateFormData(this.newDepartment)
        )
        .then((response) => {
          if (response.data.status) {
            if (!this.newDepartment.id) {
              this.departments.unshift(response.data.row);
            } else {
              let index = this.departments.findIndex(
                (row) => row.id == this.newDepartment.id
              );
              this.departments[index] = response.data.row;
            }
            this.modal.hide();
            this.newDepartment = {};
            this.$notify({
              type: "success",
              message: "department saved successfully",
            });
          }
        });
    },
    handleEdit(department) {
      this.newDepartment = { ...department };
      this.selectRow(department);
      this.modal.show();
    },
    handleDestroy(department, i) {
      this.$confirm({
        title: "Deleting",
        content: `Are you sure you want to delete ${department.name} from list of departments?`,
        actionText: "Yes, Continue",
        closeText: "Discard",
        classes: "btn btn-danger",
        action: () => {
          this.$http
            .get(`departments/destroy/${department.id}`)
            .then((response) => {
              if (response.data.status) {
                this.departments.splice(i, 1);
                this.$notify({
                  type: "success",
                  message: "Department deleted successfully",
                });
              }
            });
        },
      });
    },
    selectRow(row) {
      this.selectedRow = row;
      this.leader = row.leader;
    },
  },
};
</script>
<template>
  <div class="row justify-content-center">
    <div class="col-md-10">
      <div class="card">
        <div class="card-body">
          <div class="d-flex align-items-center mb-2">
            <h4>{{ $trans("Department") }} ({{ departments.length }})</h4>
            <button
              v-if="this.hasPermissionTo('C')"
              data-bs-toggle="modal"
              data-bs-target="#department-modal"
              class="btn btn-primary ms-auto"
            >
              <i class="uil uil-plus me-1"></i> {{ $trans("Add New") }}
            </button>
          </div>
          <div class="table-responsive">
            <table class="table align-middle table-nowrap table-check">
              <thead>
                <tr>
                  <th class="check" scope="col" style="width: 50px">
                    <div class="form-check font-size-16">
                      <input type="checkbox" class="form-check-input" />
                      <label class="form-check-label" for="checkAll"></label>
                    </div>
                  </th>
                  <th scope="col">{{ $trans("Name") }}</th>
                  <th scope="col">{{ $trans("Leader") }}</th>
                  <th scope="col">{{ $trans("Description") }}</th>
                  <th scope="col">{{ $trans("Status") }}</th>
                  <th style="width: 80px; min-width: 80px" class="action">
                    Action
                  </th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(department, i) in departments" :key="department.id">
                  <th class="check" scope="row">
                    <div class="form-check font-size-16">
                      <input
                        type="checkbox"
                        class="form-check-input"
                        :value="department.id"
                        :id="'checkbox-' + i"
                      />
                      <label
                        class="form-check-label"
                        :for="'checkbox-' + i"
                      ></label>
                    </div>
                  </th>
                  <td>
                    {{ department.name.toUpperCase() }}
                  </td>
                  <td>
                    {{ department.leader ? department.leader.name : "N/A" }}
                  </td>
                  <td>{{ department.description || "N/A" }}</td>
                  <td>
                    <div
                      class="badge bg-success font-size-12"
                      v-if="department.status == 1"
                    >
                      {{ $trans("Active") }}
                    </div>
                    <div class="badge bg-danger font-size-12" v-else>
                      {{ $trans("Disabled") }}
                    </div>
                  </td>
                  <td class="action">
                    <div>
                      <button
                        class="btn btn-light btn-sm dropdown-toggle"
                        type="button"
                        data-bs-toggle="dropdown"
                        aria-expanded="false"
                      >
                        <i class="uil uil-ellipsis-h"></i>
                      </button>
                      <ul class="dropdown-menu dropdown-menu-end">
                        <li v-if="this.hasPermissionTo('U')">
                          <a
                            class="dropdown-item"
                            @click.prevent="handleEdit(department)"
                            href="javascript:void(0)"
                            >{{ $trans("Edit") }}</a
                          >
                        </li>
                        <li v-if="this.hasPermissionTo('D')">
                          <a
                            class="dropdown-item"
                            @click.prevent="handleDestroy(department, i)"
                            href="javascript:void(0)"
                            >{{ $trans("Delete") }}</a
                          >
                        </li>
                      </ul>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div
    class="modal fade"
    tabindex="-1"
    id="department-modal"
    aria-labelledby="mySmallModalLabel"
    aria-hidden="true"
    style="display: none"
  >
    <div class="modal-dialog modal-dialog-centered">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">
            {{
              newDepartment.id ? $trans("Edit department") : $trans("Create a new department")
            }}
          </h5>
          <button
            type="button"
            class="btn-close"
            data-bs-dismiss="modal"
            aria-label="Close"
          ></button>
        </div>
        <div class="modal-body">
          <div class="mb-3 row">
            <label class="col-md-4 col-form-label required"
              >{{ $trans("Departments Name") }}</label
            >
            <div class="col-md-8">
              <input
                class="form-control"
                type="text"
                placeholder="Name"
                v-model="newDepartment.name"
              />
            </div>
          </div>
          <div class="mb-3 row">
            <label class="col-md-4 col-form-label required">{{ $trans("Leader") }}:</label>
            <div class="col-md-8">
              <ZohoSearch
                placeholder="Select User"
                url="users/search"
                label="name"
                :load-defaults="true"
                @selected="selectUser"
                :default-row="leader"
              ></ZohoSearch>
            </div>
          </div>
          <div class="mb-3 row">
            <label class="col-md-4 col-form-label">{{ $trans("Description") }}</label>
            <div class="col-md-8">
              <textarea
                class="form-control"
                placeholder="Optional Comment"
                v-model="newDepartment.description"
              ></textarea>
            </div>
          </div>
          <div class="row">
            <div class="col-md-4"></div>
            <div class="col-md-8">
              <loading-button
                task="CREATING_DEPARTMENT"
                class="btn btn-primary"
                type="button w-100"
                @clicked="handleSave"
                :disabled="!newDepartment.name"
              >
                <template #caption>{{ $trans("Save and Close") }}</template>
              </loading-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
