<script>
import LoadingButton from "@/components/LoadingButton.vue";
import { permissionsHandler } from "@/helpers/permissions-handler";
export default {
  name: "Units",
  mixins: [permissionsHandler],
  components: { LoadingButton },
  data: () => ({
    units: [],
    newUnit: {},
    modal: null,
    selectedRow: {},
  }),
  created() {
    this.$http.get("stock/units").then((response) => {
      this.units = response.data.rows;
    });
  },
  mounted() {
    this.modal = new bootstrap.Modal(document.getElementById("unit-modal"), {});
  },
  methods: {
    handleSave() {
      this.$http
        .post("stock/units/store", this.$helper.generateFormData(this.newUnit))
        .then((response) => {
          if (response.data.status) {
            if (!this.newUnit.id) {
              this.units.unshift(response.data.row);
            } else {
              let index = this.units.findIndex(
                (row) => row.id == this.newUnit.id
              );
              this.units[index] = response.data.row;
            }
            this.modal.hide();
            this.newUnit = {};
            this.$notify({
              type: "success",
              message: "Unit saved successfully",
            });
          }
        });
    },
    handleEdit(unit) {
      this.newUnit = { ...unit };
      this.selectRow(unit);
      this.modal.show();
    },
    handleDestroy(unit, i) {
      this.$confirm({
        title: "Deleting",
        content: `Are you sure you want to delete ${unit.name} from list of units?`,
        actionText: "Yes, Continue",
        closeText: "Discard",
        classes: "btn btn-danger",
        action: () => {
          this.$http.get(`stock/units/destroy/${unit.id}`).then((response) => {
            if (response.data.status) {
              this.units.splice(i, 1);
              this.$notify({
                type: "success",
                message: "Unit deleted successfully",
              });
            }
          });
        },
      });
    },
    selectRow(row) {
      this.selectedRow = row;
    },
  },
};
</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("Product units") }} ({{ units.length }})</h4>
            <button
              v-if="this.hasPermissionTo('C')"
              data-bs-toggle="modal"
              data-bs-target="#unit-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("Description") }}</th>
                  <th style="width: 80px; min-width: 80px" class="action">
                    Action
                  </th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(unit, i) in units" :key="unit.id">
                  <th class="check" scope="row">
                    <div class="form-check font-size-16">
                      <input
                        type="checkbox"
                        class="form-check-input"
                        :value="unit.id"
                        :id="'checkbox-' + i"
                      />
                      <label
                        class="form-check-label"
                        :for="'checkbox-' + i"
                      ></label>
                    </div>
                  </th>
                  <td>
                    {{ unit.name.toUpperCase() }}
                  </td>
                  <td>{{ !unit.description ? "N/A" : unit.description }}</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(unit)"
                            href="javascript:void(0)"
                            >{{ $trans("Edit") }}</a
                          >
                        </li>
                        <li v-if="this.hasPermissionTo('D')">
                          <a
                            class="dropdown-item"
                            @click.prevent="handleDestroy(unit, 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="unit-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">
            {{ newUnit.id ? $trans("Edit Unit") : $trans("Create a new Unit") }}
          </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("Unit Name") }}</label>
            <div class="col-md-8">
              <input
                class="form-control"
                type="text"
                placeholder="Name"
                v-model="newUnit.name"
              />
            </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="newUnit.description"
              ></textarea>
            </div>
          </div>
          <div class="row">
            <div class="col-md-4"></div>
            <div class="col-md-8">
              <loading-button
                task="CREATING_UNIT"
                class="btn btn-primary"
                type="button w-100"
                @clicked="handleSave"
                :disabled="!newUnit.name"
              >
                <template #caption>{{ $trans("Save and Close") }}</template>
              </loading-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
