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

$(document).on('change','#partner_type_id', function() {
    $partner_type_id = $(this).val();
    $.ajax({
        url: $UrlGetPartner,
        dataType: 'json',
        type: 'post',
        data: 'partner_type_id=' + $partner_type_id+'&partner_id='+$partner_id,
        mimeType:"multipart/form-data",
        beforeSend: function() {
            $('#partner_id').before('<i id="loader" class="fa fa-refresh fa-spin"></i>');
        },
        complete: function() {
            $('#loader').remove();
        },
        success: function(json) {
            if(json.success)
            {
                $('#partner_id').select2('destroy');
                $('#partner_id').html(json.html);
                $('#partner_id').select2({width:'100%'});
            }
            else {
                alert(json.error);
            }
        },
        error: function(xhr, ajaxOptions, thrownError) {
            console.log(xhr.responseText);
        }
    })
});

$(document).on('change','#partner_id', function() {
    var $partner_type_id = $('#partner_type_id').val();
    var $partner_id = $('#partner_id').val();
    //var $ref_document_type_id = $(this).val();
    $.ajax({
        url: $UrlGetRefDocumentNo,
        dataType: 'json',
        type: 'post',
        //data: 'ref_document_type_id=' + $ref_document_type_id + '&partner_type_id=' + $partner_type_id + '&partner_id=' + $partner_id,
        data: 'partner_type_id=' + $partner_type_id + '&partner_id=' + $partner_id,
        mimeType:"multipart/form-data",
        beforeSend: function() {
            $('#ref_document_identity').before('<i id="loader" class="fa fa-refresh fa-spin"></i>');
        },
        complete: function() {
            $('#loader').remove();
        },
        success: function(json) {
            if(json.success)
            {
                // $('#ref_document_identity').select2('destroy');
                $('#ref_document_identity').html(json.html);
                $('#ref_document_identity').select2({width: '100%'});
            }
            else {
                alert(json.error);
            }
        },
        error: function(xhr, ajaxOptions, thrownError) {
            console.log(xhr.responseText);
        }
    })
});

$(document).on('change','#ref_document_identity', function() {
    var $partner_type_id = $('#partner_type_id').val();
    var $partner_id = $('#partner_id').val();
    var $ref_document_type_id = $('#ref_document_identity option:selected').data('ref_document_type_id');
    var $ref_document_identity = $('#ref_document_identity').val();
    $('#ref_document_type_id').val($ref_document_type_id);
    var $data = {
        partner_type_id : $partner_type_id,
        partner_id : $partner_id,
        ref_document_type_id : $ref_document_type_id,
        ref_document_identity : $ref_document_identity,
        //document_currency_id : $('#document_currency_id').val()
    };
    var $details = [];
    $.ajax({
        url: $UrlGetRefDocument,
        dataType: 'json',
        type: 'post',
        data: $data,
        mimeType:"multipart/form-data",
        beforeSend: function() {
            $('#ref_document_id').before('<i id="loader" class="fa fa-refresh fa-spin"></i>');
            $('#tblSaleReturn tbody').html('');
        },
        complete: function() {
            $('#loader').remove();
        },
        success: function(json) {
            if(json.success)
            {
                var $invoice = json['invoice'];
                $('#rate_type').val($invoice['rate_type']);
                $details = json['details'];
                for($i=0;$i<$details.length;$i++) {
                    fillGrid($details[$i]);
                }

                calculateTotal();
            }
            else {
                alert(json.error);
            }
        },
        error: function(xhr, ajaxOptions, thrownError) {
            console.log(xhr.responseText);
        }
    })
});

function fillGrid($obj) {
    var $total_cubic_feet = $obj['total_cubic_feet'];
    var $qty = $obj['qty'];
    var $avg_cubic_feet = parseFloat($total_cubic_feet/$qty).toFixed(8);

    $html = '';
    $html += '<tr id="grid_row_'+$grid_row+'" data-row_id="'+$grid_row+'">';
    $html += '<td><a onclick="removeRow(this);" title="Remove" class="btn btn-sm btn-danger" href="javascript:void(0);"><i class="fa fa-times"></i></a></td>';
    $html += '<td>';
    $html += '<input type="text" class="form-control" readonly name="sale_return_details['+$grid_row+'][manual_ref_no]" id="sale_return_detail_manual_ref_no_'+$grid_row+'" value="'+$obj['manual_ref_no']+'" />';
    $html += '</td>';
    $html += '<td>';
    $html += '<input type="text" class="form-control" readonly name="sale_return_details['+$grid_row+'][product_code]" id="sale_return_detail_product_code_'+$grid_row+'" value="'+$obj['product_code']+'" />';
    $html += '</td>';
    $html += '<td>';
    $html += '<input type="hidden" name="sale_return_details['+$grid_row+'][product_id]" id="sale_return_detail_product_id_'+$grid_row+'" value="'+$obj['product_id']+'" />';
    $html += '<input type="text" class="form-control" readonly name="sale_return_details['+$grid_row+'][product_name]" id="sale_return_detail_product_name_'+$grid_row+'" value="'+$obj['product_name']+'" />';
    $html += '</td>';
    $html += '<td>';
    $html += '<input type="text" class="form-control" name="sale_return_details['+$grid_row+'][container_no]" id="sale_return_detail_container_no_'+$grid_row+'" value="'+$obj['container_no']+'" />';
    $html += '</td>';
    $html += '<td>';
    $html += '<input type="text" class="form-control" name="sale_return_details['+$grid_row+'][batch_no]" id="sale_return_detail_batch_no_'+$grid_row+'" value="'+$obj['batch_no']+'" />';
    $html += '</td>';
    $html += '<td>';
    $html += '<input type="text" class="form-control fPInteger" onchange="updateCubicFeet(this);" name="sale_return_details['+$grid_row+'][qty]" id="sale_return_detail_qty_'+$grid_row+'" value="'+$obj['qty']+'" />';
    $html += '<input type="hidden" id="sale_return_detail_avg_cubic_feet_'+$grid_row+'" value="'+$avg_cubic_feet+'" />';
    $html += '</td>';
    $html += '<td>';
    $html += '<input type="text" class="form-control fPDecimal" onchange="calculateTotalCubicFeet(this);" name="sale_return_details['+$grid_row+'][total_cubic_meter]" id="sale_return_detail_total_cubic_meter_'+$grid_row+'" value="'+$obj['total_cubic_meter']+'" />';
    $html += '</td>';
    $html += '<td>';
    $html += '<input type="text" class="form-control fPDecimal" onchange="calculateTotalCubicMeter(this);" name="sale_return_details['+$grid_row+'][total_cubic_feet]" id="sale_return_detail_total_cubic_feet_'+$grid_row+'" value="'+$obj['total_cubic_feet']+'" />';
    $html += '</td>';
    $html += '<td>';
    $html += '<input type="text" class="form-control" readonly name="sale_return_details['+$grid_row+'][rate]" id="sale_return_detail_rate_'+$grid_row+'" value="'+$obj['rate']+'" />';
    $html += '<input type="hidden" name="sale_return_details['+$grid_row+'][cog_rate]" id="sale_return_detail_cog_rate_'+$grid_row+'" value="'+$obj['cog_rate']+'" />';
    $html += '</td>';
    $html += '<td>';
    $html += '<input type="hidden" name="sale_return_details['+$grid_row+'][cog_amount]" id="sale_return_detail_cog_amount_'+$grid_row+'" value="'+$obj['cog_amount']+'" />';
    $html += '<input type="text" class="form-control" readonly name="sale_return_details['+$grid_row+'][amount]" id="sale_return_detail_amount_'+$grid_row+'" value="'+$obj['amount']+'" />';
    $html += '</td>';
    $html += '<td>';
    $html += '<input type="text" class="form-control" name="sale_return_details['+$grid_row+'][remarks]" id="sale_return_detail_remarks_'+$grid_row+'" value="'+$obj['remarks']+'" />';
    $html += '</td>';
    $html += '</tr>';


    $('#tblSaleReturn tbody').prepend($html);
    $grid_row++;
}

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

function updateCubicFeet(obj) {
    var $row_id = $(obj).parent().parent().data('row_id');
    var $qty = $(obj).val();
    var $avg_cubic_feet = $('#sale_return_detail_avg_cubic_feet_'+$row_id).val();
    var $total_cubic_feet = ($avg_cubic_feet * $qty).toFixed(4);

    $('#sale_return_detail_total_cubic_feet_'+$row_id).val($total_cubic_feet).trigger('change');
}

function calculateTotalCubicFeet(obj) {
    var $row_id = $(obj).parent().parent().data('row_id');
    var $total_cubic_meter = parseFloat($(obj).val());
    var $total_cubic_feet = ($total_cubic_meter * 35.31467).toFixed(4);

    $('#sale_return_detail_total_cubic_feet_'+$row_id).val($total_cubic_feet);
    calculateAmount(obj);
}

function calculateTotalCubicMeter(obj) {
    var $row_id = $(obj).parent().parent().data('row_id');
    var $total_cubic_feet = parseFloat($(obj).val());
    var $total_cubic_meter = ($total_cubic_feet / 35.31467).toFixed(4);

    $('#sale_return_detail_total_cubic_meter_'+$row_id).val($total_cubic_meter);
    calculateAmount(obj);
}

function calculateAmount($obj) {
    var $rate_type =  $("#rate_type").val();
    var $row_id = $($obj).parent().parent().data('row_id');
    var $total_cubic_meter = parseFloat($('#sale_return_detail_total_cubic_meter_' + $row_id).val()) || 0.00;
    var $total_cubic_feet = parseFloat($('#sale_return_detail_total_cubic_feet_' + $row_id).val()) || 0.00;
    var $qty = parseFloat($('#sale_return_detail_qty_' + $row_id).val()) || 0.00;
    var $rate = parseFloat($('#sale_return_detail_rate_' + $row_id).val()) || 0.00;
    var $cog_rate = parseFloat($('#sale_return_detail_cog_rate_' + $row_id).val()) || 0.00;

    if($rate_type=='PCS') {
        var $amount = $qty * $rate;
    } else {
        var $amount = $total_cubic_feet * $rate;
    }
    var $cog_amount = $total_cubic_feet * $cog_rate;
    $amount = roundUpto($amount,2);
    $cog_amount = roundUpto($cog_amount,2);

    $('#sale_return_detail_amount_' + $row_id).val($amount);
    $('#sale_return_detail_cog_amount_' + $row_id).val($cog_amount);

    $('#sale_return_detail_discount_percent_' + $row_id).trigger('change');
    $('#sale_return_detail_tax_percent_' + $row_id).trigger('change');

    calculateTotal();
}


function calculateTotal() {
    var $total_quantity = 0;
    var $total_cubic_meter = 0;
    var $total_cubic_feet = 0;
    var $net_amount = 0;
    $('#tblSaleReturn tbody tr').each(function() {
        var $row_id = $(this).data('row_id');
        var $amount = $('#sale_return_detail_amount_' + $row_id).val();
        var $quantity = $('#sale_return_detail_qty_' + $row_id).val();
        var $cubic_meter = $('#sale_return_detail_total_cubic_meter_' + $row_id).val();
        var $cubic_feet = $('#sale_return_detail_total_cubic_feet_' + $row_id).val();

        $total_quantity += parseFloat($quantity);
        $total_cubic_meter += parseFloat($cubic_meter);
        $total_cubic_feet += parseFloat($cubic_feet);
        $net_amount += parseFloat($amount);
    })

    var $cash_returned = $('#cash_returned').val() || 0.00;
    var $balance_amount = $net_amount - $cash_returned;

    $('#total_quantity').val(roundUpto($total_quantity,2));
    $('#total_cubic_meter').val(roundUpto($total_cubic_meter,4));
    $('#total_cubic_feet').val(roundUpto($total_cubic_feet,4));
    $('#net_amount').val(roundUpto($net_amount,2));
    $('#cash_returned').val(roundUpto($cash_returned,2));
    $('#balance_amount').val(roundUpto($balance_amount,2));
}
