//DEVELOP
const PATH_GENERAL = 'http://localhost:7070/Asistencia/';
const PATH_IP = 'http://172.16.2.102:7070/Asistencia/';
//PRODUCCION
const PATH_DOMAIN = '';
const CODIGO_PROYECTO = '7';
//const PATH_SERVICIO_REST = 'http://172.16.2.53:8080/security-rest/api/'//'http://app8.sacooliveros.edu.pe:8080/security-rest/api/';
const PATH_SERVICIO_REST = 'http://app9.sacooliveros.edu.pe:8080/security-rest/api/';
//<editor-fold> SERVICIOS REST

const baseURLRest = 'http://sistem16:666/';

const ajaxWebService = axios.create({
	baseURL: baseURLRest
});
const ajaxModal = axios.create({
	baseURL: `http://localhost:7070/Asistencia/vistas/modals/`
});

//<editor-fold>
//<editor-fold> MODULO DE POLICIAS
const URI_TIPOROL_POLICIA = "tipoRolPolicias";
const URI_FRECUENCIA_ROL_POLICIA = "frecuenciaRolPolicias";
const URI_SEDES = "sedes";
const URI_ESTADO_ASISTENCIA = "estadoAsistencia";
const URI_POLICIAS = "policias";
const URI_ROL_POLICIA = "rolesPolicias";
const URI_POLICIAS_ASISTENCIA = "asistenciaPolicias";
const URI_POLICIA_MONTOS_AMANECIDAS = "montoAmanecidas";
const URI_POLICIA_CONCEPTOSEDES = "conceptoSedes";
const URI_POLICIA_REPORTE_MONTOS = "reporteMontosPolicias";
const URI_POLICIA_PROYECCION = "proyeccion";
const URI_POLICIA_PROYECTADO_COMPARATIVO = "proyectadoComparativo";
const URI_ADMINISTRATIVO_ASISTENCIA = "asistenciaAdministrativa";
const URI_TRABAJADORES = "trabajadores";
const URI_ADMINISTRATIVOS_TOLERANCIA_INDIVIDUAL = "toleranciasIndividuales";
const URI_ADMINISTRATIVOS_ESTADO_TOLERANCIA_INDIVIDUAL = "estadoTolerancias";
const URI_ADMINISTRATIVOS_VACACIONES_INDIVIDUAL = "vacacionesAdministrativasIndividuales";
const URI_CARGOS = "cargoLaboral";
//</editor-fold>


//</editor-fold>

swal.mixin({
	buttonsStyling: false,
	confirmButtonClass: 'btn btn-primary mr-5 ml-5',
	cancelButtonClass: 'btn btn-secondary mr-5 ml-5'
});

$.extend($.fn.dataTable.defaults, {
//	bSort: false,
	bFilter: false,
//	aaSorting: [],
	ordering: false,
	bLengthChange: false,
	bInfo: true,
//	paging: true,
	iDisplayLength: 20,
//	bStateSave: false,
//	autoWidth: false,
//	responsive: true,
//	stateSave: true,
	scrollX: true,
	responsive: true,
	language: {
		lengthMenu: "Mostrar: _MENU_",
		zeroRecords: "&nbsp;&nbsp;&nbsp; No se encontraron resultados",
		info: "&nbsp;&nbsp;&nbsp; Mostrando del _START_ al _END_ de un total de _TOTAL_ registros",
		infoEmpty: "&nbsp;&nbsp;&nbsp; Mostrando 0 de 0 registros",
		search: "Filtrar:",
		loadingRecords: "Cargando...",
		processing: '<span style="width:100%;"><img src="http://www.snacklocal.com/images/ajaxload.gif"></span>',
		paginate: {
			first: "First",
			last: "Last",
			next: "Siguiente",
			previous: "Anterior"
		}
	}
});

ajaxWebService.interceptors.response.use(function (response) {
	// Do something with response data
	let respuesta = {
		status: response.data.status || true,
		message: response.data.message || `Operación exitosa`,
		data: response.data.data || response.data
	};
//	console.log(respuesta, moment().format("YYYY/DD/MM HH:MM:SS s"))
	return respuesta;
}, function (error) {
	// Do something with response error
	return Promise.reject(error);
});


/*Ajax genral*/
const ajaxRequestSendBody = obj => {
	let body = JSON.stringify(obj.body);
	return new Promise((resolve, reject) => {
		$.ajax({
			url: obj.url,
			type: obj.type,
			headers: obj.headers,
			data: {body: body},
			beforeSend: (xhr, settings) => {
			}, success: (response, textStatus, jqXHR) => {
				resolve(response)
			}, error: (jqXHR, textStatus, errorThrown) => {
				reject({
					status: jqXHR.status,
					throw: errorThrown || {},
					jqXHR: jqXHR,
					request: obj
				})
			}
		})
	})
}
/*Ajax General*/
/*Ajax genral*/
const ajaxRequestGeneral = obj => {
	let body = JSON.stringify(obj.body);
	return new Promise((resolve, reject) => {
		$.ajax({
			url: obj.url,
			type: obj.type,
			headers: obj.headers,
			data: {body: body},
			beforeSend: (xhr, settings) => {
			}, success: (response, textStatus, jqXHR) => {
				resolve(response)
			}, error: (jqXHR, textStatus, errorThrown) => {
				reject({
					status: jqXHR.status,
					throw: errorThrown || {},
					jqXHR: jqXHR,
					request: obj
				})
			}
		})
	})
}
let createSelectOptions = (obj, valueName, textName) => {
	let options = ''
	obj.forEach((data) => {
		options += ` < option value = "${data[valueName]}" > ${data[textName]} < /option>`
	})
	return options
}

let customSwal = {
	alert(title, text, type) {
		let colors = {
			success: '#66BB6A',
			error: '#EF5350',
			warning: '#FF7043'
		}
		let btnColor = colors[type]
		return new Promise((resolve, reject) => {
			swal({
				title: title,
				text: text,
				confirmButtonColor: btnColor,
				type: type
			}, (isConfirm) => {
				resolve()
			})
		})
	}
}

/**
 * Get the closest matching element up the DOM tree.
 * @private
 * @param  {Element} elem     Starting element
 * @param  {String}  selector Selector to match against
 * @return {Boolean|Element}  Returns null if not match found
 */
let getClosest = (elem, selector) => {

// Element.matches() polyfill
	if (!Element.prototype.matches) {
		Element.prototype.matches =
			Element.prototype.matchesSelector ||
			Element.prototype.mozMatchesSelector ||
			Element.prototype.msMatchesSelector ||
			Element.prototype.oMatchesSelector ||
			Element.prototype.webkitMatchesSelector ||
			function (s) {
				var matches = (this.document || this.ownerDocument).querySelectorAll(s),
					i = matches.length
				while (--i >= 0 && matches.item(i) !== this) {
				}
				return i > -1
			}
	}
// Get closest match
	for (; elem && elem !== document; elem = elem.parentNode) {
		if (elem.matches(selector))
			return elem
	}
	return null
}
let block = () => {
	$.blockUI({
		message: '<i class="icon-spinner4 spinner"></i>',
		timeout: 2000, //unblock after 2 seconds
		overlayCSS: {
			backgroundColor: '#1b2024',
			opacity: 0.8,
			cursor: 'wait'
		},
		css: {
			border: 0,
			color: '#fff',
			padding: 0,
			backgroundColor: 'transparent'
		}
	});
}
//let logOut = () =>{
//    document.querySelector('#logOut').addEventListener('click', (e) => {
//        window.location.href = 'http://172.16.2.53:8080/proyecto-estandar/vistas/logout'
//    })
//}
//logOut();

//let logOut = () => {
//    $('.logOut').click(function () {
//        console.log("redireccionando")
//        window.location.href = CONSTANTES.PATH_IP + 'vistas/logout';
//    })
//}

let logOut = () => {
	document.querySelector('#logOut').addEventListener('click', (e) => {
		window.location.href = '../vistas/logout';
	});
};
function defaultConfigDatePicker() {
	$('.datepicker').datepicker({
		dateFormat: 'dd/mm/yy',
		showButtonPanel: true,
		changeMonth: true,
		changeYear: true,
		minDate: '-4Y',
		maxDate: '+1Y',
		inline: true
	});
	$.datepicker.regional['es'] = {
		closeText: 'Cerrar',
		prevText: '<Ant',
		nextText: 'Sig>',
		currentText: 'Hoy',
		monthNames: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Setiembre', 'Octubre', 'Noviembre', 'Diciembre'],
		monthNamesShort: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'],
		dayNames: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'],
		dayNamesShort: ['Dom', 'Lun', 'Mar', 'Mie', 'Jue', 'Vie', 'Sáb'],
		dayNamesMin: ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sá'],
		weekHeader: 'Sm',
		dateFormat: 'dd/mm/yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''
	};
	$.datepicker.setDefaults($.datepicker.regional['es']);
	;
}


//function defaultConfigDateRangePicker() {
//    $('.daterange-basic').daterangepicker({
//        applyClass: 'bg-slate-600',
////        "singleDatePicker": true,
//        cancelClass: 'btn-default',
////        showDropdowns: false,
////        timePicker: true,
////        opens: 'center',
////        singleDatePicker: true,
//        autoApply: true,
//        locale: {
//            format: 'DD/MM/YYYY'
//        }
//    });
////    $('.calendar.right').hide();
//}




(function (a) {
	a.fn.validCampo = function (b) {
		a(this).on({keypress: function (a) {
				var c = a.which, d = a.keyCode, e = String.fromCharCode(c).toLowerCase(), f = b;
				(-1 != f.indexOf(e) || 9 == d || 37 != c && 37 == d || 39 == d && 39 != c || 8 == d || 46 == d && 46 != c) && 161 != c || a.preventDefault()
			}})
	}
})(jQuery);
function primeraLetraMayuscula(str) {
	let strLower = str.toLowerCase();
	let caracter = strLower.substr(0, 1).toUpperCase();
	let cadena = caracter + strLower.substr(1);
	return cadena;
}



const makeDatatable = (
	wrapName = ``,
	forDatatable = {
	data: [],
		columns: [],
		footerFilter: false,
		footer: false
	},
	className = ``,
	) => {
	if (!wrapName) {
		return {
			message: `{wrapName} is empty`,
			status: false
		}
	}

	if (forDatatable.columns.length <= 0) {
		return {
			message: `{columns} is empty`,
			status: false
		}
	}

	let nameDatatable = `${wrapName}-datatable`;

	// table
	let table_head = `
		<table id="${nameDatatable}" class="table table-hover ${className}" cellspacing="0" width="100%">`;

	// headers
	let table_head_th = `
		<thead>
			<tr>`;
	forDatatable.columns.forEach((obj) => {
		let title = `undefined`;
		if (obj.title) {
			title = obj.title;
		} else if (obj.data) {
			title = obj.data;
		}
		table_head_th += `
			<th>${title}</th>`
	})
	table_head_th += `
			</tr>
		</thead>`

	// footers
	let table_foot_th = ``;
	if (forDatatable.footer) {
		table_foot_th = `
			<tfoot>
				<tr>`;
		forDatatable.columns.forEach((obj) => {
			let title = `undefined`;
			if (obj.title) {
				title = obj.title;
			} else if (obj.data) {
				title = obj.data;
			}
			table_foot_th += `
				<th>${title}</th>`
		})
		table_foot_th += `
				</tr>
			</tfoot>
		`
	}

	// table
	let table_foot = `</table>`

	$(`#${wrapName}`).empty().append(`${table_head}${table_head_th}${table_foot_th}${table_foot}`);

	if (forDatatable.footerFilter) {
		// Setup - add a text input to each footer cell
		$(`#${nameDatatable} tfoot th`).each(function () {
			var title = $(this).text();
			$(this).html(`<input type="text" class="form-control" placeholder="${title}" />`);
		});
	}

	$(`#${nameDatatable}`)
		.DataTable(forDatatable);

	if (forDatatable.footerFilter) {
		// DataTable
		let table = $(`#${nameDatatable}`).DataTable();

		// Apply the search
		table.columns().every(function () {
			var that = this;
			$('input', this.footer()).on('keyup change', function () {
				if (that.search() !== this.value) {
					that
						.search(this.value)
						.draw();
				}
			});
		});

		$(`#${wrapName} .dataTables_scrollBody`).appendTo(`#${wrapName} .dataTables_scroll`);
	}

	return Promise.resolve({
		datatable: $(`#${nameDatatable}`),
		container: $(`#${wrapName}`)
	});
}



const randomIntFromInterval = (minimum, maximum) => {
	return Math.round(Math.random() * (maximum - minimum) + minimum);
}

const cleanQueryParams = (params = {}) => {
	for (var key in params) {
		if (params.hasOwnProperty(key)) {
			if (!params[key]) {
				delete params[key];
			}
		}
	}

	return params;
}

let initDatePicker = (...selectorName) => {
	selectorName.forEach(id => {
		let options = {
			format: "dd/mm/yyyy",
			zIndexOffset: 3000,
			autoclose: true,
			language: "es",
			onSelect: function () {
//        $(this).valid();
			}
		}
		$(id).datepicker(options);
		$(id).datepicker('setDate', 'now');
	});

}

const initSelect2 = (nodeIdentifier, URI, {title, subtitle} = {}) => {
	console.log(2)
	$(`${nodeIdentifier}`).select2({
		containerCssClass: 'select-xs',
		ajax: {
			url: URI,
			dataType: `json`,
			delay: 1000,
			data: function (params) {
				return {
					q: params.term, // search term
					page: params.page
				};
			},
			processResults: function (data, params) {
				// parse the results into the format expected by Select2
				// since we are using custom formatting functions we do not need to
				// alter the remote JSON data, except to indicate that infinite
				// scrolling can be used
				params.page = params.page || 1;

				return {
					results: data,
					pagination: {
						more: (params.page * 30) < data.length
					}
				};
			},
			cache: true
		},
		placeholder: `Buscar`,
		allowClear: true,
		escapeMarkup: function (markup) {
			return markup;
		}, // let our custom formatter work
		minimumInputLength: 1,
		templateResult: formatRepo,
		templateSelection: formatRepoSelection
	});

	function formatRepo(repo) {
		if (repo.loading) {
			return repo.text;
		}

		var markup = `
			<div class='select2-result-repository clearfix'>
				<div class='select2-result-repository__title'>${repo[title]}</div>`;
		markup += `
				<div class='select2-result-repository__statistics'>
					<div class='select2-result-repository__forks'>${repo[subtitle]}</div>					
				</div>		
			</div>`

		return markup;
	}

	function formatRepoSelection(repo) {
		if (repo.id) {
			return repo[title];
		} else {
			return repo.text;
		}
}
}



const generarFechas = (desde, hasta) => {
	let reverseDesde = desde.split("/").reverse().join("/");
	let reverseHasta = hasta.split("/").reverse().join("/");
	desde = moment(reverseDesde);
	hasta = moment(reverseHasta);
	let diaActual = desde;

	let fechas = [];
	while (diaActual.isSameOrBefore(hasta)) {
		fechas.push(diaActual.format('DD/MM/YYYY'));
		diaActual.add(1, 'days');
	}
	return fechas;
}


