<template>
  <v-card class="pa-5" width="600px">
    <v-form dark v-model="valid" ref="form">
      <v-text-field
        v-model="name"
        label="Name"
        outlined
        filled
        dense
        dark
        counter="30"
        :rules="[required('Name'), minLength('Name', 2), maxLength('Name', 30)]"
        v-on:keyup.enter="submitFunc()"
      ></v-text-field>
      <v-textarea
        v-model="description"
        label="Description"
        outlined
        dense
        dark
        filled
        auto-grow
        counter="true"
        :rules="[required('Description')]"
        v-on:keyup.enter="submitFunc()"
      ></v-textarea>
      <v-treeview
        :active.sync="active"
        :items="items"
        :load-children="fetchChildren"
        :open.sync="open"
        activatable
        selection-type="independent"
        dark
        color="warning"
        transition
      >
        <template v-slot:prepend="{ item }">
          <v-icon v-if="!item.children"> mdi-map-marker </v-icon>
        </template>
      </v-treeview>
      <div class="text-center">
        <v-btn
          class="signin-btn"
          rounded
          color--text="white"
          dark
          :disabled="!valid"
          @click="submitFunc()"
        >
          Add Location
        </v-btn>
      </div>
    </v-form>
    <v-container class="pt-50">
      <v-alert
        v-model="success"
        prominent
        dense
        type="success"
        transition="slide-y-transition"
      >
        {{ successMessage }}
      </v-alert>
      <v-alert
        v-model="error"
        prominent
        dense
        type="error"
        transition="slide-y-transition"
      >
        {{ errorMessage }}
      </v-alert>
    </v-container>
  </v-card>
</template>

<script>
import validations from "@/utils/validations";
import { API } from "../utils/api_common";
import { mapState } from "vuex";
export default {
  name: "AddLocationForm",
  data: () => ({
    valid: false,
    name: "",
    description: "",
    parent: null,
    successMessage: null,
    errorMessage: null,
    success: false,
    error: false,
    active: [],
    open: [],
    ...validations,
    ...mapState(["topLocations"]),
  }),
  props: ["defaultParent", "closeFunc"],
  computed: {
    items() {
      let locations = [];
      if (this.topLocations() == null) {
        this.$store.dispatch("loadTopLocations");
      }
      for (let l of this.topLocations()) {
        locations.push(l);
      }
      return locations;
    },
  },
  mounted() {
    this.$refs.form.reset();
    this.$store.dispatch("loadTopLocations");
  },
  methods: {
    async fetchChildren(item) {
      await API
        .get(
          "api/v1/locations/" + item.id + "/getChildren",
          {
            headers: {
              Authorization: localStorage.getItem("token"),
            },
          }
        )
        .then((response) => {
          if (response.status == 200 && response.data) {
            for (let l of response.data) {
              l.children = [];
            }
            item.children = response.data;
          } else {
            item.children = null;
          }
        })
        .catch((error) => {
          console.log(error.response.data);
        });
    },
    submitFunc() {
      let data = {
        name: this.name,
        description: this.description,
        parent: null,
      };
      if (this.active.length == 1) {
        data.parent = {
          id: this.active[0],
        };
      }
      API
        .post("api/v1/locations/", data, {
          headers: {
            Authorization: localStorage.getItem("token"),
          },
        })
        .then((response) => {
          if (response.status == 201) {
            this.successMessage = "Location Added";
            this.success = true;
            this.$refs.form.reset();
            setTimeout(() => {
              this.$router.push({
                name: "Location",
                params: { id: response.data.id },
              });
              this.success = false;
              this.successMessage = "";
              this.closeFunc("addLocation");
              this.$store.dispatch("loadTopLocations");
            }, 2000);
          }
        })
        .catch((error) => {
          this.errorMessage = error.response.data.error;
          this.error = true;
          setTimeout(() => {
            this.errorMessage = null;
            this.error = false;
          }, 3000);
        });
    },
  },
};
</script>