<template>
  <v-container>

    <AdminNestedList
      :depth="0"
      @edit="openEditor"
      @delete="deleteCategory"
      :categories="parentCategories"
    ></AdminNestedList>

    <modal height="auto" name="category-editor">
      <h2>Редактирование категории</h2>
      <v-text-field
        v-model="editingCategory.alias"
        label="Алиас"
      ></v-text-field>
      <v-text-field
        v-model="editingCategory.title"
        label="Название"
      ></v-text-field>

      <v-btn color="primary" @click="editCategory">Сохранить</v-btn>
      <v-btn color="error" @click="$modal.hide('category-editor')"
        >Отмена</v-btn
      >
    </modal>
  </v-container>
</template>

<script>
export default {
  layout: "admin",
  data() {
    return {
      categories: [],
      editingCategory: false,
    };
  },
  async mounted() {
    await this.loadCategories();
  },

  methods: {
    async loadCategories() {
      await this.$axios.$get("/admin/categories").then((res) => {
        this.categories = res.data;
      });
    },

    getChildCaregories(parent) {
      return this.childCategories.filter(
        (child) => child.parent_id == parent.id
      );
    },

    openEditor(category) {
      this.editingCategory = Object.assign({}, category);
      this.$modal.show("category-editor");
    },

    async editCategory(category) {
      const result = await this.$swal.fire({
        title: "Вы уверены, что хотите отредактировать категорию?",
        showCancelButton: true,
        confirmButtonText: "Принять",
        icon: "question",
        cancelButtonText: `Отменить`,
        confirmButtonColor: `#1976d2`,
        denyButtonColor: `#2196f3`,
      });

      if (result.isConfirmed) {
        let { id, title, alias, parent_id } = this.editingCategory;

        await this.$axios.post("admin/categories/update", {
          id, title, alias, parent_id,
        });

        await this.loadCategories();
        this.$swal.fire("Готово!", "", "success");
        this.$modal.hide("category-editor");
      }
    },

    async deleteCategory(category) {
      console.log(123)
      const result = await this.$swal.fire({
        title: `Вы уверены, что хотите удалить категорию?`,
        showCancelButton: true,
        confirmButtonText: "Удалить",
        icon: "error",
        cancelButtonText: `Не удалять`,
        confirmButtonColor: `#ab003c`,
        denyButtonColor: `#2196f3`,
      });

      if (result.isConfirmed) {
        let { id } = category;
        await this.$axios.post("admin/categories/remove", { id });

        await this.loadCategories();
        this.$swal.fire("Готово!", "", "success");
      }
    },
  },

  computed: {
    parentCategories() {
      return this.categories.filter((category) => !category.parent_id);
    },
  },
};
</script>

<style>
</style>