/**
 * 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%'});
                $('#partner_id').trigger('change');
            }
            else {
                alert(json.error);
            }
        },
        error: function(xhr, ajaxOptions, thrownError) {
            console.log(xhr.responseText);
        }
    })
});

$(document).on('change','#partner_id', function() {
    $partner_id = $(this).val();
    if($partner_id != '') {
        $html = '';
        $html += '<option value="">&nbsp;</option>';
//        if($ref_document_type_id==17) {
//            $html += '<option value="17" selected="true">'+$lang['goods_received']+'</option>';
//        } else {
//            $html += '<option value="17">'+$lang['goods_received']+'</option>';
//        }
        if($ref_document_type_id==1) {
            $html += '<option value="1" selected="true">'+$lang['purchase_invoice']+'</option>';
        } else {
            $html += '<option value="1">'+$lang['purchase_invoice']+'</option>';
        }

        $('#ref_document_type_id').select2('destroy');
        $('#ref_document_type_id').html($html);
        $('#ref_document_type_id').select2({width: '100%'});
        $('#ref_document_type_id').trigger('change');
    } else {
        $('#ref_document_type_id').select2('destroy');
        $('#ref_document_type_id').html('');
        $('#ref_document_type_id').select2({width: '100%'});
    }
    $('#ref_document_identity').select2('destroy');
    $('#ref_document_identity').html('<option value="">&nbsp;</option>');
    $('#ref_document_identity').select2({width: '100%'});

});

$(document).on('change','#ref_document_type_id', function() {
    var $data = {
        partner_type_id : $('#partner_type_id').val(),
        partner_id : $('#partner_id').val(),
        ref_document_type_id : $('#ref_document_type_id').val(),
        ref_document_identity : $ref_document_identity,
        document_currency_id : $('#document_currency_id').val()
    };
    $.ajax({
        url: $UrlGetRefDocumentNo,
        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>');
        },
        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 $data = {
        partner_type_id : $('#partner_type_id').val(),
        partner_id : $('#partner_id').val(),
        ref_document_type_id : $('#ref_document_type_id').val(),
        ref_document_identity : $('#ref_document_identity').val(),
        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>');
            $('#tblPurchaseReturn').find('tbody').html('');
            $grid_rw = 0;
        },
        complete: function() {
            $('#loader').remove();
        },
        success: function(json) {
            if(json.success)
            {
                console.log(json);
                let $details = json['details'];
                let $document = json['document'];
                $('#rate_type').val($document.rate_type);
                $('#total_quantity').val($document.total_quantity);
                $('#total_cubic_meter').val($document.total_cubic_meter);
                $('#total_cubic_feet').val($document.total_cubic_feet);
                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) {
    console.log($obj);
    $html = '';
    $html += '<tr id="grid_row_'+$grid_row+'" data-row_id="'+$grid_row+'">';
    $html += '<td>';
    $html += '<input type="hidden" name="purchase_return_details['+$grid_row+'][ref_document_type_id]" id="purchase_return_detail_ref_document_type_id_'+$grid_row+'" value="'+$obj['document_type_id']+'" />';
    $html += '<input type="hidden" name="purchase_return_details['+$grid_row+'][ref_document_identity]" id="purchase_return_detail_ref_document_identity_'+$grid_row+'" value="'+$obj['document_identity']+'" />';
    $html += '<a target="_blank" href="'+$obj['href']+'">'+$obj['document_identity']+'</a>';
    $html += '</td>';
    $html += '<td>';
    $html += '<input type="hidden" name="purchase_return_details['+$grid_row+'][warehouse_id]" id="purchase_return_detail_warehouse_id_'+$grid_row+'" value="'+$obj['warehouse_id']+'" />';
    $html += '<input type="text" class="form-control" name="purchase_return_details['+$grid_row+'][warehouse]" id="purchase_return_detail_warehouse_'+$grid_row+'" value="'+$obj['warehouse']+'" readonly/>';
    $html += '</td>';
    $html += '<td>';
    $html += '<input type="text" class="form-control" style="min-width: 100px;" class="form-control" name="purchase_return_details['+$grid_row+'][product_code]" id="purchase_return_detail_product_code_'+$grid_row+'" value="'+$obj['product_code']+'" readonly/>';
    $html += '</td>';
    $html += '<td>';
    $html += '<input type="hidden" name="purchase_return_details['+$grid_row+'][product_id]" id="purchase_return_detail_product_id_'+$grid_row+'" value="'+$obj['product_id']+'" />';
    $html += '<input type="text" class="form-control" name="purchase_return_details['+$grid_row+'][product_name]" id="purchase_return_detail_product_name_'+$grid_row+'" value="'+$obj['product_name']+'" readonly/>';
    $html += '<td>';
    $html += '<input style="min-width: 100px;" type="text" class="form-control fPDecimal" name="purchase_return_details['+$grid_row+'][container_no]" id="purchase_return_detail_container_no_'+$grid_row+'" value="'+$obj['container_no']+'" readonly/>';
    $html += '</td>';
    $html += '<td>';
    $html += '<input style="min-width: 100px;" type="text" class="form-control fPDecimal" name="purchase_return_details['+$grid_row+'][batch_no]" id="purchase_return_detail_batch_no_'+$grid_row+'" value="'+$obj['batch_no']+'" readonly/>';
    $html += '</td>';
    $html += '<td>';
    $html += '<input type="hidden" class="form-control" id="purchase_return_detail_unit_id_'+$grid_row+'" name="purchase_return_details['+$grid_row+'][unit_id]" value="'+$obj['unit_id']+'" />';
    $html += '<input onchange="calculateAmount(this);" style="min-width: 100px;" type="text" class="form-control fPDecimal" name="purchase_return_details['+$grid_row+'][qty]" id="purchase_return_detail_qty_'+$grid_row+'" value="'+$obj['qty']+'" />';
    $html += '</td>';
    $html += '<td>';
    $html += '<input onchange="calculateTotalCubicFeet(this);" style="min-width: 100px;" type="text" class="form-control fPDecimal" name="purchase_return_details['+$grid_row+'][total_cubic_meter]" id="purchase_return_detail_total_cubic_meter_'+$grid_row+'" value="'+$obj['total_cubic_meter']+'"/>';
    $html += '</td>';
    $html += '<td>';
    $html += '<input onchange="calculateTotalCubicMeter(this);" style="min-width: 100px;" type="text" class="form-control fPDecimal" name="purchase_return_details['+$grid_row+'][total_cubic_feet]" id="purchase_return_detail_total_cubic_feet_'+$grid_row+'" value="'+$obj['total_cubic_feet']+'"/>';
    $html += '</td>';
    $html += '<td>';
    $html += '<input style="min-width: 100px;" onchange="calculateAmount(this);" type="text" class="form-control fPDecimal" name="purchase_return_details['+$grid_row+'][rate]" id="purchase_return_detail_rate_'+$grid_row+'" value="'+$obj['rate']+'" readonly/>';
    $html += '</td>';
    $html += '<td>';
    $html += '<input type="text" style="min-width: 100px;" class="form-control fPDecimal" name="purchase_return_details['+$grid_row+'][amount]" id="purchase_return_detail_amount_'+$grid_row+'" value="'+$obj['amount']+'" readonly="true" />';
    $html += '</td>';
    $html += '<td>';
    $html += '<input type="text" style="min-width: 100px;" class="form-control fPDecimal" name="purchase_return_details['+$grid_row+'][remarks]" id="purchase_return_detail_remarks_'+$grid_row+'" value="" />';
    $html += '</td>';
    $html += '</tr>';


    $('#tblPurchaseReturn tbody').prepend($html);

    calculateAmount($obj);
    $grid_row++;
}

function calculateAmount($obj) {
    var $rate_type =  $("input[name='rate_type']:checked"). val();
    var $row_id = $($obj).parent().parent().data('row_id');
    // alert($rate_type);
    var $total_cubic_meter = parseFloat($('#purchase_return_detail_total_cubic_meter_' + $row_id).val()) || 0.00;
    var $total_cubic_feet = parseFloat($('#purchase_return_detail_total_cubic_feet_' + $row_id).val()) || 0.00;
    var $qty = parseFloat($('#purchase_return_detail_qty_' + $row_id).val()) || 0.00;
    var $rate = parseFloat($('#purchase_return_detail_rate_' + $row_id).val()) || 0.00;
    if($rate_type=='PCS') {
        var $amount = $qty * $rate;
    } else {
        var $amount = $total_cubic_feet * $rate;
    }
    $amount = roundUpto($amount,2);
    $('#purchase_return_detail_amount_' + $row_id).val($amount.toFixed(0));
    calculateTotal();
}

function calculateTotal() {
    var $item_amount = 0;
    var $item_total = 0;
    var $total_quantity = 0;
    var $total_cubic_meter = 0;
    var $total_cubic_feet = 0;
    $('#tblPurchaseReturn tbody tr').each(function() {
        var $row_id = $(this).data('row_id');
        var $amount = $('#purchase_return_detail_amount_' + $row_id).val();
        var $total_amount = $('#purchase_return_detail_total_amount_' + $row_id).val();
        var $quantity = $('#purchase_return_detail_qty_' + $row_id).val();
        var $cubic_meter = $('#purchase_return_detail_total_cubic_meter_' + $row_id).val();
        var $cubic_feet = $('#purchase_return_detail_total_cubic_feet_' + $row_id).val();

        $item_amount = (parseFloat($item_amount) + parseFloat($amount)).toFixed(2);
        $item_total += parseFloat($total_amount);
        $total_quantity += parseFloat($quantity);
        $total_cubic_meter += parseFloat($cubic_meter);
        $total_cubic_feet += parseFloat($cubic_feet);
    });
    $('#total_quantity').val(roundUpto($total_quantity,0));
    $('#total_cubic_meter').val(roundUpto($total_cubic_meter,4));
    //$('#total_cubic_feet').val(roundUpto($total_cubic_meter * 35.3147,4));
    $('#total_cubic_feet').val(roundUpto($total_cubic_feet,4));
    var $net_amount = parseFloat($item_total);
    //console.log($discount_amount, $labour_charges, $misc_charges, $net_amount, $cash_received, $balance_amount);
    $('#item_amount').val(roundUpto($item_amount,2));
    $('#item_total').val(roundUpto($item_total,2));
    $('#net_amount').val(roundUpto($net_amount,2));
}

function calculateTotalCubicFeet($obj) {
    var $rate_type =  $("input[name='rate_type']:checked"). val();
    var $row_id = $($obj).parent().parent().data('row_id');
    var $total_cubic_meter = parseFloat($('#purchase_return_detail_total_cubic_meter_' + $row_id).val() || 0.0000000);
    if($rate_type=='LOG') {
        var $total_cubic_feet = parseFloat($total_cubic_meter*27.750).toFixed(4);
    }
    else
    {
        var $total_cubic_feet = parseFloat($total_cubic_meter*35.3147).toFixed(4);
    }
    $('#purchase_return_detail_total_cubic_feet_' + $row_id).val($total_cubic_feet);
    calculateRowTotal($obj);
    calculateAmount($obj);
}

function calculateTotalCubicMeter($obj) {
    var $rate_type =  $("input[name='rate_type']:checked"). val();
    var $row_id = $($obj).parent().parent().data('row_id');
    var $total_cubic_feet = parseFloat($('#purchase_return_detail_total_cubic_feet_' + $row_id).val() || 0.0000000);
    if($rate_type=='LOG') {
        var $total_cubic_meter = parseFloat($total_cubic_feet/27.750).toFixed(4);
    } else {
        var $total_cubic_meter = parseFloat($total_cubic_feet/35.3147).toFixed(4);
    }
    var $total_cubic_meter = parseFloat($total_cubic_feet/35.3147).toFixed(4);
    $('#purchase_return_detail_total_cubic_meter_' + $row_id).val($total_cubic_meter);
    calculateRowTotal($obj);
    calculateAmount($obj);
}

function calculateRowTotal($obj) {
    var $row_id = $($obj).parent().parent().data('row_id');
    var $amount = parseFloat($('#purchase_return_detail_amount_' + $row_id).val());
    var $gross_amount = roundUpto($amount,2);
    var $total_amount = roundUpto($gross_amount,2);
    $('#purchase_return_detail_gross_amount_' + $row_id).val($gross_amount.toFixed(0));
    $('#purchase_return_detail_total_amount_' + $row_id).val($total_amount.toFixed(0));
    calculateTotal();
    calculateAmount($obj);
}
