/**
 * Created by Huzaifa on 9/18/15.
 */

$(document).on('change','#from_warehouse_id', function() {
    $warehouse_id = $(this).val();
    $.ajax({
        url: $UrlGetContainers,
        dataType: 'json',
        type: 'post',
        data: 'warehouse_id=' + $warehouse_id,
        mimeType:"multipart/form-data",
        beforeSend: function() {
            $('#container_no').parent().before('<i id="loader" class="fa fa-refresh fa-spin"></i>');
            $('#tblStockTransferDetail tbody').html('');
        },
        complete: function() {
            $('#loader').remove();
        },
        success: function(json) {
            if(json.success)
            {
                $('#container_no').html(json.html).trigger('change');
            }
            else {
                alert(json.error);
            }
        },
        error: function(xhr, ajaxOptions, thrownError) {
            console.log(xhr.responseText);
        }
    })

});

$(document).on('click','#addContainer', function() {
    var $data = {
        warehouse_id : $('#warehouse_id').val(),
        container_no : $('#container_no').val()
    };

    var $details = [];
    $.ajax({
        url: $UrlGetContainerData,
        dataType: 'json',
        type: 'post',
        data: $data,
        mimeType:"multipart/form-data",
        beforeSend: function() {
            $('#addContainer').html('<i id="loader" class="fa fa-refresh fa-spin"></i>');
        },
        complete: function() {
            $('#addContainer').html('<i class="fa fa-plus"></i>');
        },
        success: function(json) {
            if(json.success)
            {
                $details = json['details'];

                console.log($details);
                for($i=0;$i<$details.length;$i++) {
                    fillGrid($details[$i]);
                }
            }
            else {
                alert(json.error);
            }
        },
        error: function(xhr, ajaxOptions, thrownError) {
            console.log(xhr.responseText);
        }
    })
});

function fillGrid($obj) {
    var $from_warehouse_id = $('#from_warehouse_id').val();
    $html = '';
    $html += '<tr id="grid_row_'+$grid_row+'" data-row_id="'+$grid_row+'">';
    $html += '<td><a onclick="removeRow(this);" title="Remove" class="btn btn-xs btn-danger" href="javascript:void(0);"><i class="fa fa-times"></i></a></td>';
    $html += '<td>';
    $html += '<select class="form-control select2" id="stock_transfer_detail_warehouse_id_'+$grid_row+'" name="stock_transfer_details['+$grid_row+'][warehouse_id]" >';
    $html += '<option value="">&nbsp;</option>';
    $warehouses.forEach(function($warehouse) {
        if($warehouse.warehouse_id != $from_warehouse_id) {
            $html += '<option value="'+$warehouse.warehouse_id+'">'+$warehouse.name+'</option>';
        }
    });
    $html += '</select>';
    $html += '</td>';
    $html += '<td>';
    $html += '<input type="text" style="min-width: 100px;" class="form-control" name="stock_transfer_details['+$grid_row+'][manual_ref_no]" id="stock_transfer_detail_manual_ref_no_'+$grid_row+'" value="'+$obj['manual_ref_no']+'" readonly />';
    $html += '</td>';
    $html += '<td>';
    $html += '<input type="text" style="min-width: 100px;" class="form-control" name="stock_transfer_details['+$grid_row+'][container_no]" id="stock_transfer_detail_container_no_'+$grid_row+'" value="'+$obj['container_no']+'" readonly />';
    $html += '</td>';
    $html += '<td>';
    $html += '<input type="text" style="min-width: 100px;" class="form-control" name="stock_transfer_details['+$grid_row+'][batch_no]" id="stock_transfer_detail_batch_no_'+$grid_row+'" value="'+$obj['batch_no']+'" readonly />';
    $html += '</td>';
    $html += '<td>';
    $html += '<input type="text" style="min-width: 100px;" class="form-control" name="stock_transfer_details['+$grid_row+'][product_code]" id="stock_transfer_detail_product_code_'+$grid_row+'" value="'+$obj['product_code']+'" readonly />';
    $html += '<input type="hidden" style="min-width: 300px;" class="form-control" name="stock_transfer_details['+$grid_row+'][product_id]" id="stock_transfer_detail_product_id_'+$grid_row+'" value="'+$obj['product_id']+'" readonly />';
    $html += '</td>';
    $html += '<td>';
    $html += '<input type="text" style="min-width: 300px;" class="form-control" name="stock_transfer_details['+$grid_row+'][product_name]" id="stock_transfer_detail_product_name_'+$grid_row+'" value="'+$obj['product_name']+'" readonly />';
    $html += '<input type="hidden" class="form-control" name="stock_transfer_details['+$grid_row+'][unit_id]" id="stock_transfer_detail_unit_id_'+$grid_row+'" value="'+$obj['base_unit_id']+'" />';
    $html += '</td>';
    $html += '<td>';
    $html += '<input type="text" style="min-width: 100px;" class="form-control" name="stock_transfer_details['+$grid_row+'][cubic_meter]" id="stock_transfer_detail_cubic_meter_'+$grid_row+'" value="'+$obj['cubic_meter']+'" readonly />';
    $html += '</td>';
    $html += '<td>';
    $html += '<input type="text" style="min-width: 100px;" class="form-control" name="stock_transfer_details['+$grid_row+'][cubic_feet]" id="stock_transfer_detail_cubic_feet_'+$grid_row+'" value="'+$obj['cubic_feet']+'" readonly />';
    $html += '</td>';
    $html += '<td>';
    $html += '<input onchange="calculateRowTotal(this);" type="text" class="form-control" name="stock_transfer_details['+$grid_row+'][qty]" id="stock_transfer_detail_qty_'+$grid_row+'" value="'+$obj['balance_qty']+'" />';
    $html += '</td>';
    $html += '<td>';
    $html += '<input type="text" style="min-width: 100px;" class="form-control" name="stock_transfer_details['+$grid_row+'][total_cubic_meter]" id="stock_transfer_detail_total_cubic_meter_'+$grid_row+'" value="'+$obj['balance_cubic_meter']+'" readonly />';
    $html += '</td>';
    $html += '<td>';
    $html += '<input type="text" style="min-width: 100px;" class="form-control" name="stock_transfer_details['+$grid_row+'][total_cubic_feet]" id="stock_transfer_detail_total_cubic_feet_'+$grid_row+'" value="'+$obj['balance_cubic_feet']+'" readonly />';
    $html += '</td>';
    $html += '<td>';
    $html += '<input type="text" class="form-control" name="stock_transfer_details['+$grid_row+'][cog_rate]" id="stock_transfer_detail_cog_rate_'+$grid_row+'" value="'+$obj['avg_cog_rate']+'" readonly />';
    $html += '</td>';
    $html += '<td>';
    $html += '<input type="text" class="form-control" name="stock_transfer_details['+$grid_row+'][cog_amount]" id="stock_transfer_detail_cog_amount_'+$grid_row+'" value="'+$obj['balance_amount']+'" readonly />';
    $html += '</td>';
    $html += '<td><a onclick="removeRow(this);" title="Remove" class="btn btn-xs btn-danger" href="javascript:void(0);"><i class="fa fa-times"></i></a></td>';
    $html += '</tr>';


    $('#tblStockTransferDetail tbody').append($html);
    $('#stock_transfer_detail_warehouse_id_'+$grid_row).select2({width: '100%'});
    $('#stock_transfer_detail_qty_'+$grid_row).trigger('change');
    $grid_row++;
}

function removeRow($obj) {
    //console.log($obj);
    var $row_id = $($obj).parent().parent().data('row_id');
    $('#grid_row_'+$row_id).remove();
    calculateTotal();
}

function calculateRowTotal($obj) {
    var $row_id = $($obj).parent().parent().data('row_id');

    var $cubic_meter = parseFloat($('#stock_transfer_detail_cubic_meter_' + $row_id).val()) || 0.00;
    var $cubic_feet = parseFloat($('#stock_transfer_detail_cubic_feet_' + $row_id).val()) || 0.00;
    var $qty = parseFloat($('#stock_transfer_detail_qty_' + $row_id).val()) || 0.00;
    var $rate = parseFloat($('#stock_transfer_detail_cog_rate_' + $row_id).val()) || 0.00;

    var $total_cubic_meter = $qty * $cubic_meter;
    var $total_cubic_feet = $qty * $cubic_feet;

    var $amount = roundUpto($total_cubic_feet * $rate,4);
    $amount = $amount || 0.00;

    $('#stock_transfer_detail_total_cubic_feet_' + $row_id).val(roundUpto($total_cubic_feet,4));
    $('#stock_transfer_detail_total_cubic_meter_' + $row_id).val(roundUpto($total_cubic_meter,4));
    $('#stock_transfer_detail_cog_amount_' + $row_id).val($amount);
    calculateTotal();
}

function calculateTotal() {
    var $total_qty = 0;
    var $total_cubic_meter = 0;
    var $total_cubic_feet = 0;
    var $total_amount = 0;
    $('#tblStockTransferDetail tbody tr').each(function() {
        $row_id = $(this).data('row_id');
        $qty = $('#stock_transfer_detail_qty_' + $row_id).val();
        $cubic_meter = $('#stock_transfer_detail_total_cubic_meter_' + $row_id).val();
        $cubic_feet = $('#stock_transfer_detail_total_cubic_feet_' + $row_id).val();
        $amount = $('#stock_transfer_detail_cog_amount_' + $row_id).val();

        $total_qty += parseFloat($qty);
        $total_cubic_meter += parseFloat($cubic_meter);
        $total_cubic_feet += parseFloat($cubic_feet);
        $total_amount += parseFloat($amount);
    })

    $('#total_qty').val(roundUpto($total_qty,2));
    $('#total_cubic_meter').val(roundUpto($total_cubic_meter,2));
    $('#total_cubic_feet').val(roundUpto($total_cubic_feet,2));
    $('#total_amount').val(roundUpto($total_amount,2));
}
