<template>
  <v-container>
    <v-tabs v-model="currentTab" centered grow>
      <v-tab v-for="tab in jsonForm" :key="tab.label" :href="`#tab-${tab.label}`">
        {{ tab.label }}
      </v-tab>
    </v-tabs>

    <v-tabs-items v-model="currentTab" class="my-4">
      <v-tab-item v-for="tab in jsonForm" :key="tab.label" :value="`tab-${tab.label}`">
        <form-gen
          v-if="doc"
          :value="doc"
          :more="tab.field"
          :form="tab.form"
          :coll="{type: $route.params.rsc, id: doc._id}"
          :disabled="disabled"
          @update="hasUpdate()"
        />
      </v-tab-item>
    </v-tabs-items>

    <v-fab-transition>
      <v-btn
        v-show="canSave"
        class="mx-2"
        fab
        dark
        large
        color="success ma-3"
        absolute
        bottom
        right
        @click="save()"
      >
        <v-icon dark>
          mdi-content-save
        </v-icon>
      </v-btn>
    </v-fab-transition>
  </v-container>
</template>

<script>
import FormGen from '@/components/FormGen/FormGen'

export default {
  layout: 'admin',
  components: { FormGen },
  data: () => ({
    jsonForm: [],
    currentTab: '',
    doc: null,
    canSave: false,
    disabled: true
  }),
  mounted () {
    this.$store.commit('admin/ui/setBreadcrumbs', [
      { text: 'Resources', href: '/admin/resources' },
      { text: this.$route.params.rsc, href: `/admin/resources/${this.$route.params.rsc}` },
      { text: 'Edit', href: `/admin/resources/${this.$route.params.rsc}/${this.$route.params.id}` }
    ])
    this.getForm()
    this.getDoc()
  },
  methods: {
    hasUpdate () {
      this.canSave = true
    },
    getForm () {
      this.$axios.get(`/cloud/api/${this.$route.params.rsc}/private/json-form`)
        .then((res) => {
          this.jsonForm = res.data
          this.jsonForm.forEach((tab) => {
            if (!this.currentTab) { this.currentTab = `#tab-${tab.label}` }
          })
          this.disabled = false
        })
    },
    getDoc () {
      this.$axios.get(`/cloud/api/${this.$route.params.rsc}/${this.$route.params.id}`)
        .then((res) => {
          this.doc = res.data.data
          this.$store.commit('admin/ui/setTitle', this.doc.name)
        })
    },
    save () {
      this.$axios.put(`/cloud/api/${this.$route.params.rsc}/${this.$route.params.id}`, this.doc)
        .then((res) => {
          this.canSave = false
          this.$store.commit('admin/ui/snack', { msg: 'Enregistré avec succès', color: 'success' })
        })
        .catch((res) => {
          this.$store.commit('admin/ui/snack', { msg: 'Impossible de sauvegarder', color: 'error' })
        })
    }
  }
}
</script>
