<!--
Contenu de la page pages/organization.vue
Contient toutes les informations sur l'organization courante
-->
<template>
  <LayoutContainer>
    <UiForm v-if="!pending" :model="models().Organization" :entity="organization">
      <template #form.input="{model, entity: organization}">
        <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" v-model="organization.name" :rules="rules.name" />
                </v-col>

                <v-col cols="12" sm="6">
                  <UiInputText field="acronym" v-model="organization.acronym" />
                </v-col>

                <v-col v-if="organizationProfile.isInsideNetwork()" cols="12" sm="6">
                  <UiInputText
                      :label="organizationProfile.isCmf() ? 'identifierCmf' : 'identifierFfec'"
                      field="identifier"
                      v-model="organization.identifier"
                  />
                </v-col>

                <v-col v-if="organizationProfile.isFfec()" cols="12" sm="6">
                  <UiInputText field="ffecApproval" v-model="organization.ffecApproval"/>
                </v-col>

                <v-col cols="12" sm="6">
                  <UiInputText field="description" v-model="organization.description"/>
                </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(organization.logo)"
                    :upload="true"
                    :width="200"
                    field="logo"
                    :ownerId="id"
                  ></UiImage>
                </v-col>

                <v-col v-if="!organizationProfile.isManagerProduct()" cols="12" sm="6">
<!--                  <UiInputEnum field="principalType" v-model="organization.principalType" enum-type="organization_principal_type"/>-->
                </v-col>

<!--                <v-col v-if="!organizationProfile.isFfec() && !organizationProfile.isManagerProduct() && !organizationProfile.isArtist()" cols="12" sm="6">-->
<!--                  <UiInputEnum field="schoolCategory" v-model="organization.schoolCategory" enum-type="organization_school_cat"/>-->
<!--                </v-col>-->

<!--                <v-col v-if="organizationProfile.isFfec()" cols="12" sm="6">-->
<!--                  <UiInputEnum field="typeEstablishment" v-model="organization.typeEstablishment" enum-type="organization_type_establishment"/>-->
<!--                </v-col>-->

<!--                <v-col v-if="organization.typeEstablishment === 'MULTIPLE'" cols="12" sm="6">-->
<!--                  <UiInputEnum field="typeEstablishmentDetail" v-model="organization.typeEstablishmentDetail" enum-type="organization_type_establishment_detail" />-->
<!--                </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(organization.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>

                <!-- TODO: essayer de faire une condition plus explicite pour le v-if -->
<!--                <v-col cols="12" sm="6" v-if="getIdsFromUris(organization.typeOfPractices).indexOf(37) >= 0">-->
<!--                  <UiInputTextArea field="otherPractice" v-model="organization.otherPractice" />-->
<!--                </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">-->
<!--                  <UiCollection-->
<!--                    :model="models().OrganizationAddressPostal"-->
<!--                    :parent="entity"-->
<!--                    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-->
<!--                              :link="`/organization/address/${item.id}`"-->
<!--                              :model="models().OrganizationAddressPostal"-->
<!--                              :entity="item"-->
<!--                            >-->
<!--                              <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>-->
<!--                  </UiCollection>-->
<!--                </v-col>-->
<!--              </v-row>-->
<!--            </v-container>-->
<!--          </UiExpansionPanel>-->

<!--          &lt;!&ndash;  Point de Contact&ndash;&gt;-->
<!--          <UiExpansionPanel id="contact_point" icon="fa-phone">-->
<!--            <v-container class="container">-->
<!--              <v-row>-->
<!--                <v-col cols="12" sm="12">-->
<!--                  <UiCollection-->
<!--                    :model="models().ContactPoint"-->
<!--                    :parent="entity"-->
<!--                    loaderType="image"-->
<!--                    newLink="/organization/contact_points/new"-->
<!--                  >-->
<!--                    <template #list.item="{items}">-->
<!--                      <v-container fluid>-->
<!--                        <v-row :dense="true">-->
<!--                          <v-col-->
<!--                            v-for="item in items"-->
<!--                            :key="item.id"-->
<!--                            cols="4"-->
<!--                          >-->
<!--                            <UiCard-->
<!--                              :link="`/organization/contact_points/${item.id}`"-->
<!--                              :model="models().ContactPoint"-->
<!--                              :entity="item"-->
<!--                            >-->
<!--                              <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&#45;&#45;text"><v-icon class="ot-danger&#45;&#45;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&#45;&#45;text"><v-icon class="ot-danger&#45;&#45;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&#45;&#45;text"><v-icon class="ot-danger&#45;&#45;text">mdi-alert</v-icon> <strong>{{ $t('mobilPhoneInvalid') }}</strong> : {{ formatPhoneNumber(item.mobilPhoneInvalid) }} </span>-->
<!--                              </template>-->
<!--                            </UiCard>-->
<!--                          </v-col>-->
<!--                        </v-row>-->
<!--                      </v-container>-->
<!--                    </template>-->
<!--                  </UiCollection>-->
<!--                </v-col>-->
<!--              </v-row>-->
<!--            </v-container>-->
<!--          </UiExpansionPanel>-->

<!--          &lt;!&ndash; Informations légales &ndash;&gt;-->
<!--          <UiExpansionPanel id="legalInformation" icon="fa-gavel">-->
<!--            <v-container fluid class="container">-->
<!--              <v-row>-->
<!--                <v-col cols="12" sm="6">-->
<!--                  <UiInputText-->
<!--                    field="siretNumber"-->
<!--                    :data="entity['siretNumber']"-->
<!--                    :error="siretError"-->
<!--                    :error-message="siretErrorMessage"-->
<!--                    :rules="rules.siretRule"-->
<!--                    @update="checkSiretHook($event, 'siretNumber')"-->
<!--                  />-->
<!--                </v-col>-->

<!--                <v-col cols="12" sm="6">-->
<!--                  <UiInputText field="apeNumber" :data="entity['apeNumber']"/>-->
<!--                </v-col>-->

<!--                <v-col v-if="entity['legalStatus'] === 'ASSOCIATION_LAW_1901'" cols="12" sm="6">-->
<!--                  <UiInputText field="waldecNumber" :data="entity['waldecNumber']"/>-->
<!--                </v-col>-->

<!--                <v-col cols="12" sm="6">-->
<!--                  <UiInputDatePicker field="creationDate" :data="entity['creationDate']"/>-->
<!--                </v-col>-->

<!--                <v-col cols="12" sm="6">-->
<!--                  <UiInputText field="prefectureName" :data="entity['prefectureName']"/>-->
<!--                </v-col>-->

<!--                <v-col cols="12" sm="6">-->
<!--                  <UiInputText field="prefectureNumber" :data="entity['prefectureNumber']"/>-->
<!--                </v-col>-->

<!--                <v-col cols="12" sm="6">-->
<!--                  <UiInputDatePicker field="declarationDate" :data="entity['declarationDate']"/>-->
<!--                </v-col>-->

<!--                <v-col cols="12" sm="6">-->
<!--                  <UiInputText field="tvaNumber" :data="entity['tvaNumber']"/>-->
<!--                </v-col>-->

<!--                <v-col cols="12" sm="6">-->
<!--                  <UiInputEnum field="legalStatus" :data="entity['legalStatus']" enum-type="organization_legal"/>-->
<!--                </v-col>-->

<!--              </v-row>-->
<!--            </v-container>-->
<!--          </UiExpansionPanel>-->

<!--          &lt;!&ndash;  Agréments &ndash;&gt;-->
<!--          <UiExpansionPanel id="agrements" icon="fa-certificate">-->
<!--            <v-container class="container">-->
<!--              <v-row>-->
<!--                <v-col cols="12" sm="6">-->
<!--                  <UiInputText field="youngApproval" :data="entity['youngApproval']"/>-->
<!--                </v-col>-->

<!--                <v-col cols="12" sm="6">-->
<!--                  <UiInputText field="trainingApproval" :data="entity['trainingApproval']"/>-->
<!--                </v-col>-->

<!--                <v-col cols="12" sm="6">-->
<!--                  <UiInputText field="otherApproval" :data="entity['otherApproval']"/>-->
<!--                </v-col>-->
<!--              </v-row>-->
<!--            </v-container>-->
<!--          </UiExpansionPanel>-->

<!--          &lt;!&ndash; Salariés &ndash;&gt;-->
<!--          <UiExpansionPanel id="salary" icon="fa-users">-->
<!--            <v-container class="container">-->
<!--              <v-row>-->
<!--                <v-col cols="12" sm="6">-->
<!--                  <UiInputText field="collectiveAgreement" :data="entity['collectiveAgreement']"/>-->
<!--                </v-col>-->

<!--                <v-col cols="12" sm="6">-->
<!--                  <UiInputEnum field="opca" :data="entity['opca']" enum-type="organization_opca"/>-->
<!--                </v-col>-->

<!--                <v-col cols="12" sm="6">-->
<!--                  <UiInputText field="icomNumber" :data="entity['icomNumber']"/>-->
<!--                </v-col>-->

<!--                <v-col cols="12" sm="6">-->
<!--                  <UiInputText field="urssafNumber" :data="entity['urssafNumber']"/>-->
<!--                </v-col>-->
<!--              </v-row>-->
<!--            </v-container>-->
<!--          </UiExpansionPanel>-->

<!--          &lt;!&ndash; Réseaux &ndash;&gt;-->
<!--          <UiExpansionPanel v-if="organizationProfile.isInsideNetwork()" id="network" icon="fa-share-alt">-->
<!--            <v-container class="container">-->
<!--              <v-row>-->
<!--                <v-col cols="12" sm="12">-->
<!--                  <UiCollection-->
<!--                    :model="models().NetworkOrganization"-->
<!--                    :parent="entity"-->
<!--                    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>-->
<!--                  </UiCollection>-->
<!--                </v-col>-->
<!--                <v-col v-if="organizationProfile.isFfec()" cols="12" sm="6">-->
<!--                  <UiInputText field="budget" :data="entity['budget']" type="number" />-->
<!--                </v-col>-->

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

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

<!--          &lt;!&ndash; Communication &ndash;&gt;-->
<!--          <UiExpansionPanel id="communication" icon="fa-rss">-->
<!--            <v-container class="container">-->
<!--              <v-row>-->
<!--                <v-col cols="12" sm="6">-->
<!--                  <UiInputText field="twitter" :data="entity['twitter']"/>-->
<!--                </v-col>-->

<!--                <v-col cols="12" sm="6">-->
<!--                  <UiInputText field="youtube" :data="entity['youtube']"/>-->
<!--                </v-col>-->

<!--                <v-col cols="12" sm="6">-->
<!--                  <UiInputText field="facebook" :data="entity['facebook']"/>-->
<!--                </v-col>-->

<!--                <v-col cols="12" sm="6">-->
<!--                  <UiInputText field="instagram" :data="entity['instagram']"/>-->
<!--                </v-col>-->

<!--                <v-col cols="12" sm="6">-->
<!--                  <UiInputCheckbox field="portailVisibility" :data="entity['portailVisibility']"/>-->
<!--                </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(entity['image'])"-->
<!--                      :upload="true"-->
<!--                      :width="200"-->
<!--                      field="image"-->
<!--                      :ownerId="id"-->

<!--                    ></UiImage>-->
<!--                  </div>-->
<!--                </v-col>-->

<!--                <v-col cols="12" sm="12">-->
<!--                  <UiCollection-->
<!--                    :model="models().OrganizationArticle"-->
<!--                    :parent="entity"-->
<!--                    loaderType="text"-->
<!--                  >-->
<!--                    <template #list.item="{items}">-->
<!--                      <h4 class="ot-grey&#45;&#45;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>-->
<!--                  </UiCollection>-->
<!--                </v-col>-->

<!--              </v-row>-->
<!--            </v-container>-->
<!--          </UiExpansionPanel>-->

<!--          &lt;!&ndash; IBAN &ndash;&gt;-->
<!--          <UiExpansionPanel id="bank_account" icon="fa-euro-sign">-->
<!--            <v-container class="container">-->
<!--              <v-row>-->
<!--                <v-col cols="12" sm="12">-->
<!--                  <UiCollection-->
<!--                    :model="models().BankAccount"-->
<!--                    :parent="entity"-->
<!--                    loaderType="image"-->
<!--                    newLink="/organization/bank_account/new"-->
<!--                  >-->
<!--                    <template #list.item="{items}">-->
<!--                      <v-container fluid>-->
<!--                        <v-row :dense="true">-->
<!--                          <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&#45;&#45;text"><v-icon class="ot-danger&#45;&#45;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&#45;&#45;text"><v-icon class="ot-danger&#45;&#45;text">mdi-alert</v-icon> <strong>{{ $t('ibanInvalid') }}</strong> : {{ item.ibanInvalid }} <br></span>-->

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

<script setup lang="ts">

import {useEntityFetch} from "~/composables/data/useEntityFetch";
import TypeOfPractice from "~/models/Organization/TypeOfPractice";
import {computed, ComputedRef, reactive, ref} from "@vue/reactivity";
import {useExtensionPanel} from "~/composables/layout/useExtensionPanel";
import {useRoute} from "#app";
import { useValidation } from "~/composables/form/useValidation";
import {useEntityManager} from "~/composables/data/useEntityManager";
import UrlUtils from "~/services/utils/urlUtils";
import Organization from "~/models/Organization/Organization";
import {useI18nUtils} from "~/composables/utils/useI18nUtils";
import ContactPoint from "~/models/Core/ContactPoint";
import BankAccount from "~/models/Core/BankAccount";
import OrganizationAddressPostal from "~/models/Organization/OrganizationAddressPostal";
import Country from "~/models/Core/Country";
import NetworkOrganization from "~/models/Network/NetworkOrganization";
import OrganizationArticle from "~/models/Organization/OrganizationArticle";
import {useI18n} from "vue-i18n";

const id: number | null = useOrganizationProfileStore().id
if (id === null) {
  throw new Error('Missing organization id')
}

const organizationProfile = reactive($organizationProfile())

const { em } = useEntityManager()
const { fetch, fetchCollection } = useEntityFetch()
const { pending } = fetch(Organization, id)

const organization: ComputedRef<Organization> = computed(() => {
  return em.find(Organization, id)
})

const { data: typeOfPractices, pending: typeOfPracticesPending } = fetchCollection(TypeOfPractice)

const route = ref(useRoute())
const { panel } = useExtensionPanel(route)

const { siretError, siretErrorMessage, validateSiret } = useValidation().useValidateSiret()

const validateSiretHook = async (siret: string, field: string, updateRepository: any) => {
  await validateSiret(siret)
  if (!siretError.value) {
    em.save(Organization, organization.value)
  }
}

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

// TODO: voir si l'extraction de cette id ne pourrait pas être faite en amont, au niveau des post-processors
const getIdsFromUris = (uris: Array<string>) => {
  const ids:Array<any> = []
  for(const uri of uris){
    ids.push(UrlUtils.extractIdFromUri(uri))
  }
  return ids
}

// TODO: voir si l'extraction de cette id ne pourrait pas être faite en amont, au niveau des post-processors
const getIdFromUri = (uri: string) => UrlUtils.extractIdFromUri(uri)

const models = () => {
  return {
    Organization,
    ContactPoint,
    BankAccount,
    OrganizationAddressPostal,
    Country,
    NetworkOrganization,
    OrganizationArticle
  }
}

const i18n = useI18n()

const rules = {
  name: [
    (nameValue: string) => !!nameValue || i18n.t('required'),
    (nameValue: string) => (nameValue || '').length <= 128 || i18n.t('name_length_rule')
  ],
  siret: [
    (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
    }
  ]
}

</script>

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