{% extends "order/order_base.html" %}

{% load inventree_extras %}
{% load status_codes %}
{% load i18n %}
{% load static %}

{% block details %}

{% include 'order/po_tabs.html' with tab='details' %}

<hr>

<div id='order-toolbar-buttons' class='btn-group' style='float: right;'>
    {% if order.status == PurchaseOrderStatus.PENDING and roles.purchase_order.change %}
    <button type='button' class='btn btn-primary' id='new-po-line'>
        <span class='fas fa-plus-circle'></span> {% trans "Add Line Item" %}</button>
    {% endif %}
</div>

<h4>{% trans "Purchase Order Items" %}</h4>

<table class='table table-striped table-condensed' id='po-table' data-toolbar='#order-toolbar-buttons'>
</table>

{% endblock %}

{% block js_ready %}

{{ block.super }}


$("#receive-order").click(function() {
    launchModalForm("{% url 'po-receive' order.id %}", {
        reload: true,
        secondary: [
            {
                field: 'location',
                label: '{% trans "New Location" %}',
                title: '{% trans "Create new stock location" %}',
                url: "{% url 'stock-location-create' %}",
            },
        ]
    });
});

$("#complete-order").click(function() {
    launchModalForm("{% url 'po-complete' order.id %}", {
        reload: true,
    });
});

$("#export-order").click(function() {
    location.href = "{% url 'po-export' order.id %}";
});

{% if order.status == PurchaseOrderStatus.PENDING %}
$('#new-po-line').click(function() {
    launchModalForm("{% url 'po-line-item-create' %}",
        {
            reload: true,
            data: {
                order: {{ order.id }},
            },
            secondary: [
                {
                    field: 'part',
                    label: '{% trans "New Supplier Part" %}',
                    title: '{% trans "Create new supplier part" %}',
                    url: "{% url 'supplier-part-create' %}",
                    data: {
                        supplier: {{ order.supplier.id }},
                    },
                },
            ],
        }
    );
});
{% endif %}

function reloadTable() {
    $("#po-table").bootstrapTable("refresh");
}

function setupCallbacks() {
    // Setup callbacks for the line buttons

    var table = $("#po-table");

    {% if order.status == PurchaseOrderStatus.PENDING %}
    table.find(".button-line-edit").click(function() {
        var pk = $(this).attr('pk');

        launchModalForm(`/order/purchase-order/line/${pk}/edit/`, {
            success: reloadTable,
        });
    });

    table.find(".button-line-delete").click(function() {
        var pk = $(this).attr('pk');

        launchModalForm(`/order/purchase-order/line/${pk}/delete/`, {
            success: reloadTable,
        });
    });
    {% endif %}

    table.find(".button-line-receive").click(function() {
        var pk = $(this).attr('pk');

        launchModalForm("{% url 'po-receive' order.id %}", {
            success: reloadTable,
            data: {
                line: pk,
            },
            secondary: [
                {
                    field: 'location',
                    label: '{% trans "New Location" %}',
                    title: '{% trans "Create new stock location" %}',
                    url: "{% url 'stock-location-create' %}",
                },
            ]
        });
    });

}

$("#po-table").inventreeTable({
    onPostBody: setupCallbacks,
    name: 'purchaseorder',
    formatNoMatches: function() { return "{% trans 'No line items found' %}"; },
    queryParams: {
        order: {{ order.id }},
        part_detail: true,
    },
    url: "{% url 'api-po-line-list' %}",
    columns: [
        {
            field: 'pk',
            title: 'ID',
            visible: false,
            switchable: false,
        },
        {
            field: 'part',
            sortable: true,
            title: '{% trans "Part" %}',
            formatter: function(value, row, index, field) {
                if (row.part) {
                    return imageHoverIcon(row.part_detail.thumbnail) + renderLink(row.part_detail.full_name, `/part/${row.part_detail.pk}/`);
                } else { 
                    return '-';
                }
            },
        },
        {
            sortable: true,
            field: 'part_detail.description',
            title: '{% trans "Description" %}',
        },
        {
            sortable: true,
            field: 'supplier_part_detail.SKU',
            title: '{% trans "Order Code" %}',
            formatter: function(value, row, index, field) {
                return renderLink(value, `/supplier-part/${row.part}/`);
            },
        },
        {
            sortable: true,
            field: 'reference',
            title: '{% trans "Reference" %}',
        },
        {
            sortable: true,
            field: 'quantity',
            title: '{% trans "Quantity" %}'
        },
        {
            sortable: true,
            field: 'received',
            title: '{% trans "Received" %}',
            formatter: function(value, row, index, field) {
                return makeProgressBar(row.received, row.quantity, {
                    id: `order-line-progress-${row.pk}`,
                });
            },
            sorter: function(valA, valB, rowA, rowB) {
                
                if (rowA.received == 0 && rowB.received == 0) {
                    return (rowA.quantity > rowB.quantity) ? 1 : -1;
                }
                
                var progressA = parseFloat(rowA.received) / rowA.quantity;
                var progressB = parseFloat(rowB.received) / rowB.quantity;

                return (progressA < progressB) ? 1 : -1;
            }
        },
        {
            field: 'notes',
            title: '{% trans "Notes" %}',
        },
        {
            field: 'buttons',
            title: '',
            formatter: function(value, row, index, field) {
                var html = `<div class='btn-group'>`;

                var pk = row.pk;

                {% if order.status == PurchaseOrderStatus.PENDING and roles.purchase_order.delete %}
                html += makeIconButton('fa-edit icon-blue', 'button-line-edit', pk, '{% trans "Edit line item" %}');
                html += makeIconButton('fa-trash-alt icon-red', 'button-line-delete', pk, '{% trans "Delete line item" %}');
                {% endif %}

                {% if order.status == PurchaseOrderStatus.PLACED and roles.purchase_order.change %}
                if (row.received < row.quantity) {
                    html += makeIconButton('fa-clipboard-check', 'button-line-receive', pk, '{% trans "Receive line item" %}');
                }
                {% endif %}

                html += `</div>`;

                return html;
            },
        }
    ]
});


{% endblock %}