{% extends '@ajax-layout/layout.twig' %}

{% block body %}
    <div>
        <center>
            <div id="genetableau">
                {% set formName = "formSdsLigns" %}
                <form method="POST" id="{{ formName }}" name="{{ formName }}">
                    <input type="hidden" name="inputName" value="{{ post.inputName }}">
                    <input type="hidden" name="divInputs" value="{{ post.divInputs }}" id="divInputs">
                    {{ inputAdvance('SWITCH', {
                        'titre' : 'Sélectionner toutes les lignes ?' | trad,
                        'name' : 'TOUS',
                        'value' : post.TOUS,
                    }) }}
                    <br>
                    <table class="table" id="tableau">
                        <thead class="thead-dark">
                        <tr>
                            <th scope="col">{{ 'N° de ligne' | trad }}</th>
                            <th scope="col">{{ 'Code article' | trad }}</th>
                            <th scope="col" width="250px">{{ 'Désignation' | trad }}</th>
                            <th scope="col">{{ 'Date souhaitée' | trad }}</th>
                            <th scope="col">{{ 'Quantité demandée' | trad }}</th>
                            <th scope="col">{{ 'Reste à servir' | trad }}</th>
                            <th scope="col">{{ post.inputName == 'SBS_LIGNS' ? 'Quantité sortie': 'Quantité transférée' | trad }}</th>
                            <th></th>
                        </tr>
                        </thead>
                        <tbody>
                        {% for key, ligneDemandeService in lignesDemandeService %}
                            <tr id="{{ key }}">
                                {% set path = path('Stock.LigneDemandeService.ligne', { noDs: ligneDemandeService.NO_DS, noLigne: ligneDemandeService.NO_LIG_DS }) %}
                                {% set zoomDivId = 'ligneDemandeService' ~ ligneDemandeService.NO_LIG_DS ~ 'detail' %}
                                <td class="code toggleSlide" onclick="toggleSlide('{{ path }}', '{{ zoomDivId }}', { id : {{ ligneDemandeService.NO_DS }} }, '', '', '');">
                                    {{ ligneDemandeService.NO_LIG_DS }}
                                </td>
                                <td>{{ ligneDemandeService.ART }}</td>
                                <td>{{ ligneDemandeService.ART_DESIGN }}</td>
                                <td>{{ ligneDemandeService.DTE_SOUH | dateTrad }}</td>
                                <td class="text-right">{{ ligneDemandeService.QTE_DEM | qte ~ ' ' ~ ligneDemandeService.UNITE_STK }}</td>
                                <td class="text-right">{{ ligneDemandeService.RESTE | qte ~ ' ' ~ ligneDemandeService.UNITE_STK }}</td>
                                <td>
                                    {{ inputAdvance('TEXT', {
                                        titre: '',
                                        name: 'QTE' ~ key,
                                        obligatoire: true,
                                        value: ligneDemandeService.RESTE | qte,
                                        pathValidator: path('Ajax.validator.float'),
                                        paramsValidator: "{'min' : '0', 'obligatoire': true, 'format': " ~ format_qte() ~ ", 'max': '" ~ ligneDemandeService.RESTE ~ "'}",
                                        addClass: 'text-right qteLign',
                                        inputAttr: {
                                            'data-noLigDs': ligneDemandeService.NO_LIG_DS
                                        }
                                    }) }}
                                </td>
                                <td>
                                    <input
                                            type="checkbox"
                                            class="form-control checkbox"
                                            data-no="{{ ligneDemandeService.NO_LIG_DS }}"
                                            id="checkbox_{{ ligneDemandeService.NO_LIG_DS }}"
                                            name="{{ post.inputName }}[{{ ligneDemandeService.NO_LIG_DS }}]"
                                            onClick="toggleCheckbox(event, 'checkbox_{{ ligneDemandeService.NO_LIG_DS }}');"
                                    />
                                </td>
                            </tr>
                            <tr class="detail_ligne hide_detail" id="{{ zoomDivId }}"></tr>
                        {% endfor %}
                        </tbody>
                    </table>
                </form>
            </div>
            <div class="validation_modal modal-footer">
                <button type="button" class="button principal button_right last mr-0" onClick="updateInputs(getState('{{ post.divInputs }}')); desactivePopup();">
                    {{ 'Valider' | trad }}
                </button>
                <button type="button" class="button secondaire button_right" onClick='desactivePopup();'>{{ 'Fermer' | trad }}</button>
            </div>
        </center>
    </div>
    <script type="application/javascript" src="{{ baseUrl('js/Modules/Stock/selectMultiple.js') }}"></script>
    <script type="application/javascript" src="{{ baseUrl('js/Modules/Stock/inventaireForm.js') }}"></script>
    <script type="application/javascript">
        refreshDomOnComplete('{{ post.divInputs }}');

        function handleSelectAllSwitchChange (event) {
            event.stopPropagation();
            event.stopImmediatePropagation();

            let nextState = [];
            const checkboxes = $('input[data-no]');
            const selectAll = $(event.target).is(':checked');

            checkboxes.each((index, element) => {
                $(element).prop('checked', selectAll);
                nextState = mutateState($(element), nextState);
            });

            setState('{{ post.divInputs }}', nextState);
            setSelectAllState('{{ post.divInputs }}', selectAll);
        }

        function updateInputs (state) {
            const ligneInputs = $('#input_{{ post.inputName }}');

            ligneInputs.empty();
            for (let key in state) {
                $('<input type="hidden" name="{{ post.inputName }}['+key+'][NO_LIG_DS]" value="'+state[key].NO_LIG_DS+'">').appendTo(ligneInputs);
                $('<input type="hidden" name="{{ post.inputName }}['+key+'][QTE]" value="'+state[key].QTE+'">').appendTo(ligneInputs);
            }
        }

        function mutateState (checkbox, state) {
            if (checkbox.is(':checked')) {
                const noLigne = checkbox.attr('data-no');
                const quantity = $('input[data-noLigDs="'+noLigne+'"]').val();

                state.push({ NO_LIG_DS: noLigne, QTE: quantity });
            } else {
                state = state.filter((ligneDemandeService) => ligneDemandeService.NO_LIG_DS !== checkbox.attr('data-no'));
            }

            return state;
        }

        function updateDom (state) {
            for (let key in state) {
                $('input[data-no="'+state[key]['NO_LIG_DS']+'"]').prop('checked', true);
                $('input[data-noLigDs="'+state[key]['NO_LIG_DS']+'"]').val(state[key].QTE);
            }
        }

        $('.qteLign').on('change', (event) => {
            const input = $(event.target);
            const noLigne = input.attr('data-noLigDs');
            const state = getState('{{ post.divInputs }}');

            const nextState = state.map((item) => {
                if (item.NO_LIG_DS === noLigne) {
                    return { ...item, QTE: input.val() };
                }

                return item;
            });

            setState('{{ post.divInputs }}', nextState);
        });
    </script>
{% endblock %}