<template>
  <ContainerComponent>
    <template>
      <v-card class="margin-bottom-20">
        <v-toolbar flat class="ot_light_grey" dark>
          <v-toolbar-title class="ot_dark_grey--text form_main_title">
            Description de l'organisation
            <v-btn @click="edit" v-if="readOnly" class="ot_green editBtn">
              Modifier
            </v-btn>
          </v-toolbar-title>
        </v-toolbar>

        <FormComponent :repository="repositories.organizationRepository" :id="id" :query="repositories.organizationRepository.query()">
          <template v-slot:form.input="{entry}">
            <v-tabs vertical>
              <v-tab><v-icon left>fa-info</v-icon>{{$t('description')}}</v-tab>
              <v-tab><v-icon left>fa-gavel</v-icon>{{$t('legalInformation')}}</v-tab>
              <v-tab><v-icon left>fa-certificate</v-icon>{{$t('agrements')}}</v-tab>
              <v-tab><v-icon left>fa-users</v-icon>{{$t('salary')}}</v-tab>
              <v-tab v-if="organizationProfile.isInsideNetwork()"><v-icon left>fa-share-alt</v-icon>{{$t('network')}}</v-tab>
              <v-tab><v-icon left>fa-rss</v-icon>{{$t('communication')}}</v-tab>

              <v-tab-item>
                <v-container fluid class="container">
                  <v-row>
                    <v-col cols="12" sm="6">
                      <InputComponent field="name" :repository="repositories.organizationRepository" :entry="entry" :rules="rules.nameRules" />
                    </v-col>

                    <v-col cols="12" sm="6">
                      <InputComponent field="acronym" :repository="repositories.organizationRepository" :entry="entry" />
                    </v-col>
                    <v-col cols="12" sm="6">
                      <InputComponent
                        field="siretNumber"
                        :repository="repositories.organizationRepository"
                        :entry="entry"
                        v-on:update="checkSiret"
                        :error="siretError"
                        :errorMessage="siretErrorMessage"
                        :rules="rules.siretRule"
                      />
                    </v-col>
                    <v-col cols="12" sm="6">
                      <InputComponent field="apeNumber" :repository="repositories.organizationRepository" :entry="entry" />
                    </v-col>
                    <v-col cols="12" sm="6" v-if="entry['legalStatus'] === 'ASSOCIATION_LAW_1901'" >
                      <InputComponent field="waldecNumber" :repository="repositories.organizationRepository" :entry="entry"  />
                    </v-col>
                    <v-col cols="12" sm="6" v-if="organizationProfile.isInsideNetwork()" >
                      <InputComponent field="identifier" :repository="repositories.organizationRepository" :entry="entry"
                                      :label="organizationProfile.isCmf() ? 'identifierCmf' : 'identifierFfec'" />
                    </v-col>
                    <v-col cols="12" sm="6" v-if="organizationProfile.isFfec()" >
                      <InputComponent field="ffecApproval" :repository="repositories.organizationRepository" :entry="entry" />
                    </v-col>
                    <v-col cols="12" sm="6">
                      <InputComponent field="description" :repository="repositories.organizationRepository" :entry="entry"  />
                    </v-col>
                    <v-col cols="12" sm="6">
                      <InputComponent field="logo" :repository="repositories.organizationRepository" :entry="entry"  />
                    </v-col>

                    <!-- @todo: ajouter les if et transformer en select-->
                    <v-col cols="12" sm="6">
                      <InputComponent field="typeOfPractices" :repository="repositories.organizationRepository" :entry="entry"  />
                    </v-col>
                    <v-col cols="12" sm="6">
                      <InputComponent field="otherPractice" :repository="repositories.organizationRepository" :entry="entry"  />
                    </v-col>
                  </v-row>
                </v-container>
              </v-tab-item>

              <v-tab-item>
                <v-container fluid class="container">
                  <v-row>
                    <v-col cols="12" sm="6">
                      <DatePickerComponent field="creationDate" :repository="repositories.organizationRepository" :entry="entry"  />
                    </v-col>
                    <v-col cols="12" sm="6">
                      <InputComponent field="prefectureName" :repository="repositories.organizationRepository" :entry="entry"  />
                    </v-col>
                    <v-col cols="12" sm="6">
                      <InputComponent field="prefectureNumber" :repository="repositories.organizationRepository" :entry="entry"  />
                    </v-col>
                    <v-col cols="12" sm="6">
                      <InputComponent field="tvaNumber" :repository="repositories.organizationRepository" :entry="entry"  />
                    </v-col>
                    <v-col cols="12" sm="6">
                      <SelectComponent field="legalStatus" :repository="repositories.organizationRepository" :entry="entry"  enumType="organization_legal" />
                    </v-col>
                    <v-col cols="12" sm="6" v-if="!organizationProfile.isManagerProduct()" >
                      <SelectComponent field="principalType" :repository="repositories.organizationRepository"
                                       :entry="entry"  enumType="organization_principal_type"
                      />
                    </v-col>
                    <v-col cols="12" sm="6" v-if="!organizationProfile.isFfec() && !organizationProfile.isManagerProduct() && !organizationProfile.isArtist()">
                      <SelectComponent field="schoolCategory" :repository="repositories.organizationRepository" :entry="entry"  enumType="organization_school_cat" />
                    </v-col>
                    <v-col cols="12" sm="6" v-if="organizationProfile.isFfec()" >
                      <SelectComponent field="typeEstablishment" :repository="repositories.organizationRepository" :entry="entry" enumType="organization_type_establishment"/>
                    </v-col>
                    <v-col cols="12" sm="6" v-if="entry.typeEstablishment === 'MULTIPLE'" >
                      <SelectComponent field="typeEstablishmentDetail" :repository="repositories.organizationRepository" :entry="entry"  enumType="organization_type_establishment_detail"/>
                    </v-col>
                  </v-row>
                </v-container>
              </v-tab-item>

              <v-tab-item>
                <v-container fluid class="container">
                  <v-row>
                    <v-col cols="12" sm="6">
                      <InputComponent field="youngApproval" :repository="repositories.organizationRepository" :entry="entry"  />
                    </v-col>
                    <v-col cols="12" sm="6">
                      <InputComponent field="trainingApproval" :repository="repositories.organizationRepository" :entry="entry"  />
                    </v-col>
                    <v-col cols="12" sm="6">
                      <InputComponent field="otherApproval" :repository="repositories.organizationRepository" :entry="entry" />
                    </v-col>
                  </v-row>
                </v-container>
              </v-tab-item>

              <v-tab-item>
                <v-container fluid class="container">
                  <v-row>
                    <v-col cols="12" sm="6">
                      <InputComponent field="collectiveAgreement" :repository="repositories.organizationRepository" :entry="entry"  />
                    </v-col>
                    <v-col cols="12" sm="6">
                      <SelectComponent field="opca" :repository="repositories.organizationRepository" :entry="entry"  enumType="organization_opca" />
                    </v-col>
                    <v-col cols="12" sm="6">
                      <InputComponent field="icomNumber" :repository="repositories.organizationRepository" :entry="entry"  />
                    </v-col>
                    <v-col cols="12" sm="6">
                      <InputComponent field="urssafNumber" :repository="repositories.organizationRepository" :entry="entry" />
                    </v-col>
                  </v-row>
                </v-container>
              </v-tab-item>

              <v-tab-item  v-if="organizationProfile.isInsideNetwork()">
                <v-container fluid class="container">
                  <v-row>
                    <v-col cols="12" sm="6"  v-if="organizationProfile.isFfec()" >
                      <InputComponent field="budget" :repository="repositories.organizationRepository" :entry="entry"  type="number" />
                    </v-col>
                    <v-col cols="12" sm="6" v-if="organizationProfile.isFfec()" >
                      <CheckboxComponent field="isPedagogicIsPrincipalActivity" :repository="repositories.organizationRepository" :entry="entry"  />
                    </v-col>
                    <v-col cols="12" sm="6" v-if="organizationProfile.isFfec()" >
                      <InputComponent field="pedagogicBudget" :repository="repositories.organizationRepository" :entry="entry"  type="number"/>
                    </v-col>
                  </v-row>
                </v-container>
              </v-tab-item>

              <v-tab-item>
                <v-container fluid class="container">
                  <v-row>
                    <v-col cols="12" sm="6">
                      <InputComponent field="twitter" :repository="repositories.organizationRepository" :entry="entry"  />
                    </v-col>
                    <v-col cols="12" sm="6">
                      <InputComponent field="facebook" :repository="repositories.organizationRepository" :entry="entry" />
                    </v-col>
                    <v-col cols="12" sm="6">
                      <InputComponent field="instagram" :repository="repositories.organizationRepository" :entry="entry" />
                    </v-col>
                    <v-col cols="12" sm="6">
                      <CheckboxComponent field="portailVisibility" :repository="repositories.organizationRepository" :entry="entry" />
                    </v-col>
                    <v-col cols="12" sm="6">
                      <InputComponent field="image" :repository="repositories.organizationRepository" :entry="entry" />
                    </v-col>
                  </v-row>
                </v-container>
              </v-tab-item>

            </v-tabs>
          </template>
        </FormComponent>
      </v-card>
    </template>


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

      <!-- Adresses -->
      <ExpansionPanelComponent :title="$t('address_postal')"  icon="fa-globe-europe">
        <v-container fluid class="container">
          <v-row>
            <v-col cols="12" sm="12">
              <DataTableComponent
                :query="repositories.addressRepository.with('addressPostal')"
                :rootModel="models.Organization"
                :rootId="id"
                :model="models.OrganizationAddressPostal"
                :headers="datatableHeaders.headersAddressPostal"
              >
                <template v-slot:item.type="{item}">
                  {{$t(item.type)}}
                </template>
                <template v-slot:item.address="{item}">
                  {{item['addressPostal.streetAddress']}}
                  {{item['addressPostal.postalCode']}}
                  {{item['addressPostal.addressCity']}}
                </template>

                <template v-slot:sheet.content="{itemId}">
                  <v-container class="container sheetBottomContainer">
                    <h2 class="sheet_bottom_title">Adresse postale</h2>
                    <FormComponent :repository="repositories.addressRepository" :id="itemId" :query="queries.addressQuery()">
                      <template v-slot:form.input="{entry: addressEntry }">
                        <v-row>
                          <v-col cols="12" sm="6">
                            <SelectComponent field="type" label="address_postal_type" :repository="repositories.addressRepository" :entry="addressEntry" enumType="address_postal_organization" />
                          </v-col>
                          <v-col cols="12" sm="6">
                            <InputComponent field="addressPostal.addressOwner" label="addressOwner" :repository="repositories.addressRepository" :entry="addressEntry" />
                          </v-col>
                          <v-col cols="12" sm="6">
                            <InputComponent field="addressPostal.streetAddress" label="streetAddress" :repository="repositories.addressRepository" :entry="addressEntry" />
                          </v-col>
                          <v-col cols="12" sm="6">
                            <InputComponent field="addressPostal.streetAddressSecond" label="streetAddressSecond" :repository="repositories.addressRepository" :entry="addressEntry" />
                          </v-col>
                          <v-col cols="12" sm="6">
                            <InputComponent field="addressPostal.streetAddressThird" label="streetAddressThird" :repository="repositories.addressRepository" :entry="addressEntry" />
                          </v-col>
                          <v-col cols="12" sm="6">
                            <InputComponent field="addressPostal.postalCode" label="postalCode" :repository="repositories.addressRepository" :entry="addressEntry" />
                          </v-col>
                          <v-col cols="12" sm="6">
                            <InputComponent field="addressPostal.addressCity" label="addressCity" :repository="repositories.addressRepository" :entry="addressEntry" />
                          </v-col>
                          <v-col cols="12" sm="6">
                            <InputComponent field="addressPostal.country" label="country" :repository="repositories.addressRepository" :entry="addressEntry" />
                          </v-col>
                        </v-row>
                      </template>
                    </FormComponent>
                  </v-container>
                </template>
              </DataTableComponent>
            </v-col>
          </v-row>
        </v-container>
      </ExpansionPanelComponent>

      <!--  Point de Contact-->
      <ExpansionPanelComponent :title="$t('contact_point')"  icon="fa-phone">
        <v-container class="container">
          <v-row>
            <v-col cols="12" sm="12">
              <DataTableComponent
                :query="repositories.contactPointRepository.query()"
                :rootModel="models.Organization"
                :rootId="id"
                :model="models.ContactPoint"
                :headers="datatableHeaders.headersContactPoint"
              >
                <template v-slot:sheet.content="{itemId }">
                  <v-container class="container sheetBottomContainer">
                    <h2 class="sheet_bottom_title">Point de contact</h2>
                    <FormComponent :repository="repositories.contactPointRepository" :query="queries.contactPointQuery()" :id="itemId">
                      <template v-slot:form.input="{entry: contactPointEntry }">
                        <v-row>
                          <v-col cols="12" sm="6">
                            <InputComponent field="email" :repository="repositories.contactPointRepository" :entry="contactPointEntry" />
                          </v-col>
                          <v-col cols="12" sm="6">
                            <InputComponent field="telphone" :repository="repositories.contactPointRepository" :entry="contactPointEntry" />
                          </v-col>
                          <v-col cols="12" sm="6">
                            <InputComponent field="mobilPhone" :repository="repositories.contactPointRepository" :entry="contactPointEntry" />
                          </v-col>
                          <v-col cols="12" sm="6">
                            <InputComponent field="faxNumber" :repository="repositories.contactPointRepository" :entry="contactPointEntry" />
                          </v-col>
                        </v-row>
                      </template>
                    </FormComponent>
                  </v-container>
                </template>
              </DataTableComponent>
            </v-col>
          </v-row>
        </v-container>
      </ExpansionPanelComponent>

      <!-- IBAN -->
      <ExpansionPanelComponent :title="$t('bank_account')"  icon="fa-euro-sign">
        <v-container class="container">
          <v-row>
            <v-col cols="12" sm="12">
              <DataTableComponent
                :query="repositories.bankAccountRepository.query()"
                :rootModel="models.Organization"
                :rootId="id"
                :model="models.BankAccount"
                :headers="datatableHeaders.headersBankAccount"
              >
                <template v-slot:sheet.content="{itemId}">
                  <v-container class="container sheetBottomContainer">
                    <h2 class="sheet_bottom_title">IBAN</h2>
                    <FormComponent :repository="repositories.bankAccountRepository" :id="itemId" :query="queries.bankAccountQuery()">
                      <template v-slot:form.input="{entry: bankAccountEntry }">
                        <v-row>
                          <v-col cols="12" sm="6">
                            <InputComponent field="bankName" :repository="repositories.bankAccountRepository" :entry="bankAccountEntry" />
                          </v-col>
                          <v-col cols="12" sm="6">
                            <InputComponent field="bic" :repository="repositories.bankAccountRepository" :entry="bankAccountEntry" />
                          </v-col>
                          <v-col cols="12" sm="6">
                            <InputComponent field="iban" :repository="repositories.bankAccountRepository" :entry="bankAccountEntry" />
                          </v-col>
                          <v-col cols="12" sm="6">
                            <InputComponent field="debitAddress" :repository="repositories.bankAccountRepository" :entry="bankAccountEntry" />
                          </v-col>
                          <v-col cols="12" sm="6">
                            <InputComponent field="holder" :repository="repositories.bankAccountRepository" :entry="bankAccountEntry" />
                          </v-col>
                          <v-col cols="12" sm="6">
                            <CheckboxComponent field="principal" :repository="repositories.bankAccountRepository" :entry="bankAccountEntry" />
                          </v-col>
                        </v-row>
                      </template>
                    </FormComponent>
                  </v-container>
                </template>
              </DataTableComponent>
            </v-col>
          </v-row>
        </v-container>
      </ExpansionPanelComponent>

    </v-expansion-panels>

  </ContainerComponent>
</template>

<script lang="ts">
  import {defineComponent, useContext, onUnmounted, computed} from '@nuxtjs/composition-api'
  import {$dataProvider} from "~/services/dataProvider/dataProvider";
  import {$organizationProfile} from "~/services/profile/organizationProfile";
  import {Organization} from '@/models/Organization/Organization'
  import {OrganizationAddressPostal} from "~/models/Organization/OrganizationAddressPostal";
  import {ContactPoint} from "~/models/Core/ContactPoint";
  import {BankAccount} from "~/models/Core/BankAccount";
  import {useRepositoryHelper} from "~/use/store/useRepository";
  import {Utils} from "~/use/form/utils";

  export default defineComponent({
    name: 'organization_edit',
    setup() {
      const {store, app:{i18n}} = useContext()
      const organizationProfile = $organizationProfile(store)
      const id = store.state.profile.organization.id;

      const repositories = getRepositories()


      const {siretError, siretErrorMessage, checkSiret} = Utils.useHandleSiret()
      //onUnmounted( useRepositoryHelper.cleanRepository(repository) )

      const readOnly = computed(() => {
        return useRepositoryHelper.getReadOnly(repositories.organizationRepository)
      })

      return {
        repositories,
        queries: getQueries(),
        id,
        organizationProfile,
        models: {Organization, ContactPoint, BankAccount, OrganizationAddressPostal},
        edit: useRepositoryHelper.editRepository(repositories.organizationRepository),
        datatableHeaders: getDataTablesHeaders(i18n),
        rules: getRules(i18n),
        siretError,
        siretErrorMessage,
        checkSiret,
        panel:null,
        readOnly
      }
    },

    async asyncData({store, $rest}){
      await $dataProvider(store, $rest).getItem(Organization, store.state.profile.organization.id)
    }
  })

  function getRules(i18n: any){
    return {
      nameRules : [
        (nameValue:string) => !!nameValue || i18n.t('required'),
        (nameValue:string) => (nameValue || '').length <= 128 || i18n.t('name_length_rule')
      ],
      siretRule : [
        (siretValue:string) => /^([0-9]{9}|[0-9]{14})$/.test(siretValue) || i18n.t('siret_error')
      ]
    }
  }

  function getDataTablesHeaders(i18n: any) {
    return {
      headersContactPoint: [
        {text: i18n.t('email'), value: 'email'},
        {text: i18n.t('telphone'), value: 'telphone'},
        {text: i18n.t('mobilPhone'), value: 'mobilPhone'},
        {text: i18n.t('actions'), value: 'actions', sortable: false},
      ],
      headersBankAccount: [
        {text: i18n.t('bankName'), value: 'bankName'},
        {text: i18n.t('iban'), value: 'iban'},
        {text: i18n.t('bic'), value: 'bic'},
        {text: i18n.t('actions'), value: 'actions', sortable: false},
      ],
      headersAddressPostal: [
        {text: i18n.t('address_postal_type'), value: 'type'},
        {text: i18n.t('address'), value: 'address'},
        {text: i18n.t('actions'), value: 'actions', sortable: false},
      ]
    }
  }

  function getRepositories() {
    return {
      organizationRepository: useRepositoryHelper.initRepository(Organization),
      contactPointRepository: useRepositoryHelper.initRepository(ContactPoint, false),
      bankAccountRepository: useRepositoryHelper.initRepository(BankAccount, false),
      addressRepository: useRepositoryHelper.initRepository(OrganizationAddressPostal, false)
    }
  }

  function getQueries() {
    return {
      organizationQuery: () => getRepositories().organizationRepository.query(),
      contactPointQuery: () => getRepositories().contactPointRepository.query(),
      bankAccountQuery: () => getRepositories().bankAccountRepository.query(),
      addressQuery: () => getRepositories().addressRepository.with('addressPostal')
    }
  }
</script>

<style scoped>
  .v-tab{
    justify-content: left;
    font-size: 12px;
  }
  .v-icon.v-icon{
    font-size: 14px;
  }
  .sheet_bottom_title{
    text-align: left;
    border-bottom: 1px solid #1ead8d;
    margin-bottom: 35px;
  }
  .sheetBottomContainer{
    padding: 20px;
    padding-top: 30px;
  }
</style>
