{% block body %}
	<div id="refreshLigne" style="position:relative;">

		{% if withNavbar %}
			{% include "@Consultation/Consultation/_navbarConsultation.twig" %}
		{% endif %}

			{% if canEdit and not enCours %}

				<header class="bs-row">
					<form class="bs-col">
						<div class="row" id="sizePrice">
							{{ inputAdvance('TEXT',{
        			    'titre' : 'Poids du critère prix' | trad,
        			    'name' : 'POIDS_APRIX',
        			    'addStyle' : 'width:50px;',
        			    'value' : poidsAPRIX,
            		    'pathValidator' : path('Ajax.validator.float'),
            		    'paramsValidator' : "{'format' : 2.2}",
                	    'myFuncValidator' : 'updateValueLigne',
                	    'paramFuncValidator' : '[]',
        			}) }}
						</div>
						<style>
							#sizePrice {
								width: 250px;
							}
							#sizePrice label {
								width: 200px;
							}
						</style>
						<script>

							function updateValueLigne() {

var value = $( '#input_POIDS_APRIX' ).val();

activeLoader();
$.ajax( {

dataType: 'html',
url: '{{ path('Consultation.Articles.ajaxUpdateAPRIX', {idAO:idAO}) }}',
data: {

POIDS_APRIX: value

},
type: "POST",
success: function ( result ) {

desactiveLoader();

}

} );

}
						</script>
					</form>
					<div class="bs-col-auto mb-small">
						<a class="button principal m-0" href="{{ path( 'RechercheArticles.RechercheArticles.recherche', {contexte:'AO', idContexte:idAO} ) }}">
							{{ 'Rechercher dans les catalogues' | trad }}
						</a>
						<a class="button principal m-0" href="{{ path( 'Consultation.Articles.createEdit', {idAO: idAO} ) }}">
							{{ 'Ajouter une ligne libre' | trad }}
						</a>
						<a class="button principal m-0" href="{{ path( 'Consultation.Articles.listeLigneDaImport', {idAO: idAO} ) }}">
							{{ "Importer d'une DA" | trad }}
						</a>
						<a class="button principal m-0" href="{{ path( 'Consultation.Articles.formImport', {idAO: idAO} ) }}">
							{{ 'Import par fichier' | trad }}
						</a>
						{% if ligneConsultation | length > 0 %}
							<a class="button secondaire m-0 showonlyifcheck" href="javascript:void(0)" style="display: none">
								{{ 'Supprimer le(s) ligne(s)' | trad }}
							</a>
						{% endif %}
					</div>
				{% endif %}

				<form method="post" name="form-main" id="form-main" class="tab-content form-default" style="width: 100%; margin: 0">
					<table class="table table-hover">
						<thead class="thead-dark">
							<tr>
								<th scope="col" width="75px">
									{{ 'N° DA' | trad }}
								</th>
								<th scope="col" width="75px">
									{{ 'Ligne' | trad }}
								</th>
								<th scope="col" width="100px">
									{{ 'Code article' | trad }}
								</th>
								<th scope="col" width="">
									{{ 'Désignation' | trad }}
								</th>
								<th scope="col" width="">
									{{ 'Désign. compl.' | trad }}
								</th>
								<th scope="col" width="100px">
									{{'Quantité' | trad }}
								</th>
								<th scope="col" width="50px">
									{{'Unité' | trad }}
								</th>
								<th scope="col" width="135px">
									{{'Prix réf' | trad }}
								</th>
								<th scope="col">
									{{'Budget' | trad }}
								</th>
								<th scope="col" width="75px">
									{{'Actions' | trad }}
								</th>
								<th scope="col" width="" class="white-tooltip">
									{% if ligneConsultation | length > 0 and not enCours%}
										<input name="selectAll" type="checkbox" data-checkall-input="table-main" class="form-control checkbox">
										<span class='infos_tooltip left'>
											{{ 'Tout sélectionner' | trad }}
										</span>
									{% endif %}
								</th>
							</tr>
						</thead>
						<tbody>
							{% set previousTitle = "" %}
							{% set classComponent = 0 %}
							{% set AoEntet = consultation %}
							{% set sousTotalToCount = 0 %}
							{% set shouldStartCount = false %}
							{% for consultation in ligneConsultation %}
								{% if shouldStartCount == false and sousTotalToCount != 0 %}
									{% set sousTotalToCount = 0 %}
								{% endif %}
								{% if consultation.TITRE_AVANT_LIGNE %}
									{% set previousTitle = consultation.TITRE_AVANT_LIGNE %}
									{% set classComponent = classComponent + 1 %}
									<tr class="filter_Dynamique recherche tr_TITRE">
										<td colspan="11">
											<h4 style="margin-left:15px;">
												{{ consultation.TITRE_AVANT_LIGNE }}
											</h4>
										</td>
									</tr>
									{% set shouldStartCount = true %}
								{% endif %}
								<tr id="ligne_{{ consultation.NO_PO }}">
									<td>
										{% if consultation.NO_DA %}
											{{ consultation.NO_DA }}
										{% endif %}
									</td>
									<td class="loupe">
										{% if consultation.NO_PO_DA %}
											{{ consultation.NO_PO_DA }}
										{% endif %}
									</td>
									<td>
										{{ consultation.CODE_ART }}
									</td>
									<td>
										{{ consultation.DES }}
									</td>
									<td>
										{{ shortLibelle(consultation.DES_COMP, 100) }}
									</td>
									{% if not enCours %}
										<td class="montant">
											{{ inputAdvance('TEXT', {
												'name' : consultation.NO_PO,
												'value' : consultation.QTE | prix,
												'pathValidator' : path('Ajax.validator.float'),
												'addStyle' : 'text-align:right',
												'addClass' : 'changeQuantite ' ~ (previousTitle != '' ? 'sousTotalCalcul_quantite_' ~ classComponent : '')
								}) }}
										</td>
									{% else %}
										<td class="montant">
											{{ consultation.QTE | prix }}
										</td>
									{% endif %}
									<td class="devise">
										{{ consultation.UNITE }}
									</td>
									{% if not enCours %}
										<td class="montant">
											{{ inputAdvance('DEVISE', {
									'name' : consultation.NO_PO,
									'value' : consultation.PRIX_REF | prixUnitaire,
									'DEVISE' : AoEntet.DEVISE,
									'pathValidator' : path('Ajax.validator.float'),
									'addStyle' : 'changePrix ' ~ (previousTitle != '' ? 'sousTotalCalcul_prix_' ~ classComponent : ''),
									'addCss' : 'text-align:right; padding-right: 47px'
								}) }}
										</td>
									{% else %}
										<td class="montant">
											{{ consultation.PRIX_REF | prixUnitaire }}
										</td>
									{% endif %}
									<td class="montant">
										{{ consultation.BUDGET | prix }}
									</td>
									<td>
										{% if canEdit and not enCours %}
											{{ hover_action('ligne_'~consultation.NO_PO, 'modifier_v2' , "window.location.href ='"~path('Consultation.Articles.createEdit', {idAO: idAO, idLigne:consultation.NO_PO})~"'", 'float: right;margin-right:5px;') }}
											{{ hover_action('ligne_'~consultation.NO_PO, 'Supprimer_v2' , "popupConfirmation(\'"~path('Ajax.Erreur.popupConfirmationSuppresion')~"\', \'\', \'"~path('Consultation.Articles.delete', {idAO: idAO, idLigne:consultation.NO_PO})~"\', \'"~('Etes-vous sûr de vouloir supprimer le poste' | trad |e('js')|raw)~" ?\', \'refreshLigne\')", 'float: right;margin-right:5px;') }}
										{% endif %}
									</td>
									<td>
										{% if not enCours %}
											<input type="checkbox" class="form-control checkbox selected_line" data-id="{{ consultation.NO_PO }}" data-checkall="table-main" id="input_selected_line_{{ consultation.NO_PO}}" name="selected_line[]" value="{{ consultation.NO_PO }}"/>
										{% endif %}
									</td>
								</tr>
								<tr id="ligne_{{ consultation.NO_PO }}detail" class="detail_ligne hide_detail">
									<td colspan="11">
										<div class="colonne3">
											<div class="informations">
												<p>
													<span class="champs_label">
														{{ 'Fabricant' | trad }}
													</span>
													<span class="resultat">
														{% if consultation.COD_FAB %}
															{{ consultation.fabricant }}
															(
															{{ consultation.COD_FAB }}
															)
														{% endif %}
													</span>
												</p>
												<p>
													<span class="champs_label">
														{{ 'Gamme' | trad }}
													</span>
													<span class="resultat">
														{% if consultation.COD_GAM %}
															{{ consultation.gammes }}
															(
															{{ consultation.COD_GAM }}
															)
														{% endif %}
													</span>
												</p>
											</div>
										</div>
										<div class="colonne3">
											<div class="informations">
												<p>
													<span class="champs_label">
														{{ 'Sous-famille' | trad }}
													</span>
													<span class="resultat">
														{% if consultation.SSFAMILLE %}
															{{ consultation.sousFamille }}
															(
															{{ consultation.SSFAMILLE }}
															)
														{% endif %}
													</span>
												</p>
												<p>
													<span class="champs_label">
														{{ 'Réf. fabricant' | trad }}
													</span>
													<span class="resultat">
														{{ consultation.REF_FAB }}
													</span>
												</p>
											</div>
										</div>
										<div class="colonne3 last">
											<div class="informations">
												<p>
													<span class="champs_label">
														{{ 'Délais' | trad }}
													</span>
													<span class="resultat">
														{{ consultation.DELAI | dateTrad }}
													</span>
												</p>
											</div>
										</div>
									</td>
								</tr>
								{% set sousTotalToCount = sousTotalToCount + (consultation.QTE * consultation.PRIX_REF) %}
								{% if consultation.TITREST %}
									{% if condition %}
										<tr class="filter_Dynamique recherche tr_SSTOTAL">
											<td colspan="11" style="text-align:right;">
												<h5 class="sousTotalCalcul_total_{{classComponent}}">
													{{ consultation.TITREST }}
													: XXX
												</h5>
											</td>
										</tr>
									{% else %}
										<tr class="filter_Dynamique recherche tr_SSTOTAL">
											<td colspan="11" style="text-align:right;">
												<h5 class="sousTotalCalcul_total_{{classComponent}}">
													{{ consultation.TITREST }}
													:
													{{sousTotalToCount | prix ~ ' ' ~ AoEntet.DEVISE}}
												</h5>
											</td>
										</tr>
										{% set sousTotalToCount = 0 %}
										{% set shouldStartCount = false %}
									{% endif %}
								{% endif %}
								{% if consultation.TITREST %}
									{% set previousTitle = '' %}
								{% endif %}
							{% else %}
								<tr>
									<td colspan="11" style="text-align: center; color: DarkGray">
										{{- 'Aucun élément' | trad -}}
									</td>
								</tr>
							{% endfor %}
						</tbody>
					</table>
				</form>
			</div>


			{% set contentPopup %}
			<div class="modal-body clearfix display_table">
				<span class="icone-modal interrogation"></span>
				<div class="display_cell">
					{{"Voulez-vous supprimer le(s) ligne(s) sélectionnée(s)" | trad ~ " ?"}}
				</div>
			</div>
			<div class="modal-footer">
				<button type="button" class="button secondaire" data-dismiss="modal" onclick="desactivePopup();desactiveLoader();">
					{{ 'Annuler' | trad}}
				</button>
				<button type="button" class="button principal" id="confirmeDeleteCustom">
					{{ 'Confirmer' | trad}}
				</button>
			</div>
			{% endset %}

			{% if not enCours %}
				<script>
					function numberWithSpaces( x ) {

const parts = x.toString().split( "." );
parts[ 0 ] = parts[ 0 ].replace( /\B(?=(\d{3})+(?!\d))/g, " " );
return parts.join( "." );

}
function calculSousTotal() {

const allSousTotal = document.querySelectorAll( '[class^="sousTotalCalcul_total_"]' );

for ( const sousTotal of allSousTotal ) {

for ( const cls of sousTotal.classList ) {

const match = cls.match( /^sousTotalCalcul_total_(\d+)$/ );
let numero = match ? match[ 1 ] : null;
if ( numero ) {

const allQte = document.querySelectorAll( '.sousTotalCalcul_quantite_' + numero );
const allPrix = document.querySelectorAll( '.sousTotalCalcul_prix_' + numero );

let total = 0;
allQte.forEach( ( qteEl, index ) => {

let qte = parseFloat( allQte[ index ].textContent.toString().replace( /\s+/g, '' ) || qteEl.value.toString().replace( /\s+/g, '' ) || 0 );
let prix = parseFloat( allPrix[ index ].textContent.toString().replace( /\s+/g, '' ) || allPrix[ index ].value.toString().replace( /\s+/g, '' ) || 0 );
total += qte * prix;

} )
const label = ( sousTotal.innerHTML.split( ' : ' )[ 0 ] ?? '' ) + ' : ';
sousTotal.textContent = label + numberWithSpaces( total.toFixed( 2 ) ) + "  {{ AoEntet.DEVISE }}";

}

}

}

}

$( '.changeQuantite' ).change( function ( event ) {

activeLoader();
$.ajax( {

url: "{{ path('Consultation.Articles.ajaxChangementSurLigne') }}",
type: 'POST',
data: {

'NO_AO': '{{ AoEntet.NO_AO }}',
'NO_PO': event.target.name,
'QTE': event.target.value

},
success: () => {

event.target.value = numberWithSpaces( event.target.value ) + '.00';
desactiveLoader();
calculSousTotal();

},
error: ( data ) => {

desactiveLoader();
document.getElementById( 'modal-content' ).classList.add( 'modal_small' );
$( "#modal-body" ).replaceWith( data.responseText );
activePopup();

}

} );

} );

$( '.changePrix' ).change( function ( event ) {

activeLoader();
$.ajax( {

url: "{{ path('Consultation.Articles.ajaxChangementSurLigne') }}",
type: 'POST',
data: {

'NO_AO': '{{ AoEntet.NO_AO }}',
'NO_PO': event.target.name,
'PRIX_REF': event.target.value

},
success: () => {

event.target.value = event.target.value + '.000';
desactiveLoader();
calculSousTotal();

},
error: ( data ) => {

desactiveLoader();
document.getElementById( 'modal-content' ).classList.add( 'modal_small' );
$( "#modal-body" ).replaceWith( data.responseText );
activePopup();

}

} );

} );

function getAllCheckboxes() {

const checkboxes = document.querySelectorAll( '.checkbox' );
const showonlyifcheck = document.querySelector( '.showonlyifcheck' );
let getAllCheckboxesValue = [];

for ( const [ index, checkbox ] of checkboxes.entries() ) {

checkbox.checked = false;
getAllCheckboxesValue[ index ] = checkbox.checked;

checkbox.addEventListener( 'change', () => {

getAllCheckboxesValue[ index ] = checkbox.checked;

let isChecked = false;
for ( const value of getAllCheckboxesValue ) {

if ( value ) {

isChecked = true;
break;

}

}

console.log( getAllCheckboxesValue );

showonlyifcheck.style.display = isChecked ? '' : 'none';

} );

}

}

const html = {{ contentPopup|json }};
$( '#btn_close' ).click( function ( event ) {

$( ".modal-body" ).replaceWith( html );

} );

$( '.showonlyifcheck' ).click( function ( event ) {

activePopup( '{{ "Voulez-vous supprimer le(s) ligne(s) sélectionnée(s)" | trad ~ " ?" }}', html );
$( '#confirmeDeleteCustom' ).click( function () {

activeLoader();
desactivePopup();
$.ajax( {

url: {{ path('Consultation.Articles.suppressionMultiLignes', {idAO: idAO}) | json }},
type: 'POST',
data: new FormData( document.getElementById( 'form-main' ) ),
type: "POST",
contentType: false,
processData: false,
success: () => {

location.reload();

},
error: ( data ) => {

desactiveLoader();
document.getElementById( 'modal-content' ).classList.add( 'modal_small' );
activePopup( '', data.responseText );

}

} );

} )

} );

document.addEventListener( 'DOMContentLoaded', () => {

calculSousTotal();
getAllCheckboxes();

} )
				</script>
			{% endif %}

		{% endblock %}
