<!--
Contenu de la page pages/organization.vue
Contient toutes les informations sur l'organization courante
-->
<template>
  <LayoutContainer>
    <UiForm :id="id" :model="models().Organization" :query="repositories().organizationRepository.query()">
      <template #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']" @update="updateRepository" :rules="rules().nameRules" />
                </v-col>

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

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

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

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

                <v-col cols="12" sm="6">
                  <div>
                    <span>{{ $t('logo') }}</span>
                    <UiHelp right>
                      <p v-html="$t('logo_upload')" />
                    </UiHelp>
                  </div>
                  <UiImage
                    :id="getIdFromUri(entry['logo'])"
                    :upload="true"
                    :width="200"
                    field="logo"
                    :ownerId="id"
                    @update="updateRepository"
                  ></UiImage>
                </v-col>

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

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

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

                <v-col v-if="entry.typeEstablishment === 'MULTIPLE'" cols="12" sm="6">
                  <UiInputEnum field="typeEstablishmentDetail" :data="entry['typeEstablishmentDetail']" enum-type="organization_type_establishment_detail" @update="updateRepository" />
                </v-col>

                <v-col cols="12" sm="6" v-if="organizationProfile.isCmf()">
                  <div class="d-flex flex-row">
                    <UiInputAutocomplete
                      field="typeOfPractices"
                      :items="typeOfPractices"
                      :isLoading="typeOfPracticesFetchingState.pending"
                      :item-text="['name']"
                      :data="getIdsFromUris(entry['typeOfPractices'])"
                      :translate="true"
                      :multiple="true"
                      group="category"
                      :rules="rules().typeOfPractice"
                      @update="updateRepository($event.map((id) => `/api/type_of_practices/${id}`), 'typeOfPractices')"
                      class="flex"
                    />
                    <UiHelp>
                      {{ $t('type_of_practices_autocomplete') }}
                    </UiHelp>
                  </div>
                </v-col>
                <v-col cols="12" sm="6" v-if="getIdsFromUris(entry['typeOfPractices']).indexOf(37) >= 0">
                  <UiInputTextArea field="otherPractice" :data="entry['otherPractice']" @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">
                  <UiSubResource
                    :query="repositories().addressRepository.with('addressPostal')"
                    :root-model="models().Organization"
                    :root-id="id"
                    :model="models().OrganizationAddressPostal"
                    loaderType="image"
                    newLink="/organization/address/new"
                  >
                    <template #list.item="{items}">
                      <v-container fluid>
                        <v-row dense>
                          <v-col
                            v-for="item in items"
                            :key="item.id"
                            cols="4"
                          >
                            <UiCard
                              :id="item.id"
                              :link="`/organization/address/${item.id}`"
                              :model="models().OrganizationAddressPostal"
                            >
                              <template #card.title>
                                {{ $t(item.type) }}
                              </template>
                              <template #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">
                                  <UiItemFromUri
                                    :model="models().Country"
                                    :query="repositories().countryRepository.query()"
                                    :uri="item.addressPostal.addressCountry"
                                  >
                                    <template #item.text="{item}">
                                      {{item.name}}
                                    </template>
                                  </UiItemFromUri>
                                </span>
                              </template>
                            </UiCard>
                          </v-col>
                        </v-row>
                      </v-container>
                    </template>
                  </UiSubResource>
                </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">
                  <UiSubResource
                    :query="repositories().contactPointRepository.query()"
                    :root-model="models().Organization"
                    :root-id="id"
                    :model="models().ContactPoint"
                    loaderType="image"
                    newLink="/organization/contact_points/new"
                  >
                    <template #list.item="{items}">
                      <v-container fluid>
                        <v-row dense>
                          <v-col
                            v-for="item in items"
                            :key="item.id"
                            cols="4"
                          >
                            <UiCard
                              :id="item.id"
                              :link="`/organization/contact_points/${item.id}`"
                              :model="models().ContactPoint"
                            >
                              <template #card.title>
                                {{ $t(item.contactType) }}
                              </template>
                              <template #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> : {{ formatPhoneNumber(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> : {{ formatPhoneNumber(item.telphoneInvalid) }} <br></span>

                                <span v-if="item.mobilPhone"><strong>{{ $t('mobilPhone') }}</strong> : {{ formatPhoneNumber(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> : {{ formatPhoneNumber(item.mobilPhoneInvalid) }} </span>
                              </template>
                            </UiCard>
                          </v-col>
                        </v-row>
                      </v-container>
                    </template>
                  </UiSubResource>
                </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">
                  <UiInputText
                    field="siretNumber"
                    :data="entry['siretNumber']"
                    :error="siretError"
                    :error-message="siretErrorMessage"
                    :rules="rules().siretRule"
                    @update="checkSiretHook($event, 'siretNumber', updateRepository)"
                  />
                </v-col>

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

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

                <v-col cols="12" sm="6">
                  <UiInputDatePicker field="creationDate" :data="entry['creationDate']" @update="updateRepository" />
                </v-col>

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

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

                <v-col cols="12" sm="6">
                  <UiInputDatePicker field="declarationDate" :data="entry['declarationDate']" @update="updateRepository" />
                </v-col>

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

                <v-col cols="12" sm="6">
                  <UiInputEnum field="legalStatus" :data="entry['legalStatus']" enum-type="organization_legal" @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']" @update="updateRepository" />
                </v-col>

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

                <v-col cols="12" sm="6">
                  <UiInputText field="otherApproval" :data="entry['otherApproval']" @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']" @update="updateRepository" />
                </v-col>

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

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

                <v-col cols="12" sm="6">
                  <UiInputText field="urssafNumber" :data="entry['urssafNumber']" @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="12">
                  <UiSubResource
                    :query="repositories().netWorkOrganizationRepository.with('network')"
                    :root-model="models().Organization"
                    :root-id="id"
                    :model="models().NetworkOrganization"
                    loaderType="text"
                  >
                    <template #list.item="{items}">
                      <div v-for="item in items" :key="item.id">
                        <span>{{ item.network.name }}</span> - <span>{{$t('first_subscription')}} : <UiTemplateDate :data="item.startDate" /></span>
                      </div>
                    </template>
                  </UiSubResource>
                </v-col>
                <v-col v-if="organizationProfile.isFfec()" cols="12" sm="6">
                  <UiInputText field="budget" :data="entry['budget']" type="number" @update="updateRepository" />
                </v-col>

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

                <v-col v-if="organizationProfile.isFfec()" cols="12" sm="6">
                  <UiInputText field="pedagogicBudget" :data="entry['pedagogicBudget']" type="number" @update="updateRepository" />
                </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']" @update="updateRepository" />
                </v-col>

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

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

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

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

                <v-col cols="12" sm="6">
                  <div class="d-flex flex-column">
                    <UiHelp class="d-flex flex-row">
                      <span>{{ $t('image') }}</span>
                      <p v-html="$t('communication_image_upload')" />
                    </UiHelp>
                    <UiImage
                      :id="getIdFromUri(entry['image'])"
                      :upload="true"
                      :width="200"
                      field="image"
                      :ownerId="id"
                      @update="updateRepository"
                    ></UiImage>v
                  </div>
                </v-col>

                <v-col cols="12" sm="12">
                  <UiSubResource
                    :query="repositories().organizationArticleRepository.query()"
                    :root-model="models().Organization"
                    :root-id="id"
                    :model="models().OrganizationArticle"
                    loaderType="text"
                  >
                    <template #list.item="{items}">
                      <h4 class="ot_grey--text font-weight-regular">{{$t('organizationArticle')}}</h4>
                      <UiTemplateDataTable
                        :headers="[
                          { text: $t('title'), value: 'title' },
                          { text: $t('link'), value: 'link' },
                          { text: $t('date'), value: 'date' },
                        ]"
                        :items="items"
                      >
                        <template #item.date="{item}"><UiTemplateDate :data="item.date" /></template>
                      </UiTemplateDataTable>
                    </template>
                  </UiSubResource>
                </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">
                  <UiSubResource
                    :query="repositories().bankAccountRepository.query()"
                    :root-model="models().Organization"
                    :root-id="id"
                    :model="models().BankAccount"
                    loaderType="image"
                    newLink="/organization/bank_account/new"
                  >
                    <template #list.item="{items}">
                      <v-container fluid>
                        <v-row dense>
                          <v-col
                            v-for="item in items"
                            :key="item.id"
                            cols="4"
                          >
                            <UiCard
                              :id="item.id"
                              :link="`/organization/bank_account/${item.id}`"
                              :model="models().BankAccount"
                            >
                              <template #card.text>
                                <span v-if="item.bankName"><strong>{{ $t('bankName') }}</strong> : {{ item.bankName }} <br></span>

                                <span v-if="item.bic"><strong>{{ $t('bic') }}</strong> : {{ item.bic }} <br></span>
                                <span v-if="item.bicInvalid" class="ot_danger--text"><v-icon class="ot_danger--text">mdi-alert</v-icon> <strong>{{ $t('bicInvalid') }}</strong> : {{ item.bicInvalid }} <br></span>

                                <span v-if="item.iban"><strong>{{ $t('iban') }}</strong> : {{ item.iban }} <br></span>
                                <span v-if="item.ibanInvalid" class="ot_danger--text"><v-icon class="ot_danger--text">mdi-alert</v-icon> <strong>{{ $t('ibanInvalid') }}</strong> : {{ item.ibanInvalid }} <br></span>

                              </template>
                            </UiCard>
                          </v-col>
                        </v-row>
                      </v-container>
                    </template>
                  </UiSubResource>
                </v-col>
              </v-row>
            </v-container>
          </UiExpansionPanel>
        </v-expansion-panels>
      </template>
    </UiForm>
  </LayoutContainer>
</template>

<script lang="ts">
import {defineComponent, useContext, reactive} 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 {useValidator} from "~/composables/form/useValidator";
import {useNavigationHelpers} from '~/composables/form/useNavigationHelpers'
import I18N from '~/services/utils/i18n'
import {Country} from "~/models/Core/Country";
import {useTypeOfPracticeProvider} from "~/composables/data/useTypeOfPracticeProvider";
import ModelsUtils from "~/services/utils/modelsUtils";
import {NetworkOrganization} from "~/models/Network/NetworkOrganization";
import {OrganizationArticle} from "~/models/Organization/OrganizationArticle";

export default defineComponent({
  name: 'OrganizationParent',
  setup () {
    const { store, app: { i18n }, $dataProvider, route } = useContext()
    const {typeOfPractices, fetchState:typeOfPracticesFetchingState} = useTypeOfPracticeProvider($dataProvider)
    const { panel } = useNavigationHelpers(route)
    const { siretError, siretErrorMessage, checkSiret } = useValidator($dataProvider, i18n).useHandleSiret()

    const organizationProfile = reactive($organizationProfile(store))
    const id: number = store.state.profile.organization.id

    const checkSiretHook = async (siret: string, field: string, updateRepository: any) => {
      await checkSiret(siret)
      if (!siretError.value) { updateRepository(siret, field) }
    }

    const formatPhoneNumber = (number: string): string => {
      return I18N.formatPhoneNumber(number)
    }

    const getIdsFromUris = (uris: Array<string>) => {
      const ids:Array<any> = []
      for(const uri of uris){
        ids.push(ModelsUtils.extractIdFromUri(uri))
      }
      return ids
    }

    const getIdFromUri = (uri: string) => ModelsUtils.extractIdFromUri(uri)

    return {
      repositories: () => getRepositories(),
      id,
      organizationProfile,
      models: () => { return { Organization, ContactPoint, BankAccount, OrganizationAddressPostal, Country, NetworkOrganization, OrganizationArticle } },
      rules: () => getRules(i18n, organizationProfile),
      siretError,
      siretErrorMessage,
      checkSiretHook,
      formatPhoneNumber,
      typeOfPractices,
      typeOfPracticesFetchingState,
      panel,
      getIdFromUri,
      getIdsFromUris
    }
  }
})

function getRules (i18n: any, $organizationProfile: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')
    ],
    typeOfPractice: [
      (typeOfPracticeValue: Array<number>) => {
        if(!$organizationProfile.isManagerProduct())
          return typeOfPracticeValue.length > 0 || i18n.t('required')
        return true
      }
    ]
  }
}

function getRepositories () {
  return {
    organizationRepository: repositoryHelper.getRepository(Organization),
    contactPointRepository: repositoryHelper.getRepository(ContactPoint),
    bankAccountRepository: repositoryHelper.getRepository(BankAccount),
    addressRepository: repositoryHelper.getRepository(OrganizationAddressPostal),
    countryRepository: repositoryHelper.getRepository(Country),
    netWorkOrganizationRepository: repositoryHelper.getRepository(NetworkOrganization),
    organizationArticleRepository: repositoryHelper.getRepository(OrganizationArticle),
  }
}
</script>

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