{% set menuActive = 'Fournisseur'%}
{% extends 'layout.twig' %}

{% block body %}

<section class="contenu">
	
    <h1>{{ 'Fournisseurs' | trad }}</h1>
    {{ ariane() }}

    <form id="form-search" method="post" 
        class="bg_form padding_form border_form form-default" 
        action="{{ path('Fournisseur.SearchImport.search') | e('html_attr') }}"
        onsubmit="return ajaxSubmit(event);"
        data-onsuccess="updateTable"
    >
        <div class="bs-row gutter-x-base">
            {% if hasFournissTypeChoice %}
            <div class="bs-col-full">
                <div class="wrapper-radio-inline  mx-auto" style="width: 400px;max-width:100%;padding-bottom:15px;">
                    <input id="input-fourniss-PROSPECT-0" class="d-none"
                        type="radio" name="PROSPECT" value="0" checked />
                    <label for="input-fourniss-PROSPECT-0" class="bs-col radio-inline">
                        <span>{{ 'Référencé' | trad }}</span>
                        <i class="icosq-checkmark"></i>
                    </label>
                    <input id="input-fourniss-PROSPECT-1" class="d-none"
                        type="radio" name="PROSPECT" value="1" />
                    <label for="input-fourniss-PROSPECT-1" class="bs-col radio-inline">
                        <span>{{ 'Prospect' | trad }}</span>
                        <i class="icosq-checkmark"></i>
                    </label>
                </div>
            </div>
            {% endif %}
            <div class="bs-col-half">
                {{ inputAdvance('SELECT', {
                    name: 'CODE_PAYS',
                    titre: 'Pays' | trad,
                    listeValue: listePays(),
                    obligatoire: true,
                    value: paysDefault,
                    inputAttr: {
                        onchange: 'changePays(this.value)'
                    }
                }) }}
                {{ inputAdvance('TEXT', {
                    name: 'RS',
                    titre: 'Raison sociale' | trad,
                }) }}
                {{ inputAdvance('TEXT', {
                    name: 'VILLE',
                    titre: 'Ville' | trad,
                }) }}
                {{ inputAdvance('TEXT', {
                    name: 'CPOSTAL',
                    titre: 'Code postal' | trad,
                    pathValidator: path('Ajax.validator.codePostal'),
                    paramsValidator: "{'nomChamp' : '"~'Code postal' | trad~"', 'sizeMin' : '0', 'PAYS' : $('#input_CODE_PAYS').val()}",
                }) }}
                {{ inputAdvance('TEXT', {
                    name: 'NO_DUNS',
                    titre: 'DUNS Number' | trad,
                }) }}
            </div>
            <div class="bs-col-half">
                {% for name in ['NO_SIRET', 'TAXE2', 'TAXE3', 'TAXE4'] %}
                    {% set config = 
                        mapTaxeConfig[paysDefault][name] 
                        ?? mapTaxeConfig['_default'][name]
                    %}
                    <div {{ config.label is empty ? 'style="display: none"' }}>
                        {{ inputAdvance('TEXT', {
                            name: config.name,
                            titre: config.label,
                        }) }}
                    </div>
                    {#
                        pathValidator: path('Ajax.validator.isStringSansEspace'),
                        paramsValidator: {
                            sizeMax: config.validator.max
                        },
                    #}
                {% endfor %}
                
                {{ inputAdvance('TEXT', {
                    name: 'NO_TVA_IC',
                    titre: 'TVA Intra-communautaire' | trad,
                }) }}
            </div>
        </div>

        <div class="text-right">
            <button type="submit" class="button principal mr-0">
                {{- 'Rechercher' | trad -}}
            </button>
        </div>
    </form>
    <section id="section-result">
        <article id="box-warning" class="mt-base error text-center bg_form padding_form border_form"
            style="display: none"
        ></article>
        <p id="p-table-search-count" class="text-center my-base"></p>
        <article id="article-table-search-result" class="mt-base" style="display: none">
            <table class="table table-hover">
                <thead class="thead-dark">
                    <tr>
                        <th scope="col">{{ 'Actif' | trad }}</th>
                        <th id="th-taxe1" scope="col">{# rendered by js #}</th>
                        <th id="th-taxe2" scope="col">{# rendered by js #}</th>
                        <th scope="col">{{ 'Raison sociale' | trad }}</th>
                        <th scope="col">{{ 'Adresse' | trad }}</th>
                        <th scope="col">{{ 'Code Postal' | trad }}</th>
                        <th scope="col">{{ 'Ville' | trad }}</th>
                        <th scope="col">{# Action #}</th>
                    </tr>
                </thead>
                <tbody>
                </tbody>
                <tfoot class="" data-empty-label style="display: none">
                    <tr><td colspan="8" class="text-center text-muted">
                        <p>{{- 'Aucun élément trouvé' | trad -}}</p>
                        <button class="button principal" type="button" onclick="skipSearch()">
                            {{- 'Créer manuellement' | trad -}}
                        </button>
                    </td></tr>
                </tfoot>
            </table>
            <ul id="pagination-table-search" class="pagination"></ul>
            
        </article>
    </section>
</section>
{% apply jsTemplate('tpl-row') %}
    <tr>
        <td class="text-center %isActive_class%">%isActive%</td>
        <td>%NO_SIRET%</td>
        <td>%TAXE2%</td>
        <td>%RS%</td>
        <td>%ADR%</td>
        <td>%CPOSTAL%</td>
        <td>%VILLE1%</td>
        <td class="text-right">
            <span class="white-tooltip mr-base">
                <i class="%warningUniqIconClass% media-middle" style="font-size: 20px"></i>
                <span class="%warningUniqClass% infos_tooltip top-left text-left">
                    {{- 'Un fournisseur avec un %uniqTaxeLib% existant est déjà présent dans la base.' | trad -}}
                </span>
            </span>
            <button type="button" 
                class="button principal %btnSelectClass%" 
                data-click-select
            >{{- 'Importer' | trad -}}</button>
        </td>
    </tr>
{% endapply %}
<script>

{#______________________________________________________________________________
    Actions #}

function skipSearch() {
    var data = new FormData(document.getElementById('form-search'));

    let payload = {};
    for (fieldName of [
        'RS', 'CPOSTAL', 'CODE_PAYS',
        'NO_SIRET', 'TAXE2', 'TAXE3', 'TAXE4',
        'NO_TVA_IC', 'NO_DUNS',
    ]) {
        payload[ fieldName ] = data.get( fieldName );
    }

    if (data.has('PROSPECT'))
        payload.PROSPECT = data.get('PROSPECT');
    payload.VILLE1 = data.get('VILLE');
     
    gotoFormCreation(payload);
}

{#______________________________________________________________________________
    Update taxes #}

var mapTaxeConfig = {{ mapTaxeConfig | json }};
function changePays(codePays) {
    var config = mapTaxeConfig[ codePays ] ?? mapTaxeConfig['_default'];
    for (name of ['NO_SIRET', 'TAXE2', 'TAXE3', 'TAXE4']) {
        
        let label = config[ name ].label;
        let wrapper = document
            .querySelector('[name="'+name+'"]')
            .closest('.input-wrapper');
        
        let labelTag = wrapper.querySelector('label');
        labelTag.textContent = label;

        wrapper.parentElement.style.display = (label.length == 0 ? 'none' : '')
        labelTag.style.display = (label.length == 0 ? 'none' : '')
        // TODO : change validator
    }
    
}

{#______________________________________________________________________________
    Search result Table #}

var PAGE_SIZE = 10;
window.action.updateTable = function(response, status, xhr) {

    // Show table
    let wrapper = document.getElementById('article-table-search-result');
    wrapper.style.display = '';

    let search = response.search;

    // Case : one match (and no warning) -> jump directly to creation form
    if (search.list.length == 1 
        && Object.keys(response.warning).length == 0
    ) {
        selectFour(search.list[0]);
        return;
    }

    // Update table with data
    renderTable(search, 0);

    // Pagination
    let totalPage = Math.ceil(search.list.length / PAGE_SIZE);
    if (totalPage > 1) {
        $('#pagination-table-search').twbsPagination({
            totalPages: totalPage,
            visiblePages: 5,
            next : '>', prev : '<', last : '>>', first : '<<',
            initiateStartPageClick : false,
            onPageClick: function (event, page) {
                renderTable(search, page - 1);
            },
        });
    } else {
        document.getElementById('pagination-table-search').innerHTML = '';
    }

    // Update column name
    let config = mapTaxeConfig[ response.country_code ] ?? mapTaxeConfig['_default'];
    document.getElementById('th-taxe1').textContent = config.NO_SIRET.label;
    document.getElementById('th-taxe2').textContent = config.TAXE2.label;

    // Show total count
    document.getElementById('p-table-search-count').innerHTML = 
        search.count == null && search.hasMore ?
            {{ 'Plus de @1@ résultats trouvés classés par ordre de pertinence' | trad | json }}.replace('@1@', search.list.length) :
            {{ '@1@ résultats trouvés classés par ordre de pertinence' | trad | json }}.replace('@1@', search.count ?? search.list.length);
        


    // Show/hide label "Aucun élément trouvé"
    document
        .querySelector('[data-empty-label]')
        .style.display = (search.list.length == 0 ? '' : 'none');

    // Show/hide warning
    let boxWarning = document.getElementById('box-warning');
    if (Object.keys(response.warning).length != 0) {
        boxWarning.style.display = '';
        let html = '';
        
        for(let [field, warning] of Object.entries(response.warning)) {
            html += 
                '<p>'
                + ({{ 'Un fournisseur avec l’identifiant @1@ existe déjà.' | trad | json }}
                .replace('@1@',config[ field ].label))
                + '<a href="'
                + warning.link
                + '" class="button principal ml-base">'
                + {{ 'Visualiser' | trad | json }}
                + '</a></p>'
        }
        boxWarning.innerHTML = html;
    } else {
        boxWarning.style.display = 'none';
    }

    //_____
    
    desactiveLoader();
}

function renderTable(search, page_index) {
    const list = search.list;
    let wrapper = document.getElementById('article-table-search-result');
    wrapper.style.display = '';
    let tbody = wrapper.querySelector('tbody');
    tbody.innerHTML = ''; // Reset
    for (const four of list.slice(
        page_index * PAGE_SIZE,
        (page_index+1) * PAGE_SIZE
    )) {
        let el = renderRow(four, search);
        tbody.append(el);
        el
            .querySelector('[data-click-select]')
            .addEventListener('click', function() {
                activeLoader();
                selectFour(four);
            })
    }
}


    

function renderRow(fourn, search) {

	let tpl = getJsTemplate('tpl-row');

	// Replace template placeholder
    const mapReplace = {
        isActive_class: (fourn.isActive ? 
            'text-altares-good' : 'text-altares-bad'),
        isActive: fourn.isActive ? 
            {{ '&#10004;' | json }} : {{ '&#10008;' | json }},

        NO_SIRET: fourn.NO_SIRET ?? '-',
        TAXE2: fourn.TAXE2 ?? '-',
        RS: fourn.RS ?? '-',
        ADR: fourn.ADR ?? '-',
        CPOSTAL: fourn.CPOSTAL ?? '-',
        VILLE1: fourn.VILLE1 ?? '-',

        warningUniqClass: 'd-none',
        btnSelectClass: '',
        warningUniqIconClass: '',
    };

    if (fourn._error != null) { // Assume error DUPLICATE NO_SIRET
        mapReplace.warningUniqClass = ''/* Show (remove display none) */;
        let configTaxe = mapTaxeConfig[ fourn.CODE_PAYS ] ?? mapTaxeConfig['FR'];
        mapReplace.uniqTaxeLib = configTaxe[ fourn._error.field ].label;

        if (fourn._error.level == 'error') {
            mapReplace.warningUniqIconClass = 'icosq-error';
            mapReplace.btnSelectClass = 'd-none';
        } else /* Assume search.ctrlUniq == 'N' */ {
            mapReplace.warningUniqIconClass = 'icosq-warning';
        }
    }

	// Transform string into Elements
    let tmp = document.createElement('table');// Since root element is a <tr>, a <table> is requried
    tmp.innerHTML = renderJsTemplate(tpl, mapReplace);
    return tmp.querySelector('tr');
}

function selectFour(four) {

    {% if needDetail %}
        $.ajax({
            url: {{ path('Fournisseur.SearchImport.detail') | json }},
            type: 'POST',
            data : four,
            complete: function (xhr) {
                gotoFormCreation(JSON.parse(xhr.responseText).entity)
            }
        });
    {% else %}
        gotoFormCreation(four)
    {% endif %}
}
function gotoFormCreation(four) {

    var form = new FormData();
    for (fieldName of [
        // TODO : add CHIFF_AFF / get field list from config->mapping
        'CODE_PAYS',
        'ENSCOMM', 'RS', 'ADR', 'VILLE1', 'CPOSTAL',
        'TEL', 'FAX', 'EMAIL', 'SITEWEB',
        'NO_SIRET', 'TAXE2', 'TAXE3', 'TAXE4',
        'NO_TVA_IC', 'NO_DUNS', 'TYP_TVA', 'ID_EXT',
        'DTEVALMIN', 'DTEVALMAX',
        'FOUPPAL', // Groupement
    ]) {
        if (! four.hasOwnProperty(fieldName) ) continue;
        form.append(fieldName, four[ fieldName ]);
    }

    // Dynamic fields (Chiffre affaire)
    for (fieldName in four) {
        if (
            fieldName.startsWith('CHIFF_AFF')
            || fieldName.startsWith('ANNEE_CA')
            || fieldName.startsWith('DEVISE_CA')
        ) {
            form.append(fieldName, four[ fieldName ]);
        }
    }

    let searchForm = new FormData(document.getElementById('form-search'));

    form.append('PROSPECT', searchForm.get('PROSPECT'));

    // Goto Form creation fourniss with prefilled value
    {% if simplifierMode is not null %}
        redirectJSWithPost(
            {{ path('Fournisseur.CreationFournisseurSimplifier.nouveauFournisseur') | json }},
            formDataToObj(form)
        );
    {% else %}
    // TODO : just pass them as post
    setSessionModule(
        {{ path('Fournisseur.SessionCreationFournisseur.sessionAdd') | json }},
        form,
        function() {
            window.location.href = {{ path('Fournisseur.CreationFournisseur.nouveauFournisseur') | json }};
        }
    );
    {% endif %}
}

</script>
<script id="tpl-row" type="template/html">
{# TODO : why code hightlight can't understand the | trad ? #}

</script>

{% endblock %}