<template>
  <v-form
    ref="form"
    v-model="properties.valid"
    lazy-validation
  >
    <slot name="form.input" v-bind="{entry}"></slot>
<!--{{entry}}-->

    <v-container fluid class="container">
      <v-row>
        <v-col cols="12" sm="12">
          <v-btn v-if="!readOnly" class="mr-4 submitBtn ot_green ot_white--text" @click="submit">
            Enregistrer
          </v-btn>
          <v-btn v-if="!readOnly" class="mr-4 submitBtn ot_danger ot_white--text" @click="submit">
            Annuler
          </v-btn>
        </v-col>
      </v-row>
    </v-container>
  </v-form>
</template>

<script lang="ts">
  import {defineComponent, reactive, useContext, computed, toRefs} from '@nuxtjs/composition-api'
  import Vue from 'vue'
  import {useRepositoryHelper} from "~/use/store/useRepository";
  import {useQueryHelper} from "~/use/store/useQuery";
  import {Query, Repository} from "@vuex-orm/core";
  import {Model} from "~/models/Model";

  export type VForm = Vue & { validate: () => boolean }

  export default defineComponent({
    props: {
      repository: {
        type: Object as () => Repository<Model>,
        required: true
      },
      id:{
        type: Number,
        required: true
      },
      query:{
        type: Object as () => Query,
        required: true
      },
    },
    setup(props) {
      const {repository, id, query} = toRefs(props)
      const properties = reactive({
        valid: false,
        saveOk: false,
        saveKo: false
      })

      const {store} = useContext();
      const readOnly = computed(() => {
        return useRepositoryHelper.getReadOnly(repository.value)
      })

      const entry = computed(() => {
          return useQueryHelper.getFlattenEntry(query.value, id.value)
      })

      const submit = () => {
        useRepositoryHelper.setReadOnly(repository.value, true)
        console.log(useQueryHelper.getJsonEntry(query.value, id.value))
      }

      return {
        submit,
        properties,
        readOnly,
        entry
      }
    },
    // methods:{
    //   async submit(){
    //
    //     console.log()
    //
    //
    //     const form:VForm = this.$refs.form;
    //     if(form.validate()){
    //       const model = await this.repository.find(parseInt(this.$route.params.id));
    //       if(model){
    //         const playload = model.$toJson();
    //
    //         this.$http.$put(`https://local.new.api.opentalent.fr/api/${model.$entity}/${this.$route.params.id}`, playload)
    //           .then(()=>{
    //             this.saveOk=true
    //           }, () =>{
    //             this.saveKo=true
    //           })
    //
    //         setTimeout(()=>{
    //           this.saveOk=false
    //           this.saveKo=false
    //         },2000)
    //       }
    //     }
    //   }
    // }
  })
</script>

<style scoped>
  .submitBtn {
    right: 0;
    margin-top: 20px;
    margin-bottom: 20px;
  }
</style>
