<template>
  <v-row justify="center" align="center">
    <v-col cols="12" sm="8" md="8">

        <FormComponent :repository="accessesRepository">

          <v-expansion-panels v-model="panel" focusable>

            <ExpansionPanelComponent title="Informations générales">
              <InputComponent :repository="accessesRepository" field="person.name" :rules="nameRule" />
              <InputComponent :repository="accessesRepository" field="person.givenName" />
            </ExpansionPanelComponent>

            <ExpansionPanelComponent title="Activités">
              <DataTableComponent :repository="personActivitiesRepository" :uri="personActivitiesUri" :headers="personActivitiesHearders"></DataTableComponent>
            </ExpansionPanelComponent>

          </v-expansion-panels>

        </FormComponent>

    </v-col>
  </v-row>
</template>


<script>
  import {defineComponent} from '@vue/composition-api'
  import {Access} from '@/models/Access'
  import {Person} from '@/models/Person'
  import {PersonActivity} from '@/models/PersonActivity'
  import accessesData from '@/data/accessesData'

  export default defineComponent({
    setup(props, {root}) {
      const panel = 0
      const accessesRepository = root.$store.$repo(Access).with('person')
      const personActivitiesRepository = root.$store.$repo(PersonActivity)

      const personActivitiesUri = `${accessesRepository.model.$entity}/${root.$route.params.id}/${personActivitiesRepository.model.$entity}`
      const personActivitiesHearders = [
        {
          text: 'Activité',
          align: 'start',
          sortable: false,
          value: 'complementSpeciality',
        },
        { text: 'Date de début',
          value: 'startDate'
        }
      ]

      const nameRule = [
        nameValue => (nameValue || '').length <= 128 || `A maximum of 128 characters is allowed`
      ]

      return {
        accessesRepository,
        personActivitiesRepository,
        personActivitiesUri,
        personActivitiesHearders,
        panel,
        nameRule
      }
    },

    async asyncData({store, $http, params}){
      const repository = store.$repo(Access);
      // const entity = repository.model.$entity;
      // const accesses = await $http.$get(`https://local.new.api.opentalent.fr/api/${entity}/${params.id}`)
      const accesses = await accessesData()
      repository.insert(accesses);
    },

    async beforeRouteLeave (to, from, next) {
      const flushAccess =  await this.$store.$repo(Access).flush();
      const flushPerson =  await this.$store.$repo(Person).flush();
      const flushPersonActivity =  await this.$store.$repo(PersonActivity).flush();
      next(true);
    }
  })
</script>
