<template>
  <LayoutContainer>

    <UiForm :model="models.Organization" :id="id" :query="repositories.organizationRepository.query()">
      <template v-slot:form.input="{entry, updateRepository}">

        <v-expansion-panels :value="panel" focusable accordion >

          <!-- Description -->
          <UiExpansionPanel id="description" icon="fa-info">
            <v-container fluid class="container">
              <v-row>
                <v-col cols="12" sm="6">
                  <UiInputText field="name" :data="entry['name']"  v-on:update="updateRepository"/>
                </v-col>

                <v-col cols="12" sm="6">
                  <UiInputText field="acronym" :data="entry['acronym']"  v-on:update="updateRepository"/>
                </v-col>

                <v-col cols="12" sm="6">
                  <UiInputText field="siretNumber" :data="entry['siretNumber']"  v-on:update="checkSiretHook($event, 'siretNumber', updateRepository)"
                                  :error="siretError"
                                  :errorMessage="siretErrorMessage"
                                  :rules="rules.siretRule"/>
                </v-col>

                <v-col cols="12" sm="6">
                  <UiInputText field="apeNumber" :data="entry['apeNumber']"  v-on:update="updateRepository"/>
                </v-col>

                <v-col cols="12" sm="6" v-if="entry['legalStatus'] === 'ASSOCIATION_LAW_1901'">
                  <UiInputText field="waldecNumber" :data="entry['waldecNumber']"  v-on:update="updateRepository"/>
                </v-col>

                <v-col cols="12" sm="6" v-if="organizationProfile.isInsideNetwork()">
                  <UiInputText :label="organizationProfile.isCmf() ? 'identifierCmf' : 'identifierFfec'" field="identifier" :data="entry['identifier']"  v-on:update="updateRepository"/>
                </v-col>

                <v-col cols="12" sm="6" v-if="organizationProfile.isFfec()">
                  <UiInputText field="ffecApproval" :data="entry['ffecApproval']"  v-on:update="updateRepository"/>
                </v-col>

                <v-col cols="12" sm="6">
                  <UiInputText field="description" :data="entry['description']"  v-on:update="updateRepository"/>
                </v-col>

                <v-col cols="12" sm="6">
                  <UiInputText field="logo" :data="entry['logo']"  v-on:update="updateRepository"/>
                </v-col>

                <!-- @todo: ajouter les if et transformer en select-->
                <v-col cols="12" sm="6">
                  <UiInputText field="typeOfPractices" :data="entry['typeOfPractices']"  v-on:update="updateRepository"/>
                </v-col>

                <v-col cols="12" sm="6">
                  <UiInputText field="otherPractice" :data="entry['otherPractice']"  v-on:update="updateRepository"/>
                </v-col>
              </v-row>
            </v-container>
          </UiExpansionPanel>

          <!-- Adresses -->
          <UiExpansionPanel id="address_postal" icon="fa-globe-europe">
            <v-container fluid class="container">
              <v-row>
                <v-col cols="12" sm="12">
                  <UiSubList
                    :query="repositories.addressRepository.with('addressPostal', (query) => {
                      query.with('addressCountry')
                    })"
                    :rootModel="models.Organization"
                    :rootId="id"
                    :model="models.OrganizationAddressPostal"
                  >
                    <template v-slot:list.item="{items}">
                      <v-container fluid>
                        <v-row dense>
                            <v-col
                              v-for="item in items"
                              :key="item.id"
                              cols="4"
                            >
                              <UiCard
                                :link="`/organization/address/${item.id}`"
                                :model="models.OrganizationAddressPostal"
                                :id="item.id"
                              >
                                <template v-slot:card.title>{{$t(item.type)}}</template>
                                <template v-slot:card.text>
                                  {{item.addressPostal.streetAddress}} <br />
                                  <span v-if="item.addressPostal.streetAddressSecond">{{item.addressPostal.streetAddressSecond}} <br /></span>
                                  <span v-if="item.addressPostal.streetAddressThird">{{item.addressPostal.streetAddressThird}} <br /></span>
                                  {{item.addressPostal.postalCode}} {{item.addressPostal.addressCity}}<br />
                                  <span v-if="item.addressPostal.addressCountry">{{item.addressPostal.addressCountry.name}}</span>
                                </template>
                              </UiCard>
                            </v-col>
                        </v-row>
                      </v-container>
                    </template>
                  </UiSubList>
                </v-col>
              </v-row>
            </v-container>
          </UiExpansionPanel>

          <!--  Point de Contact-->
          <UiExpansionPanel id="contact_point" icon="fa-phone">
            <v-container class="container">
              <v-row>
                <v-col cols="12" sm="12">
                  <UiSubList
                    :query="repositories.contactPointRepository.query()"
                    :rootModel="models.Organization"
                    :rootId="id"
                    :model="models.ContactPoint"
                  >
                    <template v-slot:list.item="{items}">
                      <v-container fluid>
                        <v-row dense>
                          <v-col
                            v-for="item in items"
                            :key="item.id"
                            cols="4"
                          >
                            <UiCard
                              :link="`/organization/contact-points/${item.id}`"
                              :model="models.ContactPoint"
                              :id="item.id"
                            >
                              <template v-slot:card.title>{{$t(item.contactType)}}</template>
                              <template v-slot:card.text>
                                <span v-if="item.email"><strong>{{$t('email')}}</strong> : {{item.email}} <br /></span>
                                <span v-if="item.emailInvalid" class="ot_danger--text"><v-icon class="ot_danger--text">mdi-alert</v-icon> <strong>{{$t('emailInvalid')}}</strong> : {{item.emailInvalid}} <br /></span>
                                <span v-if="item.telphone"><strong>{{$t('telphone')}}</strong> : {{item.telphone}} <br /></span>
                                <span v-if="item.telphoneInvalid"  class="ot_danger--text"><v-icon class="ot_danger--text">mdi-alert</v-icon> <strong>{{$t('telphoneInvalid')}}</strong> : {{item.telphoneInvalid}} <br /></span>
                                <span v-if="item.mobilPhone"><strong>{{$t('mobilPhone')}}</strong> : {{item.mobilPhone}} <br /></span>
                                <span v-if="item.mobilPhoneInvalid" class="ot_danger--text"><v-icon class="ot_danger--text">mdi-alert</v-icon> <strong>{{$t('mobilPhoneInvalid')}}</strong> : {{item.mobilPhoneInvalid}} </span>
                              </template>
                            </UiCard>
                          </v-col>
                        </v-row>
                      </v-container>
                    </template>
                  </UiSubList>
                </v-col>
              </v-row>
            </v-container>
          </UiExpansionPanel>

          <!-- Informations légales -->
          <UiExpansionPanel id="legalInformation" icon="fa-gavel">
            <v-container fluid class="container">
              <v-row>
                <v-col cols="12" sm="6">
                  <UiInputDatePicker field="creationDate" :data="entry['creationDate']"  v-on:update="updateRepository"/>
                </v-col>
                <v-col cols="12" sm="6">
                  <UiInputText field="prefectureName" :data="entry['prefectureName']"  v-on:update="updateRepository"/>
                </v-col>

                <v-col cols="12" sm="6">
                  <UiInputText field="prefectureNumber" :data="entry['prefectureNumber']"  v-on:update="updateRepository"/>
                </v-col>

                <v-col cols="12" sm="6">
                  <UiInputText field="tvaNumber" :data="entry['tvaNumber']"  v-on:update="updateRepository"/>
                </v-col>

                <v-col cols="12" sm="6">
                  <UiInputEnum field="legalStatus" :data="entry['legalStatus']"  enumType="organization_legal" v-on:update="updateRepository"/>
                </v-col>

                <v-col cols="12" sm="6" v-if="!organizationProfile.isManagerProduct()">
                  <UiInputEnum field="principalType" :data="entry['principalType']"  enumType="organization_principal_type" v-on:update="updateRepository"/>
                </v-col>

                <v-col cols="12" sm="6" v-if="!organizationProfile.isFfec() && !organizationProfile.isManagerProduct() && !organizationProfile.isArtist()">
                  <UiInputEnum field="schoolCategory" :data="entry['schoolCategory']"  enumType="organization_school_cat" v-on:update="updateRepository"/>
                </v-col>

                <v-col cols="12" sm="6" v-if="organizationProfile.isFfec()">
                  <UiInputEnum field="typeEstablishment" :data="entry['typeEstablishment']"  enumType="organization_type_establishment" v-on:update="updateRepository"/>
                </v-col>

                <v-col cols="12" sm="6" v-if="entry.typeEstablishment === 'MULTIPLE'">
                  <UiInputEnum field="typeEstablishmentDetail" :data="entry['typeEstablishmentDetail']"  enumType="organization_type_establishment_detail" v-on:update="updateRepository"/>
                </v-col>
              </v-row>
            </v-container>
          </UiExpansionPanel>

          <!--  Agréments -->
          <UiExpansionPanel id="agrements" icon="fa-certificate">
            <v-container class="container">
              <v-row>
                <v-col cols="12" sm="6">
                  <UiInputText field="youngApproval" :data="entry['youngApproval']"  v-on:update="updateRepository"/>
                </v-col>

                <v-col cols="12" sm="6">
                  <UiInputText field="trainingApproval" :data="entry['trainingApproval']"  v-on:update="updateRepository"/>
                </v-col>

                <v-col cols="12" sm="6">
                  <UiInputText field="otherApproval" :data="entry['otherApproval']"  v-on:update="updateRepository"/>
                </v-col>
              </v-row>
            </v-container>
          </UiExpansionPanel>

          <!-- Salariés -->
          <UiExpansionPanel id="salary" icon="fa-users">
            <v-container class="container">
              <v-row>
                <v-col cols="12" sm="6">
                  <UiInputText field="collectiveAgreement" :data="entry['collectiveAgreement']"  v-on:update="updateRepository"/>
                </v-col>

                <v-col cols="12" sm="6">
                  <UiInputEnum field="opca" :data="entry['opca']"  enumType="organization_opca" v-on:update="updateRepository"/>
                </v-col>

                <v-col cols="12" sm="6">
                  <UiInputText field="icomNumber" :data="entry['icomNumber']"  v-on:update="updateRepository"/>
                </v-col>

                <v-col cols="12" sm="6">
                  <UiInputText field="urssafNumber" :data="entry['urssafNumber']"  v-on:update="updateRepository"/>
                </v-col>
              </v-row>
            </v-container>
          </UiExpansionPanel>

          <!-- Réseaux -->
          <UiExpansionPanel v-if="organizationProfile.isInsideNetwork()" id="network" icon="fa-share-alt">
            <v-container class="container">
              <v-row>
                <v-col cols="12" sm="6" v-if="organizationProfile.isFfec()">
                  <UiInputText field="budget" :data="entry['budget']"  v-on:update="updateRepository" type="number"/>
                </v-col>

                <v-col cols="12" sm="6" v-if="organizationProfile.isFfec()">
                  <UiInputCheckbox field="isPedagogicIsPrincipalActivity" :data="entry['isPedagogicIsPrincipalActivity']"  v-on:update="updateRepository"/>
                </v-col>

                <v-col cols="12" sm="6" v-if="organizationProfile.isFfec()">
                  <UiInputText field="pedagogicBudget" :data="entry['pedagogicBudget']"  v-on:update="updateRepository" type="number"/>
                </v-col>
              </v-row>
            </v-container>
          </UiExpansionPanel>

          <!-- Communication -->
          <UiExpansionPanel id="communication" icon="fa-rss">
            <v-container class="container">
              <v-row>
                <v-col cols="12" sm="6">
                  <UiInputText field="twitter" :data="entry['twitter']"  v-on:update="updateRepository"/>
                </v-col>

                <v-col cols="12" sm="6">
                  <UiInputText field="facebook" :data="entry['facebook']"  v-on:update="updateRepository"/>
                </v-col>

                <v-col cols="12" sm="6">
                  <UiInputText field="instagram" :data="entry['instagram']"  v-on:update="updateRepository"/>
                </v-col>

                <v-col cols="12" sm="6">
                  <UiInputCheckbox field="portailVisibility" :data="entry['portailVisibility']"  v-on:update="updateRepository"/>
                </v-col>

                <v-col cols="12" sm="6">
                  <UiInputText field="image" :data="entry['image']"  v-on:update="updateRepository"/>
                </v-col>
              </v-row>
            </v-container>
          </UiExpansionPanel>

          <!-- IBAN -->
          <UiExpansionPanel id="bank_account" icon="fa-euro-sign">
            <v-container class="container">
              <v-row>
                <v-col cols="12" sm="12">
                  <UiDataTable
                    :query="repositories.bankAccountRepository.query()"
                    :rootModel="models.Organization"
                    :rootId="id"
                    :model="models.BankAccount"
                    :headers="datatableHeaders.headersBankAccount"
                  >
                  </UiDataTable>
                </v-col>
              </v-row>
            </v-container>
          </UiExpansionPanel>

        </v-expansion-panels>
      </template>
    </UiForm>
  </LayoutContainer>
</template>

<script lang="ts">
  import {defineComponent, useContext} from '@nuxtjs/composition-api'
  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 {repositoryHelper} from "~/services/store/repository";
  import UseChecker from "~/use/form/useChecker";
  import {UseNavigationHelpers} from "~/use/form/useNavigationHelpers";

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

      const repositories = getRepositories()

      const {siretError, siretErrorMessage, checkSiret} = UseChecker.useHandleSiret(i18n, $dataProvider)
      const checkSiretHook = async (siret:string, field:string, updateRepository:any) => {
        await checkSiret(siret)
        if(!siretError.value)
          updateRepository(siret, field);
      }

      const {panel} = UseNavigationHelpers.expansionPanels()

      return {
        repositories,
        id,
        organizationProfile,
        models: {Organization, ContactPoint, BankAccount, OrganizationAddressPostal},
        datatableHeaders: getDataTablesHeaders(i18n),
        rules: getRules(i18n),
        siretError,
        siretErrorMessage,
        checkSiretHook,
        panel
      }
    },
  })

  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: repositoryHelper.getRepository(Organization),
      contactPointRepository: repositoryHelper.getRepository(ContactPoint),
      bankAccountRepository: repositoryHelper.getRepository(BankAccount),
      addressRepository: repositoryHelper.getRepository(OrganizationAddressPostal)
    }
  }
</script>

<style scoped>
  .v-icon.v-icon {
    font-size: 14px;
  }
</style>
