<script>
import "@/assets/stock-categories.css";
import LoadingButton from "@/components/LoadingButton.vue";
import { permissionsHandler } from "@/helpers/permissions-handler";

export default {
  name: "Categories",
  components: { LoadingButton },
  mixins: [permissionsHandler],
  data: () => ({
    category: null,
    categories: [],
    subCategories: [],
    newCategory: {},
    selectedCategory: null,
  }),
  created() {
    this.getCategories();
  },
  mounted() {
    /* var myModal = new bootstrap.Modal(document.getElementById("category-modal"), {});
    myModal.show(); */
  },
  computed: {
    submitDisabled() {
      return !this.newCategory.name;
    },
  },
  methods: {
    getCategories(parent = null) {
      var url = "stock/categories";
      if (parent) {
        url += `/show/${parent}`;
      }
      this.$http.get(url).then((response) => {
        if (!parent) {
          this.categories = response.data.rows;
        } else {
          this.subCategories = response.data.rows;
        }
      });
    },
    handleSave() {
      this.$http
        .post(
          "stock/categories/store",
          this.$helper.generateFormData(this.newCategory)
        )
        .then((response) => {
          if (response.data.status) {
            this.categories.unshift(response.data.row);
            var categoryModal = bootstrap.Modal.getInstance(
              document.getElementById("category-modal")
            );
            categoryModal.hide();
            this.newCategory = {};
            this.$notify({
              type: "success",
              message: "Category saved successfully",
            });
          }
        });
    },

    handleDelete(subCategory, i) {
      this.$confirm({
        title: "Deleting",
        content: `Are you sure you want to delete ${subCategory.name} from list of subCategories?`,
        actionText: "Yes, Continue",
        closeText: "Discard",
        classes: "btn btn-danger",
        action: () => {
          this.$http
            .get(`stock/categories/destroy/${subCategory.id}`)
            .then((response) => {
              if (response.data.status) {
                this.rows.splice(i, 1);
                this.$notify({
                  type: "success",
                  message: response.data.message,
                });
              }
            });
        },
      });
    },
    handleEdit(subCategory) {
      this.newCategory = subCategory;
    },
  },
};
</script>
<template>
  <div class="row justify-content-center">
    <div class="col-md-10">
      <div class="card">
        <div
          class="card-header justify-content-between d-flex align-items-center"
        >
          <h3>{{ $trans("Products Category") }}</h3>
          <a
            v-if="this.hasPermissionTo('C')"
            href="javascript(void:1)"
            data-bs-toggle="modal"
            data-bs-target="#category-modal"
            class="btn btn-primary btn-md ms-auto"
            target="_blank"
            ><i class="uil uil-plus me-1"></i
          ></a>
        </div>
        <div class="card-body">
          <div class="tree-loading d-none">
            <div class="half-circle-spinner loading-spinner">
              <div class="circle circle-1"></div>
              <div class="circle circle-2"></div>
            </div>
          </div>
          <div class="accordion" id="accordionExample">
            <div
              class="accordion-item"
              v-for="(category, i) in categories"
              :key="category.id"
              @click="getCategories(category.id)"
            >
              <h2 class="accordion-header d-flex" id="headingOne">
                <button
                  class="accordion-button fw-medium collapsed"
                  type="button"
                  data-bs-toggle="collapse"
                  :data-bs-target="`#` + category.name.replace(/\s+/g, '')"
                  aria-expanded="false"
                  :aria-controls="category.name.replace(/\s+/g, '')"
                >
                  <button
                    type="button"
                    class="btn btn-outline-warning me-3"
                    v-if="!Number(category.children_total)"
                  >
                    <i class="uil uil-file-alt"></i>
                  </button>
                  <button
                    type="button"
                    class="btn btn-outline-purple me-3"
                    v-else
                  >
                    <i class="uil uil-folder"></i>
                  </button>
                  <span class="mx-1">{{ category.name.toUpperCase() }}</span
                  ><a
                    href="javascript:void(0)"
                    class="btn btn-outline-success btn-sm btn-outline"
                    >{{ category.children_total }}</a
                  >
                </button>
                <button
                  v-if="this.hasPermissionTo('U')"
                  class="btn btn-outline-purple btn-md btn-outline p-3 me-1 parentBtn"
                  data-bs-toggle="modal"
                  data-bs-target="#category-modal"
                  target="_blank"
                  @click="handleEdit(category)"
                >
                  <i class="uil uil-edit"></i>
                </button>
                <button
                  v-if="this.hasPermissionTo('D')"
                  class="btn btn-outline-danger btn-md btn-outline p-3 me-2 parentBtn"
                  @click="handleDelete(category, i)"
                >
                  <i class="uil uil-trash"></i>
                </button>
              </h2>
              <div
                :id="category.name.replace(/\s+/g, '')"
                class="accordion-collapse collapse"
                :aria-labelledby="category.name.replace(/\s+/g, '')"
                data-bs-parent="#accordionExample"
              >
                <div class="accordion-body">
                  <div>
                    <ul class="list-unstyled mb-0">
                      <li
                        v-for="(subCategory, i) in subCategories"
                        :key="subCategory.id"
                        class="justify-content-between d-flex align-items-center"
                      >
                        <a
                          href="javascript:void(0)"
                          class="py-2 d-block text-muted font-weight-bold text-capitalize"
                          ><i
                            class="uil uil-check font-size-20 text-primary me-1"
                          ></i>
                          {{ subCategory.id }} - {{ subCategory.name }}
                        </a>
                        <div class="d-flex flex-wrap gap-2">
                          <button
                            v-if="this.hasPermissionTo('U')"
                            type="button"
                            data-bs-toggle="modal"
                            data-bs-target="#category-modal"
                            class="btn btn-outline-purple btn-md ms-auto"
                            target="_blank"
                            @click="handleEdit(subCategory)"
                          >
                            <i class="uil uil-edit"></i>
                          </button>
                          <button
                            v-if="this.hasPermissionTo('D')"
                            type="button"
                            class="btn btn-outline-danger"
                            @click="handleDelete(subCategory, i)"
                          >
                            <i class="uil uil-trash"></i>
                          </button>
                        </div>
                      </li>
                    </ul>
                  </div>
                  <div
                    class="alert alert-danger alert-dismissible fade show"
                    role="alert"
                    v-if="Object.keys(subCategories).length == 0"
                  >
                    <i class="uil uil-exclamation-octagon me-2"></i>
                    {{ $trans("No Sub Categories Found!") }}
                    <button
                      type="button"
                      class="btn-close"
                      data-bs-dismiss="alert"
                      aria-label="Close"
                    ></button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="card-body">
    <div
      class="modal fade"
      tabindex="-1"
      id="category-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">{{ $trans("Create category") }}</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("Category Name")
              }}</label>
              <div class="col-md-8">
                <input
                  class="form-control"
                  type="text"
                  placeholder="Name"
                  v-model="newCategory.name"
                />
              </div>
            </div>
            <div class="mb-3 row">
              <label class="col-md-4 col-form-label">{{
                $trans("Parent Category")
              }}</label>
              <div class="col-md-8">
                <select
                  class="form-control form-select"
                  v-model="newCategory.parent_id"
                >
                  <option :value="undefined" hidden disabled>
                    {{ $trans("Select Category") }}
                  </option>
                  <option
                    :value="category.id"
                    :key="category.id"
                    v-for="category in categories"
                  >
                    {{ category.name }}
                  </option>
                </select>
              </div>
            </div>
            <div class="mb-3 row">
              <label class="col-md-4 col-form-label">{{
                $trans("Descriptions")
              }}</label>
              <div class="col-md-8">
                <textarea
                  class="form-control"
                  placeholder="Optional Comment"
                  v-model="newCategory.description"
                ></textarea>
              </div>
            </div>
            <div class="row">
              <div class="col-md-4"></div>
              <div class="col-md-8">
                <loading-button
                  task="CREATING_COMPANY"
                  class="btn btn-primary"
                  type="button w-100"
                  @clicked="handleSave"
                  :disabled="submitDisabled"
                >
                  <template #caption>{{ $trans("Save and Close") }}</template>
                </loading-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<style>
.parentBtn {
  height: 50px;
  margin-top: 10px;
}
</style>
