var $table;

$("document").ready(function () {
    $("#linkReportes").addClass("subdrop");
	$table = $('#tablaDatos');
	inicialiaValores();
	consultar();

});


function ventanaFiltro(){
	$("#popuFiltro").modal("show");	
}

function consultar(){
	
	var pFechaInicio = $("#txtFechaInicio").val();
	var pFechaFin = $("#txtFechaFin").val();
	var pNidCliente = $("#ddlCliente").val();
      
	var json_request = {
		tipoOperacion: "reporteAduana"            
		,pFechaInicio:pFechaInicio
		,pFechaFin:pFechaFin
		,pNidCliente:pNidCliente
	};
	
	$.ajax({
		type: "POST",
		data: json_request,
		url: "../facturacion/dataAccess/reportes.php",
		dataType: "json",
		async: true,
		beforeSend: function () {
			ajaxindicatorstart();
		},
		success: function (resp) {             
					
			$table.DataTable().clear().draw();
			$table.dataTable().fnDestroy();
			$table.DataTable({
				data: resp.datos,
				dom: 'Bfrtip',
				searching:false,
				paging:false,
				buttons: [
					'excel', 'print'
				],			
				columns: [
					{ "data": "folioFactura","width": "10%"},
					{ "data": "folioServicio","width": "10%"},
					{ "data": "cliente","width": "30%"},
					{ "data": "fechaServicio" },
					{
                        "data": "importe",
						"width": "20%",
                        "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                            $(nTd).html("<span class='spanMoney'>" + currencyFormat(parseFloat(sData)) + "</span>");
                        }
                    },
                    {
                        "data": "contra_prestacion",
						"width": "20%",
                        "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                            $(nTd).html("<span class='spanMoney'>" + currencyFormat(parseFloat(sData)) + "</span>");
                        }
                    },
					{ "data": "agenteAduanal" },
					{ "data": "observaciones" }
				]
			});		
		},
		complete: function () {
			ajaxindicatorstop();
			$("#popuFiltro").modal("hide");	
		},
		error: function (xhr, ajaxOptions, thrownError) {
			console.log(xhr);
			console.log(ajaxOptions);
			console.log(thrownError);
		}
	});
}


function inicialiaValores(){
		
	$("#btnFiltro").click(function(){ ventanaFiltro(); });
	$("#btnConsultar").click(function(){ consultar(); });

	var today = new Date();

    var newdate = new Date();
    newdate.setDate(today.getDate() - 30);

    var ddA = newdate.getDate();
    var mmA = newdate.getMonth() + 1; //January is 0! 
    var yyyyA = newdate.getFullYear();


    var findate = new Date();
    findate.setDate(today.getDate());

    var dd = findate.getDate();
    var mm = findate.getMonth() + 1; //January is 0! 
    var yyyy = findate.getFullYear();
			
	//Iniciamos Fechas
	$('input[id$=txtFechaInicio]').datetimepicker({
        format: 'd/m/Y',
        lang: 'es',
        mask: true,
        timepicker: false
    });
	
		//Iniciamos Fechas
	$('input[id$=txtFechaFin]').datetimepicker({
        format: 'd/m/Y',
        lang: 'es',
        mask: true,
        timepicker: false
    });

	
    $("#txtFechaInicio").val(ddA + '/' + mmA + '/' + yyyyA);
    $("#txtFechaFin").val(dd + '/' + mm + '/' + yyyy);

	consultaClientes();
}



function consultaClientes(){

	var pNidSistema = "2";

    $('#ddlCliente').empty();
	var json_request = {
		tipoOperacion: "consultaClientes"            
		,pSistema:pNidSistema
	};

	$("#ddlCliente").append('<option value="-1">- TODOS -</option>');
	
	$.ajax({
		type: "POST",
		data: json_request,
		url: "../facturacion/dataAccess/notasCredito.php",
		dataType: "json",
		async: true,
		success: function (resp) {		
			console.log(resp);
			for (var i = 0; i < resp.datos.length; i++) {
				var json = resp.datos[i];					
				$("#ddlCliente").append('<option value="'+ json.rfc +'">'+ json.razonsocial +'</option>'); 
			}			
		}
	});
}


function currencyFormat(num) {
	return '$' + num.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
  }