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

$(document).on('change','#partner_id', function() {
    /*
    $partner_id = $(this).val();
    var $documents = $partners[$partner_id]['documents'];
    $html = '<option data-document_amount="0" data-amount="0" data-document_type_id="0" value="">&nbsp;</option>';
    $.each($documents, function (index, $document) {
        if($document['credit_amount'] > 0) {
            $html += '<option data-document_amount="'+$document['document_amount']+'" data-amount="'+$document['outstanding_amount']+'" data-document_type_id="'+$document['ref_document_type_id']+'" value="'+$document['ref_document_identity']+'">'+$document['ref_document_identity']+'</option>';
        }
    })

    $('#ref_document_identity').select2('destroy');
    $('#ref_document_identity').html($html);
    $('#ref_document_identity').select2({width: '100%'});
    */
    var $partner_type_id = $('#partner_type_id').val();
    var $partner_id = $(this).val();
    $.ajax({
        url: $UrlGetDocuments,
        dataType: 'json',
        type: 'post',
        data: 'partner_type_id=' + $partner_type_id+'&partner_id='+$partner_id,
        mimeType:"multipart/form-data",
        beforeSend: function() {
            $('#DivDocumentSettlementDetail').after('<i id="loader" class="fa fa-refresh fa-spin"></i>');
        },
        complete: function() {
            $('#loader').remove();
        },
        success: function(json) {
            if(json.success)
            {
                //$partners = json.partners;
                $documents = json.documents;
                $partner_coas = json.partner_coas;

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


$(document).on('click','#btnAddGrid', function() {
    var $partner_type_id = $('#partner_type_id').val();
    var $partner_id = $('#partner_id').val();
    var $accounts = [];
//    if($partner_type_id != '' && $partner_id != '') {
//        $accounts = $partner_coas;
//    } else {
        $accounts = $coas;
//    }
    var $DocumentsIdentity =[];
    $DocumentsIdentity = $documents;

    $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><a id="btnAddGrid" title="Add" class="btn btn-xs btn-primary" href="javascript:void(0);"><i class="fa fa-plus"></i></a></td>';
    $html += '<td style="width: 200px;">';
    $html += '<select class="form-control select2" onchange="GetDocumentData(this);" id="document_settlement_detail_ref_document_identity_'+$grid_row+'" name="document_settlement_details['+$grid_row+'][ref_document_identity]"> ';
    $html += '<option value="">&nbsp;</option>';
    $.each($DocumentsIdentity, function (index, $document) {
        $html += '<option value="'+$document['ref_document_identity']+'">'+$document['ref_document_identity']+'</option>';
    })
    $html += '</select>';
    $html += '</td>'
    $html += '<td style="width: 200px;">';
    $html += '<select class="form-control select2" id="document_settlement_detail_coa_id_'+$grid_row+'" name="document_settlement_details['+$grid_row+'][coa_id]">';
    $.each($accounts, function (index, $account) {

        $html += '<option value="'+$account['coa_id']+'">'+$account['display_name']+'</option>';
    })
    $html += '</select>';
    $html += '</td>'
    $html += '<td>';
    $html += '<input type="text" class="form-control fDecimal" name="document_settlement_details['+$grid_row+'][document_amount]" id="document_settlement_detail_document_amount_'+$grid_row+'" value="0.00" readonly="true"/>';
    $html += '<input type="hidden" class="form-control " name="document_settlement_details['+$grid_row+'][ref_document_type_id]" id="document_settlement_detail_ref_document_type_id_'+$grid_row+'" value="" readonly="true"/>';
    $html += '</td>'
    $html += '<td>';
    $html += '<input type="text" class="form-control fDecimal" name="document_settlement_details['+$grid_row+'][balance_amount]" id="document_settlement_detail_balance_amount_'+$grid_row+'" value="0.00" readonly="true"/>';
    $html += '</td>'
    $html += '<td>';
    $html += '<input  type="text" onchange="calculateTotal();" class="form-control fDecimal" name="document_settlement_details['+$grid_row+'][debit]" id="document_settlement_detail_debit_'+$grid_row+'" value="0.00" />';
    $html += '</td>'
    $html += '<td>';
    $html += '<input  type="text" onchange="calculateTotal();" class="form-control fDecimal" name="document_settlement_details['+$grid_row+'][credit]" id="document_settlement_detail_credit_'+$grid_row+'" value="0.00" />';
    $html += '</td>'
    $html += '<td>';
    $html += '<input type="text"  class="form-control" name="document_settlement_details['+$grid_row+'][remarks]" id="document_settlement_detail_remarks_'+$grid_row+'" value="" />';
    $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><a id="btnAddGrid" title="Add" class="btn btn-xs btn-primary" href="javascript:void(0);"><i class="fa fa-plus"></i></a></td>';
    $html += '</tr>';


    $('#tblDocumentSettlementDetail tbody').append($html);
    //$('#document_settlement_detail_ref_document_identity_'+$grid_row).select2({width: '100%'});
    //$('#document_settlement_detail_coa_id_'+$grid_row).select2({width: '100%'});
    setFieldFormat();
    $grid_row++;
});

function setDocumentInfo($obj) {
    var $row_id = $($obj).parent().parent().data('row_id');
    var $data = $($obj).find(':selected').data();

    $('#document_settlement_detail_ref_document_type_id_' + $row_id).val($data['ref_document_type_id']);
    $('#document_settlement_detail_document_amount_' + $row_id).val($data['document_amount']);
    $('#document_settlement_detail_amount_' + $row_id).val($data['amount']);
    $('#document_settlement_detail_net_amount_' + $row_id).val($data['amount']);

    calculateTotal();
}

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

function GetDocumentData($obj) {

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

    var $RefDocumentIdentity = $('#document_settlement_detail_ref_document_identity_' + $row_id).val();


    var $RefDocuments =  $documents[$RefDocumentIdentity];
    console.log($row_id,$RefDocumentIdentity,$RefDocuments);

    $('#document_settlement_detail_coa_id_' + $row_id).val($RefDocuments['coa_id']).trigger('change');
    $('#document_settlement_detail_ref_document_type_id_' + $row_id).val($RefDocuments['ref_document_type_id']);
    $('#document_settlement_detail_document_amount_' + $row_id).val($RefDocuments['document_amount']);
    $('#document_settlement_detail_balance_amount_' + $row_id).val($RefDocuments['outstanding_amount']);
    $('#document_settlement_detail_debit_' + $row_id).val($RefDocuments['credit_amount']);
    $('#document_settlement_detail_credit_' + $row_id).val($RefDocuments['debit_amount']);

//    $('#bank_payment_detail_net_amount_' + $row_id).val(roundUpto($net_amount,2));

    calculateTotal();
}

function calculateTotal() {

    var $total_debit = 0;
    var $total_credit = 0;

    $('#tblDocumentSettlementDetail tbody tr').each(function() {
        $row_id = $(this).data('row_id');
        var $debit = $('#document_settlement_detail_debit_' + $row_id).val() || 0.00;
        var $credit = $('#document_settlement_detail_credit_' + $row_id).val() || 0.00;

        $total_debit += parseFloat($debit);
        $total_credit += parseFloat($credit);
    })

    $('#total_debit').val(roundUpto($total_debit,2));
    $('#total_credit').val(roundUpto($total_credit,2));

}

