@include('layouts.commons.errors')
@include('layouts.commons.success')

<form method="POST" id="form_achats_complexes"
    action="{{ route("projets.update_achats_complexes", $projet->id ?? '') }}">
    @csrf
    {{ method_field('PUT') }}
    <input type="hidden" name="projet_id" value="{{ $projet->id }}">

    <div class="row">
        <div class="col-6">
            <div class="form-group row">
                <label for="duree_mois" class="col-6 col-form-label required">Durée en nombre de mois</label>
                <div class="col-6">
                    <input type="number" class="form-control" id="duree_mois" name="duree_mois" min="12" step="12"
                        value="{{ old('duree_mois', $projet->duree_mois ?? 12) }}" {{ $projet->report ? 'readonly' : '' }}>
                    <span class="text-danger error"></span>
                </div>
            </div>
        </div>
        <div class="col-6 text-right">
            <div class="form-group row">
                <label for="duree_mois" class="col-6 col-form-label">Date de notification</label>
                <div class="col-6">
                    <div class="input-group">
                        <input type="text" class="datepicker form-control flatpickr-input" id="date_notification"
                            name="date_notification"
                            value="{{ old('date_notification', isset($projet->date_mise_en_oeuvre) ? date('d/m/Y', strtotime($projet->date_mise_en_oeuvre)) : '') }}">
                        <div class="input-group-append">
                            <span class="input-group-text">
                                <svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-calendar3"
                                    fill="currentColor" xmlns="http://www.w3.org/2000/svg">
                                    <path fill-rule="evenodd"
                                        d="M14 0H2a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2zM1 3.857C1 3.384 1.448 3 2 3h12c.552 0 1 .384 1 .857v10.286c0 .473-.448.857-1 .857H2c-.552 0-1-.384-1-.857V3.857z" />
                                    <path fill-rule="evenodd"
                                        d="M6.5 7a1 1 0 1 0 0-2 1 1 0 0 0 0 2zm3 0a1 1 0 1 0 0-2 1 1 0 0 0 0 2zm3 0a1 1 0 1 0 0-2 1 1 0 0 0 0 2zm-9 3a1 1 0 1 0 0-2 1 1 0 0 0 0 2zm3 0a1 1 0 1 0 0-2 1 1 0 0 0 0 2zm3 0a1 1 0 1 0 0-2 1 1 0 0 0 0 2zm3 0a1 1 0 1 0 0-2 1 1 0 0 0 0 2zm-9 3a1 1 0 1 0 0-2 1 1 0 0 0 0 2zm3 0a1 1 0 1 0 0-2 1 1 0 0 0 0 2zm3 0a1 1 0 1 0 0-2 1 1 0 0 0 0 2z" />
                                </svg>
                            </span>
                        </div>
                        <span class="text-danger"></span>
                    </div>
                </div>
            </div>
        </div>
    </div>


    <h4>Référentiel</h4>
    <div class="row custom-frame pt-3">
        <div class="col-6">
            <div class="form-group row pb-0">
                <label for="montant_tco_reference" class="col-6 col-form-label required">Montant d'exploitation de
                    référence</label>
                <div class="col-6">
                    <div class="input-group">
                        <input type="text" class="form-control autonumeric" id="montant_reference" name="montant_reference"
                        value="{{ old('montant_reference', $projet->montant_reference ?? '') }}" {{ $projet->report ? 'readonly' : '' }}>
                        <div class="input-group-append">
                            <span class="input-group-text">€ / an</span>
                        </div>
                        <span class="text-danger"></span>
                    </div>
                </div>

            </div>
        </div>

        <div class="col-6 text-right">
            <div class="form-group row pb-0">
                <label for="gains_cible_12_mois_plus" class="col-6 col-form-label required">Gains cible</label>
                <div class="col-6">
                    <div class="input-group">
                        <input type="number" class="form-control" id="pourcentage_gains_cible" name="pourcentage_gains_cible"
                            value="{{ old('pourcentage_gains_cible', $projet->pourcentage_gains_cible ?? '') }}" min="0" max="100"
                            {{ $projet->report ? 'readonly' : '' }}>
                        <div class="input-group-append">
                            <span class="input-group-text">%</span>
                        </div>
                        <span class="text-danger"></span>
                    </div>
                </div>


            </div>
        </div>


        <div class="col-12">
            <table id="referentiel-table" class="table table-responsive">
                <thead>
                    <tr class="text-center">
                        <th></th>
                        @if(count($achats_complexes) === 0)
                            <th>{{$annee_N}}</th>
                        @else
                            @foreach($achats_complexes as $annee => $valeur)
                                <th>{{$annee}}</th>
                            @endforeach
                        @endif
                    </tr>
                </thead>
                <tbody>
                    <tr id="tr_montant_reference">
                        <td>Montant de référence</td>
                        @if(count($achats_complexes) === 0)
                            <td>
                                <input type="text" name="montant_reference_annees[]" class="form-control autonumeric" {{ $projet->report ? 'readonly' : '' }}>
                            </td>
                        @else
                            @foreach($achats_complexes as $annee => $valeur)
                            <td>
                                <input type="text" name="montant_reference_annees[]" class="form-control autonumeric"
                                value="{{ old('montant_reference_annees[0]',
                                $valeur['reference'] ?? '') }}" {{ $projet->report ? 'readonly' : '' }}>
                            </td>
                            @endforeach
                        @endif
                    </tr>
                    <tr id="tr_gains_cibles">
                        <td>Gains cibles</td>
                        @if(count($achats_complexes) === 0)
                            <td>
                                <input type="text" class="form-control gains_cibles_annees" disabled>
                            </td>
                        @else
                            @foreach($achats_complexes as $annee => $valeur)
                            <td>
                                <input type="text" class="form-control gains_cibles_annees" disabled>
                            </td>
                            @endforeach
                        @endif
                    </tr>

                </tbody>
            </table>
        </div>
    </div>


    <h4>Notifié</h4>
    <div class="row custom-frame pt-3">
        <div class="col-12">
            <table id="notifie-table" class="table table-responsive">
                <thead>
                    <tr class="text-center">
                        <th></th>
                        @if(count($achats_complexes) === 0)
                            <th>{{$annee_N}}</th>
                        @else
                            @foreach($achats_complexes as $annee => $valeur)
                                <th>{{$annee}}</th>
                            @endforeach
                        @endif
                    </tr>
                </thead>
                <tbody>
                    <tr id="tr-montant-notifie">
                        <td>Montant notifié</td>
                        @if(count($achats_complexes) === 0)
                            <td>
                                <input type="text" class="form-control montant_notifie_annees" disabled>
                            </td>
                        @else
                            @foreach($achats_complexes as $annee => $valeur)
                            <td>
                                <input type="text" class="form-control montant_notifie_annees" disabled>
                            </td>
                            @endforeach
                        @endif
                    </tr>
                    <tr>
                        <td><h6>Détail</h6></td>
                        <td></td>
                    </tr>
                    <tr id="tr-amort-investisseurs">
                        <td>Amort. des investisseurs</td>
                        @if(count($achats_complexes) === 0)
                            <td>
                                <input type="text" name="type_amortissements_investisseurs[]" class="form-control autonumeric">
                            </td>
                        @else
                            @foreach($achats_complexes as $annee => $valeur)
                            <td>
                                <input type="text" name="type_amortissements_investisseurs[]" class="form-control autonumeric"
                                value="{{ old('type_amortissements_investisseurs[0]',
                                $valeur['amortissements_investissements'] ?? '') }}">
                            </td>
                            @endforeach
                        @endif
                    </tr>
                    <tr id="tr-maintenance">
                        <td>Maintenance</td>
                        @if(count($achats_complexes) === 0)
                            <td>
                                <input type="text" name="type_maintenances[]" class="form-control autonumeric">
                            </td>
                        @else
                            @foreach($achats_complexes as $annee => $valeur)
                            <td>
                                <input type="text" name="type_maintenances[]" class="form-control autonumeric"
                                value="{{ old('type_maintenances[0]',
                                $valeur['maintenances'] ?? '') }}">
                            </td>
                            @endforeach
                        @endif
                    </tr>
                    <tr id="tr-couts-installation">
                        <td>Coûts d'installation</td>
                        @if(count($achats_complexes) === 0)
                            <td>
                                <input type="text" name="type_couts_installation[]" class="form-control autonumeric">
                            </td>
                        @else
                            @foreach($achats_complexes as $annee => $valeur)
                            <td>
                                <input type="text" name="type_couts_installation[]" class="form-control autonumeric"
                                value="{{ old('type_couts_installation[0]',
                                $valeur['couts_installations'] ?? '') }}">
                            </td>
                            @endforeach
                        @endif
                    </tr>
                    <tr id="tr-consommables">
                        <td>Consommables</td>
                        @if(count($achats_complexes) === 0)
                            <td>
                                <input type="text" name="type_consommables[]" class="form-control autonumeric">
                            </td>
                        @else
                            @foreach($achats_complexes as $annee => $valeur)
                            <td>
                                <input type="text" name="type_consommables[]" class="form-control autonumeric"
                                value="{{ old('type_consommables[0]',
                                $valeur['consommables'] ?? '') }}">
                            </td>
                            @endforeach
                        @endif
                    </tr>
                    <tr id="tr-couts-formation">
                        <td>Coûts de formation</td>
                        @if(count($achats_complexes) === 0)
                            <td>
                                <input type="text" name="type_couts_formation[]" class="form-control autonumeric">
                            </td>
                        @else
                            @foreach($achats_complexes as $annee => $valeur)
                            <td>
                                <input type="text" name="type_couts_formation[]" class="form-control autonumeric"
                                value="{{ old('type_couts_formation[0]',
                                $valeur['couts_formations'] ?? '') }}">
                            </td>
                            @endforeach
                        @endif
                    </tr>
                    <tr id="tr-ressources-internes">
                        <td>Ressources internes</td>
                        @if(count($achats_complexes) === 0)
                            <td>
                                <input type="text" name="type_ressources_internes[]" class="form-control autonumeric">
                            </td>
                        @else
                            @foreach($achats_complexes as $annee => $valeur)
                            <td>
                                <input type="text" name="type_ressources_internes[]" class="form-control autonumeric"
                            value="{{ old('type_ressources_internes[0]',
                                $valeur['resources_internes'] ?? '') }}">
                            </td>
                            @endforeach
                        @endif
                    </tr>
                    <tr id="tr-energies">
                        <td>Energies</td>
                        @if(count($achats_complexes) === 0)
                            <td>
                                <input type="text" name="type_energies[]" class="form-control autonumeric">
                            </td>
                        @else
                            @foreach($achats_complexes as $annee => $valeur)
                            <td>
                                <input type="text" name="type_energies[]" class="form-control autonumeric"
                            value="{{ old('type_energies[0]',
                                $valeur['energies'] ?? '') }}">
                            </td>
                            @endforeach
                        @endif
                    </tr>
                    <tr id="tr-autres">
                        <td>Autres</td>
                        @if(count($achats_complexes) === 0)
                            <td>
                                <input type="text" name="type_autres[]" class="form-control autonumeric">
                            </td>
                        @else
                            @foreach($achats_complexes as $annee => $valeur)
                            <td>
                                <input type="text" name="type_autres[]" class="form-control autonumeric"
                            value="{{ old('type_autres[0]',
                                $valeur['autres'] ?? '') }}">
                            </td>
                            @endforeach
                        @endif
                    </tr>
                    <tr id="tr-gains-notifies">
                        <td>Gains notifiés</td>
                        @if(count($achats_complexes) === 0)
                            <td>
                                <input type="text" class="form-control gains_notifies_annees" disabled>
                            </td>
                        @else
                            @foreach($achats_complexes as $annee => $valeur)
                            <td>
                                <input type="text" class="form-control gains_notifies_annees" disabled>
                            </td>
                            @endforeach
                        @endif
                    </tr>
                    <tr>
                        <td>Gains notifiés (%)</td>
                        <td>
                            <div class="input-group">
                                <input type="text" id="gains_notifies_pourcentage" class="form-control" disabled>
                                <div class="input-group-append">
                                    <span class="input-group-text">%</span>
                                </div>
                            </div>
                        </td>
                    </tr>

                </tbody>
            </table>
        </div>
    </div>


    <h4>Réalisé</h4>
    <div class="row custom-frame pt-3">
        <div class="col-12">
            <table id="realise-table" class="table table-responsive">
                <thead>
                    <tr class="text-center">
                        <th></th>
                        @if(count($achats_complexes) === 0)
                            <th>{{$annee_N}}</th>
                        @else
                            @foreach($achats_complexes as $annee => $valeur)
                                <th>{{$annee}}</th>
                            @endforeach
                        @endif
                    </tr>
                </thead>
                <tbody>
                    <tr id="tr-montant-realise">
                        <td>Montant réalisé</td>
                        @if(count($achats_complexes) === 0)
                            <td>
                                <input type="text" name="montant_realise_annees[]" class="form-control">
                            </td>
                        @else
                            @foreach($achats_complexes as $annee => $valeur)
                            <td>
                                <input type="text" name="montant_realise_annees[]" class="form-control"
                                value="{{ old('montant_realise_annees[0]',
                                $valeur['realise'] ?? '') }}">
                            </td>
                            @endforeach
                        @endif
                    </tr>
                    <tr id="tr-gains_securises">
                        <td>Gains sécurisés</td>
                        @if(count($achats_complexes) === 0)
                            <td>
                                <input type="text" class="form-control gains_securises_annees" disabled>
                            </td>
                        @else
                            @foreach($achats_complexes as $annee => $valeur)
                            <td>
                                <input type="text" class="form-control gains_securises_annees" disabled>
                            </td>
                            @endforeach
                        @endif
                    </tr>
                    <tr>
                        <td>Gains sécurisés (%)</td>
                        <td>
                            <div class="input-group">
                                <input readonly="" type="text" class="form-control"
                                    id="gains_securises_pourcentage">
                                <div class="input-group-append">
                                    <span class="input-group-text">%</span>
                                </div>
                            </div>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>

    <h4>Synthèse</h4>
    <div class="row custom-frame pt-3">
        <div class="col-sm-8">
            <table id="synthese-table" class="table">
                <thead>
                    <tr>
                        <th></th>
                        @if(count($achats_complexes) === 0)
                            <th>{{$annee_N}}</th>
                        @else
                            @foreach($achats_complexes as $annee => $valeur)
                                <th>{{$annee}}</th>
                            @endforeach
                        @endif
                        <th id="synthese_total">Total</th>
                    </tr>
                </thead>
                <tbody>
                    <tr id="tr-synth-gains-cibles">
                        <td>Gains cibles en montant</td>
                        @if(count($achats_complexes) === 0)
                            <td class="synth_gains_cibles"></td>
                        @else
                            @foreach($achats_complexes as $annee => $valeur)
                                <td class="synth_gains_cibles"></td>
                            @endforeach
                        @endif
                        <td class="synth_gains_cibles_total"></td>
                    </tr>
                    <tr id="tr-synth-gains-securises">
                        <td>Gains notifiés en montant</td>
                        @if(count($achats_complexes) === 0)
                            <td class="synth_gains_notifies"></td>
                        @else
                            @foreach($achats_complexes as $annee => $valeur)
                                <td class="synth_gains_notifies"></td>
                            @endforeach
                        @endif
                        <td class="synth_gains_notifies_total"></td>
                    </tr>
                    <tr id="tr-synth-gains-securises-percentage">
                        <td>Gains sécurisés en montant</td>
                        @if(count($achats_complexes) === 0)
                            <td class="synth_gains_securises"></td>
                        @else
                            @foreach($achats_complexes as $annee => $valeur)
                            <td class="synth_gains_securises"></td>
                            @endforeach
                        @endif
                        <td class="synth_gains_securises_total"></td>
                    </tr>
                    <tr id="tr-synth-economies">
                        <td>Gains budgétaires en montant</td>
                        @if(count($achats_complexes) === 0)
                            <td class="synth_gains_budegtaires"></td>
                        @else
                            @foreach($achats_complexes as $annee => $valeur)
                            <td class="synth_gains_budegtaires"></td>
                            @endforeach
                        @endif
                        <td class="synth_gains_budegtaires_total"></td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>


    <!-- Zone commentaire -->
    <div class="row custom-frame pt-3">
        <div class="col-12">
            <div class="form-group">
                <label for="commentaire">Commentaire</label>
                <textarea class="form-control" name="commentaire" rows="3">{{ old('commentaire', $projet->commentaire ?? '') }}</textarea>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-12">
            <div class="form-group text-right">
                <a href="{{ route('projets.index') }}" class="btn btn-outline-warning">Annuler</a>
                @if($editable)
                    <input type="submit" class="btn btn-outline-success" value="Enregistrer">
                @endif
            </div>
        </div>
    </div>
</form>


{{--Liste des éléments à dupliquer lors de l'ajout d'une colonne --}}
<div id="liste_elements_a_dupliquer" class="d-none">
    {{-- Tableau référentiel --}}
    {{-- Montant de référence --}}
    <div id="referentiel_montant_reference_duplicate">
        <input type="text" name="montant_reference_annees[]" class="form-control autonumeric" {{ $projet->report ? 'readonly' : '' }}>
    </div>
    {{-- Gains cibles --}}
    <div id="referentiel_gains_cible_duplicate" class="d-none">
        <input type="text" class="form-control gains_cibles_annees" disabled>
    </div>


    {{-- Tableau notifié --}}
    {{-- Montant notifié --}}
    <div id="notifie_montant_notifie_duplicate">
        <input type="text" class="form-control montant_notifie_annees" disabled>
    </div>
    {{-- Amortissement des investisseurs --}}
    <div id="notifie_amort_investisseurs_duplicate">
        <input type="text" name="type_amortissements_investisseurs[]" class="form-control">
    </div>
    {{-- Maintenance --}}
    <div id="notifie_maintenance_duplicate">
        <input type="text" name="type_maintenances[]" class="form-control">
    </div>
    {{-- Coûts d'installation --}}
    <div id="notifie_couts_installation_duplicate">
        <input type="text" name="type_couts_installation[]" class="form-control">
    </div>
    {{-- Consommables --}}
    <div id="notifie_consommables_duplicate">
        <input type="text" name="type_consommables[]" class="form-control">
    </div>
    {{-- Coûts de formation --}}
    <div id="notifie_couts_formation_duplicate">
        <input type="text" name="type_couts_formation[]" class="form-control">
    </div>
    {{-- Ressources internes --}}
    <div id="notifie_ressources_internes_duplicate">
        <input type="text" name="type_ressources_internes[]" class="form-control">
    </div>
    {{-- Energies --}}
    <div id="notifie_energies_duplicate">
        <input type="text" name="type_energies[]" class="form-control">
    </div>
    {{-- Autres --}}
    <div id="notifie_autres_duplicate">
        <input type="text" name="type_autres[]" class="form-control">
    </div>
    {{-- Gains notifiés --}}
    <div id="notifie_gains_notifies_duplicate">
        <input type="text" class="form-control gains_notifies_annees" disabled>
    </div>


    {{-- Tableau réalisé --}}
    {{-- Montant réalisé --}}
    <div id="realise_montant_realise_duplicate">
        <input type="text" name="montant_realise_annees[]" class="form-control">
    </div>
    {{-- Gains sécurisés --}}
    <div id="realise_gains_securises_duplicate">
        <input type="text" class="form-control gains_securises_annees" disabled>
    </div>
</div>

{{-- Liste des années qui sont ensuite envoyées au back --}}
<div id="liste_annees">
    @if(count($achats_complexes) === 0)
        <input type="hidden" form="form_achats_complexes" name="annees[]" value="{{$annee_N}}">
    @else
        @foreach($achats_complexes as $annee => $valeur)
            <input type="hidden" form="form_achats_complexes" name="annees[]" value="{{$annee}}">
        @endforeach
    @endif
</div>

{{-- Nombre d'années de départ qui permet de calculer le nombre de colonnes par la suite --}}
<input type="hidden" id="annees_depart" value="{{isset($achats_complexes) ? count($achats_complexes) : 0 }}">


<script>
    $(document).ready(function() {
        $("#duree_mois").on("change", function() {
            construire_tableaux();
        });

        $("#montant_reference").on("change", function(e) {
            e.preventDefault();

            var dureeMois = $("#duree_mois").val();
            var nbColonnes = Math.floor(dureeMois / 12);
            var montant_reference = parseInt($("#montant_reference").val().replace(/ /g, ''));

            // Montant de référence
			var montant_reference_par_annee = Math.round( montant_reference / nbColonnes );
			$( "#referentiel-table input[name='montant_reference_annees[]']" ).each(function() {
				$(this).val(montant_reference_par_annee);
                createOrUpdateAutoNumeric($(this));
            });

            calcul_achats_complexes();
        });


        // Au changement d'une valeur, on recalcule tout
        $("form#form_achats_complexes").on("change", "input:not(#montant_reference)", function() {
            calcul_achats_complexes();
        });

        construire_tableaux();
    });

    function construire_tableaux() {
        // TODO : à optimiser avec un tableau qui stocke le nombre de colonnes. Il est initialisé à 0 ou au nombre de colonnes si on charge des données
        var dureeMois = $("#duree_mois").val();
        if (dureeMois == "" || dureeMois < 12) {
            return;
        }

        // On supprime les éléments déjà ajoutés
        $(".element_duplicated").remove();

        var nbColonnes = Math.floor(dureeMois / 12);
        var i = 1;
        var nbAnneesDepart = parseInt($("#annees_depart").val());
        // Si les années de départ existent et sont inférieurs au nombre de colonnes, on augmente la valeur de i pour ne pas dupliquer les colonnes
        if (nbAnneesDepart !== 0 && nbAnneesDepart <= nbColonnes) {
            i = nbAnneesDepart;
        } // Si elles sont inférieures alors on supprime les colonnes créées au chargement
        else {
            for (var j = nbAnneesDepart ; j > nbColonnes ; j--) {
                $("#referentiel-table tr").children("th:nth-child(" + (j+1) + "), td:nth-child(" + (j+1) + ")").remove();
                $("#notifie-table tr").children("th:nth-child(" + (j+1) + "), td:nth-child(" + (j+1) + ")").remove();
                $("#realise-table tr").children("th:nth-child(" + (j+1) + "), td:nth-child(" + (j+1) + ")").remove();
                $("#synthese-table tr").children("th:nth-child(" + (j+1) + "), td:nth-child(" + (j+1) + ")").remove();
                $("#liste_annees").children("input:nth-child(" + (j+1) + ")").remove();
            }
            $("#annees_depart").val("0"); // On réinitialise les années de départ
        }
        for (i ; i < nbColonnes ; i++){
            var annee_courante = {{$annee_N}} + i;
            var annee_th = "<th class='element_duplicated'>" + annee_courante + "</th>";
            var input_annee_courante = '<input type="hidden" form="form_achats_complexes" name="annees[]" class="element_duplicated" value="' + annee_courante + '">';
            $("#liste_annees").append(input_annee_courante);

            //Tableau référentiel
            var referentiel_td_montant_reference = $("#referentiel_montant_reference_duplicate").html();
            referentiel_td_montant_reference = "<td class='element_duplicated'>" + referentiel_td_montant_reference + "</td>";
            var referentiel_td_gains_cible = $("#referentiel_gains_cible_duplicate").html();
            referentiel_td_gains_cible = "<td class='element_duplicated'>" + referentiel_td_gains_cible + "</td>";
            // On insère les éléments
            $("#referentiel-table thead tr").append(annee_th);
            $("#referentiel-table tr#tr_montant_reference").append(referentiel_td_montant_reference);
            $("#referentiel-table tr#tr_gains_cibles").append(referentiel_td_gains_cible);


            // Tableau notifié
            var notifie_montant_notifie_duplicate = $("#notifie_montant_notifie_duplicate").html();
            notifie_montant_notifie_duplicate = "<td class='element_duplicated'>" + notifie_montant_notifie_duplicate + "</td>";
            var notifie_amort_investisseurs_duplicate = $("#notifie_amort_investisseurs_duplicate").html();
            notifie_amort_investisseurs_duplicate = "<td class='element_duplicated'>" + notifie_amort_investisseurs_duplicate + "</td>";
            var notifie_maintenance_duplicate = $("#notifie_maintenance_duplicate").html();
            notifie_maintenance_duplicate = "<td class='element_duplicated'>" + notifie_maintenance_duplicate + "</td>";
            var notifie_couts_installation_duplicate = $("#notifie_couts_installation_duplicate").html();
            notifie_couts_installation_duplicate = "<td class='element_duplicated'>" + notifie_couts_installation_duplicate + "</td>";
            var notifie_consommables_duplicate = $("#notifie_consommables_duplicate").html();
            notifie_consommables_duplicate = "<td class='element_duplicated'>" + notifie_consommables_duplicate + "</td>";
            var notifie_couts_formation_duplicate = $("#notifie_couts_formation_duplicate").html();
            notifie_couts_formation_duplicate = "<td class='element_duplicated'>" + notifie_couts_formation_duplicate + "</td>";
            var notifie_ressources_internes_duplicate = $("#notifie_ressources_internes_duplicate").html();
            notifie_ressources_internes_duplicate = "<td class='element_duplicated'>" + notifie_ressources_internes_duplicate + "</td>";
            var notifie_energies_duplicate = $("#notifie_energies_duplicate").html();
            notifie_energies_duplicate = "<td class='element_duplicated'>" + notifie_energies_duplicate + "</td>";
            var notifie_autres_duplicate = $("#notifie_autres_duplicate").html();
            notifie_autres_duplicate = "<td class='element_duplicated'>" + notifie_autres_duplicate + "</td>";
            var notifie_gains_notifies_duplicate = $("#notifie_gains_notifies_duplicate").html();
            notifie_gains_notifies_duplicate = "<td class='element_duplicated'>" + notifie_gains_notifies_duplicate + "</td>";
            // On insère les éléments
            $("#notifie-table thead tr").append(annee_th);
            $("#notifie-table tr#tr-montant-notifie").append(notifie_montant_notifie_duplicate);
            $("#notifie-table tr#tr-amort-investisseurs").append(notifie_amort_investisseurs_duplicate);
            $("#notifie-table tr#tr-maintenance").append(notifie_maintenance_duplicate);
            $("#notifie-table tr#tr-couts-installation").append(notifie_couts_installation_duplicate);
            $("#notifie-table tr#tr-consommables").append(notifie_consommables_duplicate);
            $("#notifie-table tr#tr-couts-formation").append(notifie_couts_formation_duplicate);
            $("#notifie-table tr#tr-ressources-internes").append(notifie_ressources_internes_duplicate);
            $("#notifie-table tr#tr-energies").append(notifie_energies_duplicate);
            $("#notifie-table tr#tr-autres").append(notifie_autres_duplicate);
            $("#notifie-table tr#tr-gains-notifies").append(notifie_gains_notifies_duplicate);

            // Tableau réalisé
            var realise_montant_realise_duplicate = $("#realise_montant_realise_duplicate").html();
            realise_montant_realise_duplicate = "<td class='element_duplicated'>" + realise_montant_realise_duplicate + "</td>";
            var realise_gains_securises_duplicate = $("#realise_gains_securises_duplicate").html();
            realise_gains_securises_duplicate = "<td class='element_duplicated'>" + realise_gains_securises_duplicate + "</td>";
            // On insère les éléments
            $("#realise-table thead tr").append(annee_th);
            $("#realise-table tr#tr-montant-realise").append(realise_montant_realise_duplicate);
            $("#realise-table tr#tr-gains_securises").append(realise_gains_securises_duplicate);


            // Tableau synthèse
            var synthese_gains_cibles_duplicate = "<td class='element_duplicated synth_gains_cibles'></td>";
            var synthese_gains_notifies_duplicate = "<td class='element_duplicated synth_gains_notifies'></td>";
            var synthese_gains_securises_duplicate = "<td class='element_duplicated synth_gains_securises'></td>";
            var synthese_gains_budgetaires_duplicate = "<td class='element_duplicated synth_gains_budegtaires'></td>";
            // On insère les éléments
            $("#synthese-table thead tr th#synthese_total").before(annee_th);
            $("#synthese-table tr#tr-synth-gains-cibles td.synth_gains_cibles_total").before(synthese_gains_cibles_duplicate);
            $("#synthese-table tr#tr-synth-gains-securises td.synth_gains_notifies_total").before(synthese_gains_notifies_duplicate);
            $("#synthese-table tr#tr-synth-gains-securises-percentage td.synth_gains_securises_total").before(synthese_gains_securises_duplicate);
            $("#synthese-table tr#tr-synth-economies td.synth_gains_budegtaires_total").before(synthese_gains_budgetaires_duplicate);
		}

        // On applique autonumeric pour tous les nouveaux elements
        applyAutoNumericAllDuplicateElement();

		calcul_achats_complexes();
    }

    function calcul_achats_complexes() {
        if (dureeMois == "" || dureeMois < 12 ) {
            return;
        }

		if (!$("#montant_reference").val()) return;
        if (!$("#pourcentage_gains_cible").val()) return;

		var dureeMois = $("#duree_mois").val();
        var nbColonnes = Math.floor(dureeMois / 12);
		var date_notification_nb_mois = 12 - parseInt($('#date_notification').val().substr(3,2)) + 1;
		var montant_reference = $("#montant_reference").val();
        var gains_cibles = $("#pourcentage_gains_cible").val();

		if (montant_reference && nbColonnes >0 ){

			// Montant de référence
			// var montant_reference_par_annee = Math.round( montant_reference / nbColonnes );
			// $( "#referentiel-table input[name='montant_reference_annees[]']" ).each(function() {
			// 	$(this).val(montant_reference_par_annee);
            // });


			// Parcours du détail et calcul du montant notifié
			var totalGainsNotifies = 0;
			for (var i = 0 ; i <= nbColonnes ; i++) {

                // Gains cibles
                if ($("#referentiel-table input[name='montant_reference_annees[]']").eq(i).val()) {
                    var montant_reference_annee = parseInt($("#referentiel-table input[name='montant_reference_annees[]']").eq(i).val().replace(/ /g, ''));
                    var gains_cible_par_annee = Math.round( (parseInt(montant_reference_annee) * parseInt(gains_cibles) /100));
                    $( "#referentiel-table .gains_cibles_annees" ).eq(i).val(gains_cible_par_annee);
                } else {
                    $( "#referentiel-table .gains_cibles_annees" ).eq(i).val("");
                }

				var colonneMontantNotifie = $("#notifie-table .montant_notifie_annees").eq(i);
				var colonneGainsNotifies = $("#notifie-table .gains_notifies_annees").eq(i);
				var total = 0;
				// Amortissement des investisseurs
				if ($("#notifie-table input[name='type_amortissements_investisseurs[]']").eq(i).val())
					total += parseInt($("#notifie-table input[name='type_amortissements_investisseurs[]']").eq(i).val().replace(/ /g, ''));
				// Maintenance
				if ($("#notifie-table input[name='type_maintenances[]']").eq(i).val())
					total += parseInt($("#notifie-table input[name='type_maintenances[]']").eq(i).val().replace(/ /g, ''));
				// Coûts d'installation
				if ($("#notifie-table input[name='type_couts_installation[]']").eq(i).val())
					total += parseInt($("#notifie-table input[name='type_couts_installation[]']").eq(i).val().replace(/ /g, ''));
				// Consommables
				if ($("#notifie-table input[name='type_consommables[]']").eq(i).val())
					total += parseInt($("#notifie-table input[name='type_consommables[]']").eq(i).val().replace(/ /g, ''));
				// Coûts de formation
				if ($("#notifie-table input[name='type_couts_formation[]']").eq(i).val())
					total += parseInt($("#notifie-table input[name='type_couts_formation[]']").eq(i).val().replace(/ /g, ''));
				// Ressources internes
				if ($("#notifie-table input[name='type_ressources_internes[]']").eq(i).val())
					total += parseInt($("#notifie-table input[name='type_ressources_internes[]']").eq(i).val().replace(/ /g, ''));
				// Energies
				if ($("#notifie-table input[name='type_energies[]']").eq(i).val())
					total += parseInt($("#notifie-table input[name='type_energies[]']").eq(i).val().replace(/ /g, ''));
				// Autres
				if ($("#notifie-table input[name='type_autres[]']").eq(i).val())
					total += parseInt($("#notifie-table input[name='type_autres[]']").eq(i).val().replace(/ /g, ''));
				if (total > 0) {
					colonneMontantNotifie.val(total);
					var montantReferenceColonne = parseInt($( "#referentiel-table input[name='montant_reference_annees[]']" ).eq(i).val().replace(/ /g, ''));
					var calculGainNotifie = montantReferenceColonne - total;
					colonneGainsNotifies.val(calculGainNotifie);
					totalGainsNotifies += calculGainNotifie;
				} else {
                    colonneMontantNotifie.val("");
                    colonneGainsNotifies.val("");
                }
			}
            $( "#referentiel-table .gains_cibles_annees" ).each(function() {
                createOrUpdateAutoNumeric($(this));
            });
            $("#notifie-table .gains_notifies_annees").each(function() {
                createOrUpdateAutoNumeric($(this));
            });

			var calculGainsNotifiesPourcentage = (totalGainsNotifies/parseInt(montant_reference)*100).toFixed(2);
			$("#gains_notifies_pourcentage").val(calculGainsNotifiesPourcentage);
            createOrUpdateAutoNumeric($("#gains_notifies_pourcentage"));

			// Gains sécurisés
			var i = 0;
			var totalGainsSecurises = 0;
			$( "#realise-table input[name='montant_realise_annees[]']" ).each(function() {
				if ($(this).val() && $(this).val() > 0) {
					var calculGainsSecurises = parseInt($( "#referentiel-table input[name='montant_reference_annees[]']" ).eq(i).val()) - parseInt($(this).val());
					totalGainsSecurises += calculGainsSecurises;
                    $("#realise-table .gains_securises_annees").eq(i).val(calculGainsSecurises);
				} else {
                    $("#realise-table .gains_securises_annees").eq(i).val("");
                }
				i++;
			});
            $("#realise-table .gains_securises_annees").each(function () {
                createOrUpdateAutoNumeric($(this));
            });
			var totalGainsSecurisesPourcentage = (totalGainsSecurises/parseInt(montant_reference)*100).toFixed(2);
			$("#gains_securises_pourcentage").val(totalGainsSecurisesPourcentage);
            createOrUpdateAutoNumeric($('#gains_securises_pourcentage'));

			// Synthèse gains cibles
			var i = 0;
			var totalGainsCiblesMontant = 0;
			$("#referentiel-table .gains_cibles_annees").each(function(){
				if ($(this).val()) {
					var currentGainsCibles = parseInt($(this).val());
					$("#synthese-table .synth_gains_cibles").eq(i).html(currentGainsCibles);
					totalGainsCiblesMontant += currentGainsCibles;
				} else {
                    $("#synthese-table .synth_gains_cibles").eq(i).empty();
                }
				i++;
			});
			$(".synth_gains_cibles_total").html(totalGainsCiblesMontant);

			// Synthèse gains notifiés
			var i = 0;
			var totalGainsNotifiesMontant = 0;
			$("#notifie-table .montant_notifie_annees").each(function(){
				if ($(this).val()) {
					var currentGainsNotifies = parseInt($(this).val());
					$("#synthese-table .synth_gains_notifies").eq(i).html(currentGainsNotifies);
					totalGainsNotifiesMontant += currentGainsNotifies;
				} else {
                    $("#synthese-table .synth_gains_notifies").eq(i).empty();
                }
				createOrUpdateAutoNumeric($(this));
				i++;
			});
			$(".synth_gains_notifies_total").html(totalGainsNotifiesMontant);

			// Synthèse gains sécurisés
			var i = 0;
			var totalGainsSecurisesMontant = 0;
			$("#realise-table .gains_securises_annees").each(function(){
				if ($(this).val()) {
					var currentGainsSecurises = parseInt($(this).val());
					$("#synthese-table .synth_gains_securises").eq(i).html(currentGainsSecurises);
					totalGainsSecurisesMontant += currentGainsSecurises;
				} else {
                    $("#synthese-table .synth_gains_securises").eq(i).empty();
                }
				i++;
			});
			$(".synth_gains_securises_total").html(totalGainsSecurisesMontant);

			// Synthèse gains budgétaires
			var i = 0;
			var totalGainsBudgetairesMontant = 0;
			var gains_reductions_budgetaires ={{$projet->impact_budgetaire}};
			$("#notifie-table .gains_notifies_annees").each(function(){
				if ($(this).val()) {
					var currentGainsBudgetaires = Math.round(parseInt($(this).val()) * gains_reductions_budgetaires / 100);
					$("#synthese-table .synth_gains_budegtaires").eq(i).html(currentGainsBudgetaires);
					totalGainsBudgetairesMontant += currentGainsBudgetaires;
				} else {
                    $("#synthese-table .synth_gains_budegtaires").eq(i).empty();
                }
				i++;
			});
			$(".synth_gains_budegtaires_total").html(totalGainsBudgetairesMontant);
        }
    }

    function createOrUpdateAutoNumeric(DOMElement)
    {
        if(DOMElement.length) {
            if (AutoNumeric.getAutoNumericElement(DOMElement[0]) === null) {
                new AutoNumeric(DOMElement[0], autonumericConfig);
            }
            else {
                // Permet de gérer les élements de synthèse qui sont des span et non des inputs
                DOMElement.val() === '' ?
                    AutoNumeric.getAutoNumericElement(DOMElement[0]).set(DOMElement.html())
                    : AutoNumeric.getAutoNumericElement(DOMElement[0]).set(DOMElement.val());
            }
        }
    }

    function applyAutoNumericAllDuplicateElement()
    {
        // Tableau referentiel
        $('#referentiel-table').find('input').each(function () {
            createOrUpdateAutoNumeric($(this));
        });

        // Tableau notifié
        $('.montant_notifie_annees').each(function () {
            createOrUpdateAutoNumeric($(this));
        });
        $('#notifie-table').find('input').each(function () {
            createOrUpdateAutoNumeric($(this));
        });
        $('.gains_notifies_annees').each(function () {
            createOrUpdateAutoNumeric($(this));
        });

        // Tableau réalisé
        $('#realise-table').find('input').each(function () {
            createOrUpdateAutoNumeric($(this));
        });

        // Tableau synthèse
        $('#synthese-table').find('input').each(function () {
            createOrUpdateAutoNumeric($(this));
        });
    }
</script>
