var orders = [],
    table_orders = null,
    op_details = null;

function replay() {

}
/**
 * Display the main orders table
 */
function display_orders_table() {
    if (table_orders) {
        table_orders.clear().destroy();
        $('#orders').empty();
    }

    table_orders = $('#orders').DataTable({
        data: orders,
        columns:[
            {
                data:"id",
                title:"Sélectionner",
                className:"dt-body-center",
                render: function (data) {
                    return '<input type="checkbox" id="select_bc_'+data+'" value="'+data+'">';
                },
                width: "4%",
                orderable: false
            },
            {data:"date", "title":"Date traitement", "width": "8%", "className":"dt-body-center"},
            {
                data: "id",
                title: "Id. commande",

            },

            {
                data:"supplier",
                title:"Fournisseur",
                render: function (data, type, full) {
                    // Add tooltip with PO over partner name
                    return '<div class="tooltip">' + data + ' <span class="tooltiptext">' + full.id + '</span> </div>';
                }
            },
            {
                title: "Etape",
                data:"update_type",
                className:"dt-body-center",
                orderable: false,
                width: "20%"
            },

        ],
        dom: 'rtip',
        order: [
            [
                1,
                "asc"
            ]
        ],
        iDisplayLength: 25,
        language: {url : '/static/js/datatables/french.json'}
    });
}


 $('#orders').on('click', 'tbody td', function () {
        var row_data = table_orders.row($(this)).data();
        var data_to_show = [];
        if (op_details) {
            op_details.clear().destroy();
            $('#operation_details').empty();
        }
        var modal_content = $('#show_detail').clone()
        modal_content.find('table').attr('id', 'operation_details')
        modal_content.find('h3').html(row_data.supplier)
        modal_content.find('p').html("Commande id. " + row_data.id + ", étape " + row_data.update_type)
        for (oid in row_data.orders) {
            row_data.orders[oid]['po'].forEach((r) => {data_to_show.push(r)})
        }
        var table_columns = [{
                                data: "barcode",
                                title: "Code-barre",
                             },
                             {

                                title: "Article",
                                render: function (data, type, full) {

                                    return full.product_id[1];
                                }
                            },
                            {
                                title: "UdM",
                                render: function (data, type, full) {

                                    return full.product_uom[1];
                                }
                            }
                            ];

        if (row_data.update_type == 'qty_valid') {
            table_columns.push({data: "old_qty", title: "Qté prévue"});
            table_columns.push({data: "product_qty", title: "Qté reçue"});
        } else {
            table_columns.push({data: "old_price_unit", title: "Prix prévu"});
            table_columns.push({data: "price_unit", title: "Prix constaté"});
        }
        console.log(data_to_show)



        openModal(modal_content.html(), replay, 'Rejouer', false);
        op_details = $('#operation_details').DataTable({
            data: data_to_show,
            columns: table_columns,
            dom: 'rtip',
            order: [
                [
                    1,
                    "asc"
                ]
            ],
            iDisplayLength: 25,
            language: {url : '/static/js/datatables/french.json'}
        });

 })
$(document).ready(function() {
    if (coop_is_connected()) {
        openModal();
        // Set date format for DataTable so date ordering can work
        $.fn.dataTable.moment('D/M/Y');

        // Get orders
        $.ajax({
            type: 'GET',
            url: "/reception/get_backups",
            dataType:"json",
            traditional: true,
            contentType: "application/json; charset=utf-8",
            success: function(data) {
                orders = data.data;
                display_orders_table();
                closeModal();
            },
            error: function(data) {
                err = {msg: "erreur serveur lors de la récupération des commandes", ctx: 'get_list_orders'};
                if (typeof data.responseJSON != 'undefined' && typeof data.responseJSON.error != 'undefined') {
                    err.msg += ' : ' + data.responseJSON.error;
                }
                report_JS_error(err, 'orders');

                alert('Erreur lors de la récupération des commandes, rechargez la page plus tard.');
            }
        });
    }
});