{#
    /**
     * This file is part of FacturaScripts
     * Copyright (C) 2017-2021 Carlos Garcia Gomez <carlos@facturascripts.com>
     *
     * This program is free software: you can redistribute it and/or modify
     * it under the terms of the GNU Lesser General Public License as
     * published by the Free Software Foundation, either version 3 of the
     * License, or (at your option) any later version.
     *
     * This program is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
     * GNU Lesser General Public License for more details.
     *
     * You should have received a copy of the GNU Lesser General Public License
     * along with this program. If not, see http://www.gnu.org/licenses/.
     */
#}
{% set thisView = fsc.getCurrentView() %}

<script type="text/javascript">
    businessDocViewLineData = {{ thisView.getLineData() | raw }};
    businessDocViewFormName = "form{{ thisView.getViewName() }}";
    businessDocViewUrl = "{{ thisView.model.url('edit') | raw }}";
    function businessDocViewDelete(viewName) {
        bootbox.confirm({
            title: "{{ i18n.trans('confirm-delete') }}",
            message: "{{ i18n.trans('are-you-sure') }}",
            closeButton: false,
            buttons: {
                cancel: {
                    label: '<i class="fas fa-times"></i> {{ i18n.trans('cancel') }}'
                },
                confirm: {
                    label: '<i class="fas fa-check"></i> {{ i18n.trans('confirm') }}',
                    className: "btn-danger"
                }
            },
            callback: function (result) {
                if (result) {
                    $("#form" + viewName + " :input[name=\"action\"]").val("delete");
                    $("#form" + viewName).submit();
                }
            }
        });

        return false;
    }
</script>

<form id="form{{ thisView.getViewName() }}" action="#" method="post">
    <input type="hidden" name="action"/>
    <input type="hidden" name="activetab" value="{{ thisView.getViewName() }}"/>
    <input type="hidden" name="code" value="{{ thisView.model.primaryColumnValue() }}"/>
    <input type="hidden" name="{{ thisView.model.primaryColumn() }}" value="{{ thisView.model.primaryColumnValue() }}"/>
    <input type="hidden" name="idestado" value="{{ thisView.model.idestado }}" id="doc_idestado"/>
    <input type="hidden" name="multireqtoken" value="{{ fsc.multiRequestProtection.newToken() }}"/>
    <div class="{{ currentView.settings.card ? '' : 'container-fluid' }}">
        <div class="form-row">
            {% if thisView.model.subjectColumn() == 'codcliente' %}
                {{ _self.customerSelect(i18n, 'codcliente', 'codcliente', thisView.model, fsc.getNewSubjectUrl()) }}
            {% elseif thisView.model.subjectColumn() == 'codproveedor' %}
                {{ _self.supplierSelect(i18n, 'codproveedor', 'codproveedor', thisView.model, fsc.getNewSubjectUrl()) }}
            {% endif %}
            {{ _self.customSelect('doc_codalmacen', 'codalmacen', thisView.model.codalmacen, thisView.getSelectValues('Almacen')) }}
            {{ _self.customSelect('doc_codserie', 'codserie', thisView.model.codserie, thisView.getSelectValues('Serie')) }}
            {{ _self.customInput('doc_fecha', 'fecha', thisView.model.fecha, 'text', 'fas fa-calendar-alt', {class: 'form-control datepicker'}) }}
            {% for field in fsc.getCustomFields() %}
                {{ _self.customInput('doc_' ~ field.name, field.name, fsc.getViewModelValue(thisView.getViewName(), field.name),
                    'text', field.icon, {placeholder: i18n.trans(field.label)}) }}
            {% endfor %}
            {{ _self.customSelect('doc_codpago', 'codpago', thisView.model.codpago, thisView.getSelectValues('FormaPago')) }}
            {{ _self.customSelect('doc_coddivisa', 'coddivisa', thisView.model.coddivisa, thisView.getSelectValues('Divisa')) }}
            <div class="col-sm-3 col-md-2 col-lg mb-2">
                <div class="input-group">
                    <input type="text" id="doc_total" name="total" value="{{ thisView.model.total }}" class="form-control text-right" disabled="" />
                    <div class="input-group-append">
                        {% if thisView.settings.btnSave %}
                            <button type="button" class="btn btn-primary" onclick="businessDocViewSave();">
                                <i class="fas fa-save" aria-hidden="true"></i>
                            </button>
                        {% endif %}
                    </div>
                </div>
            </div>
            {{ _self.statusSelect(thisView.model, thisView, i18n) }}
        </div>
        {% if thisView.model.exists() %}
            <div class="row">
                {{ _self.parentDocuments(thisView.model.parentDocuments(), fsc, i18n) }}
                {% if thisView.model.femail %}
                    <div class="col-sm">
                        <div class="alert alert-info text-center">
                            <i class="fas fa-envelope fa-fw" aria-hidden="true"></i> {{ thisView.model.femail }}
                        </div>
                    </div>
                {% endif %}
                {% if thisView.model.paid() %}
                    <div class="col-sm">
                        <div class="alert alert-success text-center">
                            <i class="fas fa-check fa-fw" aria-hidden="true"></i> {{ i18n.trans('paid') }}
                        </div>
                    </div>
                {% endif %}
                {% if thisView.model.editable == false %}
                    <div class="col-sm">
                        <div class="alert alert-danger text-center">
                            <i class="fas fa-lock fa-fw"></i> {{ i18n.trans('non-editable-document') }}
                        </div>
                    </div>
                {% endif %}
                {{ _self.childrenDocuments(thisView.model.childrenDocuments(), fsc, i18n) }}
            </div>
        {% endif %}
        <div id="document-lines"></div>
        <div class="form-row mt-2">
            <div class="col-sm-12">
                <p class="text-center text-muted">
                    {{ i18n.trans('grid-help') }}
                    {% if thisView.getMaxLines() < 200 %}
                        <span class="text-danger">
                            {{ i18n.trans('max-input-vars-warning', {'%numlines%': thisView.getMaxLines()}) }}
                        </span>
                    {% endif %}
                </p>
            </div>
            {% if fsc.showDocSubType %}
                {{ _self.customSelect('doc_codsubtipodoc', 'codsubtipodoc', thisView.model.codsubtipodoc,
                    thisView.getSelectValues('BusinessDocSubType'), true, i18n.trans('doc-subtype')) }}
            {% endif %}
            {% if fsc.showDocOperation %}
                {{ _self.customSelect('doc_codoperaciondoc', 'codoperaciondoc', thisView.model.codoperaciondoc,
                    thisView.getSelectValues('BusinessDocTypeOperation'), true, i18n.trans('doc-operation')) }}
            {% endif %}
            {{ _self.customInput('doc_netosindto', 'netosindto', thisView.model.netosindto, 'text', '',
                {class: 'form-control', disabled: ''}, i18n.trans('subtotal')) }}
            {% if thisView.model.editable %}
                {{ _self.customInput('doc_dtopor1', 'dtopor1', thisView.model.dtopor1, 'number', 'fas fa-percentage',
                    {class: 'form-control'}, i18n.trans('global-dto')) }}
                {{ _self.customInput('doc_dtopor2', 'dtopor2', thisView.model.dtopor2, 'number', 'fas fa-percentage',
                    {class: 'form-control'}, i18n.trans('global-dto-2')) }}
            {% else %}
                {{ _self.customInput('doc_dtopor1', 'dtopor1', thisView.model.dtopor1, 'number', 'fas fa-percentage',
                    {class: 'form-control', disabled: ''}, i18n.trans('global-dto')) }}
                {{ _self.customInput('doc_dtopor2', 'dtopor2', thisView.model.dtopor2, 'number', 'fas fa-percentage',
                    {class: 'form-control', disabled: ''}, i18n.trans('global-dto-2')) }}
            {% endif %}
            {{ _self.customInput('doc_neto', 'neto', thisView.model.neto, 'text', '',
                {class: 'form-control', disabled: ''}, i18n.trans('net')) }}
            {{ _self.customInput('doc_totaliva', 'totaliva', thisView.model.totaliva, 'text', '',
                {class: 'form-control', disabled: ''}, i18n.trans('taxes')) }}
            {% if thisView.model.totalrecargo != 0 %}
                {{ _self.customInput('doc_totalrecargo', 'totalrecargo', thisView.model.totalrecargo, 'text', '',
                    {class: 'form-control', disabled: ''}, i18n.trans('re')) }}
            {% endif %}
            {% if thisView.model.totalirpf != 0 %}
                {{ _self.customInput('doc_totalirpf', 'totalirpf', thisView.model.totalirpf, 'text', '',
                    {class: 'form-control', disabled: ''}, i18n.trans('irpf')) }}
            {% endif %}
            {% if thisView.model.totalsuplidos != 0 %}
                {{ _self.customInput('doc_totalsuplidos', 'totalsuplidos', thisView.model.totalsuplidos, 'text', '',
                    {class: 'form-control', disabled: ''}, i18n.trans('supplied-amount')) }}
            {% endif %}
            {{ _self.customInput('doc_total2', 'total', thisView.model.total, 'text', '',
                {class: 'form-control', disabled: ''}, i18n.trans('total')) }}
        </div>
        <div class="form-row mb-2">
            {{ thisView.getRow('business').edit(thisView.model) | raw }}
        </div>
        <div class="form-row">
            <div class="col">
                {% if fsc.hasData and thisView.settings.btnDelete %}
                    <button type="button" class="btn btn-sm btn-danger" onclick="businessDocViewDelete('{{ thisView.getViewName() }}');">
                        <i class="fas fa-trash-alt fa-fw" aria-hidden="true"></i>
                        <span class="d-none d-sm-inline-block">{{ i18n.trans('delete') }}</span>
                    </button>
                {% endif %}
            </div>
            <div class="col text-center">
                {% block extras %}
                    {{ thisView.getRow('actions').render(false, thisView.getViewName()) | raw }}
                {% endblock %}
            </div>
            <div class="col text-right">
                {% if thisView.settings.btnUndo %}
                    <a class="btn btn-sm btn-secondary" href="{{ thisView.model.url() }}">
                        <i class="fas fa-undo fa-fw" aria-hidden="true"></i>
                        <span class="d-none d-sm-inline-block">{{ i18n.trans('undo') }}</span>
                    </a>
                {% endif %}
                {% if thisView.settings.btnSave %}
                    <button type="button" class="btn btn-sm btn-primary" onclick="businessDocViewSave();">
                        <i class="fas fa-save fa-fw" aria-hidden="true"></i> {{ i18n.trans('save') }}
                    </button>
                {% endif %}
            </div>
        </div>
    </div>
</form>

{% macro customSelect(id, name, value, allValues = {}, allowHide = true, label = '') %}
    {% if allowHide and allValues | length == 1 %}
        {% for key, option in allValues %}
            <input type="hidden" id="{{ id }}" name="{{ name }}" value="{{ key }}"/>
        {% endfor %}
    {% else %}
        <div class="col-sm-3 col-md-2 col-lg mb-2">
            {{ label }}
            <select id="{{ id }}" name="{{ name }}" class="form-control">
                {% for key, option in allValues %}
                    <option value="{{ key }}"{% if value == key %} selected=""{% endif %}>
                        {{ option | raw }}
                    </option>
                {% endfor %}
            </select>
        </div>
    {% endif %}
{% endmacro %}

{% macro customInput(id, name, value, type = "text", icon = NULL, attributes = NULL, label = '') %}
    <div class="col-sm-3 col-md-2 col-lg mb-2">
        {{ label }}
        {% if icon %}
            <div class="input-group">
                <span class="input-group-prepend">
                    <span class="input-group-text">
                        <i class="{{ icon }} fa-fw" aria-hidden="true"></i>
                    </span>
                </span>
            {% endif %}

            <input type="{{ type }}" id="{{ id }}" name="{{ name }}" value="{{ value | raw }}"
                   {% if attributes.class is not defined %}
                       class="form-control"
                   {% endif %}

                   {% for attribute,attrValue in attributes %}
                       {{ attribute }}="{{ attrValue }}"
                   {% endfor %} /> {# end input #}

            {% if icon %}
            </div>
        {% endif %}
    </div>
{% endmacro %}

{% macro customerSelect(i18n, id, name, model, newUrl) %}
    <div class="col-sm-3 col-md-2 col-lg mb-2">
        <div class="input-group">
            <span class="input-group-prepend">
                {% if model.codcliente %}
                    <a href="EditCliente?code={{ model.codcliente }}" target="_blank" class="btn btn-info">
                        <i class="fas fa-user-cog fa-fw" aria-hidden="true"></i>
                    </a>
                {% else %}
                    <a href="{{ newUrl }}" class="btn btn-success" title="{{ i18n.trans('new-customer') }}">
                        <i class="fas fa-user-plus fa-fw" aria-hidden="true"></i>
                    </a>
                {% endif %}
            </span>
            <input type="hidden" id="{{ id }}Autocomplete" name="{{ name }}" value="{{ model.codcliente }}"/>
            {% set autofocus = model.codcliente ? '' : 'autofocus=""' %}
            <input type="text" id="{{ id }}" value="{{ model.nombrecliente | raw }}" class="form-control autocomplete-dc"
                   data-field="{{ id }}" data-source="Cliente" data-fieldcode="codcliente" data-fieldtitle="nombre"
                   placeholder="{{ i18n.trans('customer') }}" {{ autofocus }} autocomplete="off"/>
        </div>
    </div>
{% endmacro %}

{% macro supplierSelect(i18n, id, name, model, newUrl) %}
    <div class="col-sm-3 col-md-2 col-lg mb-2">
        <div class="input-group">
            <span class="input-group-prepend">
                {% if model.codproveedor %}
                    <a href="EditProveedor?code={{ model.codproveedor }}" target="_blank" class="btn btn-info">
                        <i class="fas fa-user-cog fa-fw" aria-hidden="true"></i>
                    </a>
                {% else %}
                    <a href="{{ newUrl }}" class="btn btn-success" title="{{ i18n.trans('new-supplier') }}">
                        <i class="fas fa-user-plus fa-fw" aria-hidden="true"></i>
                    </a>
                {% endif %}
            </span>
            <input type="hidden" id="{{ id }}Autocomplete" name="{{ name }}" value="{{ model.codproveedor }}"/>
            {% set autofocus = model.codproveedor ? '' : 'autofocus=""' %}
            <input type="text" id="{{ id }}" value="{{ model.nombre | raw }}" class="form-control autocomplete-dc"
                   data-field="{{ id }}" data-source="Proveedor" data-fieldcode="codproveedor" data-fieldtitle="nombre"
                   placeholder="{{ i18n.trans('supplier') }}" {{ autofocus }} autocomplete="off"/>
        </div>
    </div>
{% endmacro %}

{% macro statusSelect(model, view, i18n) %}
    {% set status = model.getStatus() %}
    {% if model.exists() == false %}
    {% elseif status.generadoc %}
        <div class="col mb-2">
            <button class="btn btn-block btn-secondary" type="button">
                <i class="{{ status.icon() }} fa-fw" aria-hidden="true"></i> {{ status.nombre }}
            </button>
        </div>
    {% else %}
        <div class="col mb-2">
            <div class="dropdown">
                <button class="btn btn-block btn-secondary dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                    <i class="{{ status.icon() }} fa-fw" aria-hidden="true"></i> {{ status.nombre }}
                </button>
                <div class="dropdown-menu dropdown-menu-right">
                    {% set showDocumentStitcher = false %}
                    {% for status in view.documentStatus %}
                        {% if model.idestado == status.idestado %}
                            <a class="dropdown-item active" href="#">
                                <i class="{{ status.icon() }} fa-fw" aria-hidden="true"></i> {{ status.nombre }}
                            </a>
                        {% else %}
                            <a class="dropdown-item" href="#" onclick="$('#doc_idestado').val('{{ status.idestado }}'); businessDocViewSave();">
                                {% if status.generadoc %}
                                    {% set showDocumentStitcher = true %}
                                {% endif %}
                                <i class="{{ status.icon() }} fa-fw" aria-hidden="true"></i> {{ status.nombre }}
                            </a>
                        {% endif %}
                    {% endfor %}
                    {% if model.exists() and showDocumentStitcher %}
                        <div class="dropdown-divider"></div>
                        <a class="dropdown-item" href="DocumentStitcher?model={{ model.modelClassName() }}&codes={{ model.primaryColumnValue() }}">
                            <i class="fas fa-magic fa-fw" aria-hidden="true"></i> {{ i18n.trans('group-or-split') }}
                        </a>
                    {% endif %}
                </div>
            </div>
        </div>
    {% endif %}
{% endmacro %}

{% macro parentDocuments(relatedDocuments, fsc, i18n) %}
    {% if relatedDocuments | length > 2 %}
        <div class="col-sm">
            <div class="alert alert-warning text-center">
                <i class="fas fa-backward fa-fw" aria-hidden="true"></i>
                <a href="#" data-toggle="modal" data-target="#parentsModal">{{ i18n.trans('previous-documents') }}</a>
            </div>
        </div>
        <div class="modal fade" id="parentsModal" tabindex="-1" role="dialog">
            <div class="modal-dialog modal-lg" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">
                            <i class="fas fa-backward fa-fw" aria-hidden="true"></i>
                            {{ i18n.trans('previous-documents') }}
                        </h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="table-responsive">
                        <table class="table table-hover mb-0">
                            <tbody>
                                {% for doc in relatedDocuments %}
                                    <tr>
                                        <td>
                                            <a href="{{ doc.url() }}">
                                                {{ i18n.trans(doc.modelClassName()) }}
                                                {{ doc.primaryDescription() }}
                                            </a>
                                        </td>
                                        <td class="text-right">{{ fsc.toolBox().coins().format(doc.total) }}</td>
                                        <td class="text-right">{{ doc.fecha }}</td>
                                    </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    {% else %}
        {% for relatedDoc in relatedDocuments %}
            <div class="col-sm">
                <div class="alert alert-warning text-center">
                    <i class="fas fa-backward fa-fw" aria-hidden="true"></i> {{ i18n.trans(relatedDoc.modelClassName()) }}
                    <a href="{{ relatedDoc.url() }}">{{ relatedDoc.primaryDescription() }}</a>
                </div>
            </div>
        {% endfor %}
    {% endif %}
{% endmacro %}

{% macro childrenDocuments(relatedDocuments, fsc, i18n) %}
    {% if relatedDocuments | length > 2 %}
        <div class="col-sm">
            <div class="alert alert-success text-center">
                <i class="fas fa-forward fa-fw" aria-hidden="true"></i>
                <a href="#" data-toggle="modal" data-target="#childrenModal">{{ i18n.trans('documents-generated') }}</a>
            </div>
        </div>
        <div class="modal fade" id="childrenModal" tabindex="-1" role="dialog">
            <div class="modal-dialog modal-lg" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">
                            <i class="fas fa-forward fa-fw" aria-hidden="true"></i>
                            {{ i18n.trans('documents-generated') }}
                        </h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="table-responsive">
                        <table class="table table-hover mb-0">
                            <tbody>
                                {% for doc in relatedDocuments %}
                                    <tr>
                                        <td>
                                            <a href="{{ doc.url() }}">
                                                {{ i18n.trans(doc.modelClassName()) }}
                                                {{ doc.primaryDescription() }}
                                            </a>
                                        </td>
                                        <td class="text-right">{{ fsc.toolBox().coins().format(doc.total) }}</td>
                                        <td class="text-right">{{ doc.fecha }}</td>
                                    </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    {% else %}
        {% for relatedDoc in relatedDocuments %}
            <div class="col-sm">
                <div class="alert alert-success text-center">
                    <i class="fas fa-forward fa-fw" aria-hidden="true"></i> {{ i18n.trans(relatedDoc.modelClassName()) }}
                    <a href="{{ relatedDoc.url() }}">{{ relatedDoc.primaryDescription() }}</a>
                </div>
            </div>
        {% endfor %}
    {% endif %}
{% endmacro %}