$(document).ready(function () { // NOSONAR
	inicializarDataTable();
	marcarChekboxes();

	$("#configuration_form.chilexpress_oficial #region_origen").on('change', function (ev) {
		actualizarComunaDesdeRegion($(ev.currentTarget), $("#configuration_form.chilexpress_oficial #comuna_origen"));
	});

	$("#configuration_form.chilexpress_oficial #region_devolucion").on('change', function (ev) {
		actualizarComunaDesdeRegion($(ev.currentTarget), $("#configuration_form.chilexpress_oficial #comuna_devolucion"));
	});


	if ($("body.adminaddresses #address_form #id_state").length) {
		let $city = $("body.adminaddresses #address_form #city");
		let $state = $("body.adminaddresses #address_form #id_state");
		$city.parent().siblings('label').text('Comuna'); // Esto podría ser una opción del Módulo
		$state.parent().siblings('label').text('Región'); // Esto podría ser una opción del Módulo

		let city_val = $city.val();
		let $city_parent = $city.parent('div');
		let $new_city = $('<select name="city" class="form-control form-control-select"><option value="' + city_val + '"  selected>Esperando que carguen las regiones...</select>')
		$city.remove();
		$city_parent.append($new_city);
		$city = $new_city;

		$state.on('change', function (ev) {
			updateCity();
		});

		// No hay forma de saber cuando cambiara el estado debido a que funciona via ajax
		// Y no tiene ningun callback, asi que solo nos queda esperar que cambie
		let stateWasUpdated = false;
		let initHTMLLength = $state.html().length;
		for (let i = 100; i < 8000; i += 100) {

			setTimeout(function () {
				if ($state.html().length !== initHTMLLength && !stateWasUpdated) {
					stateWasUpdated = true;
					updateCity();
				}
			}, i);
		}



		function updateCity() {

			let state_val = $state.val();
			city_val = $city.val();
			$city.html('<option value="" disabled="" selected="selected">Cargando...</selected>');
			$.ajax({
				type: 'POST',
				url: chilexpress_oficial_ajax_url.replace(/&amp;/gi, '&'),
				cache: false,
				dataType: 'json',
				data: {
					action: 'obtener_comunas_con_id',
					region: state_val,
					ajax: true
				},
				success: function (result) {
					let html = '';
					Object.keys(result.comunas).forEach(function (key) {
						html += '<option value="' + key + '" ' + ((key === city_val) ? 'selected="selected"' : '') + '>' + result.comunas[key] + '</option>';
					});
					if ($city) {
						$city.html(html);
					}
				}
			});
		}
	}

	/** Orders table **/
	const vdot1 = parseInt(_PS_VERSION_.split(".")[0]) || 1;
	const vdot2 = parseInt(_PS_VERSION_.split(".")[1]) || 1;
	const vdot3 = parseInt(_PS_VERSION_.split(".")[2]) || 1;
	const vdot4 = parseInt(_PS_VERSION_.split(".")[3]) || 1;
	const intVersion = ((vdot1 * 1000) + (vdot2 * 100) + (vdot3 * 10) + vdot4);
	if (intVersion >= 1773) {
		$('td.column-carrier_reference, td.column-tracking_number').each(function () {
			if ($(this).has('a').length === 0) {
				function decodeHtml(str) {
					let map =
					{
						'&amp;': '&',
						'&lt;': '<',
						'&gt;': '>',
						'&quot;': '"',
						'&#039;': "'"
					};
					return str.replace(/&amp;|&lt;|&gt;|&quot;|&#039;/g, function (m) {
						return map[m];
					});
				}
				$(this).html(decodeHtml($(this).text()));
			}
		});
	}

	if ($("a[data-tracking-code]").length) {
		$(document.body).append($("#trackingModal"));

		$(".with-tooltip").tooltip();
		setTimeout(function () {
			$(".with-tooltip").tooltip();
		}, 1000);
		$("a[data-tracking-code]").each(function (index, el) {

			$(el).on('click', function (ev) { // NOSONAR
				ev.preventDefault();
				let $el = $(ev.currentTarget);
				if ($el.text() === 'Cargando...') { return false; }
				let oldText = $el.text();
				$el.text('Cargando...');

				$.ajax({
					type: "post",
					url: chilexpress_oficial_ajax_url,
					dataType: 'json',
					data: {
						action: 'track_order',
						order_id: $el.data('orderid'),
						tracking_code: $el.data('tracking-code'),
						ajax: true
					},
					error: function (result) {
						$el.text(oldText);
						alert('Hubo un error al cargar la información de la Orden de Transporte');
					},
					success: function (result) {

						$el.text(oldText);
						let data = {};
						if (result.error) {
							alert(result.error);
							return;
						}
						if (result.response && result.response.data) {
							data = result.response;
						} else {
							data = result;
						}

						let dimensions = data.data.transportOrderData.dimensions.split("x");
						let dimension_1 = parseInt(dimensions[0]) * 100;
						let dimension_2 = parseInt(dimensions[1]) * 100;
						let dimension_3 = parseInt(dimensions[2]) * 100;

						let truncated_dimensions = "" + dimension_1 + "x" + dimension_2 + "x" + dimension_3;

						$("#trackingModal").modal('show');
						$("#trackingModal .orden_transporte").text(data.data.transportOrderData.transportOrderNumber);
						$("#trackingModal .producto").text(data.data.transportOrderData.product);
						$("#trackingModal .servicio").text(data.data.transportOrderData.service);
						$("#trackingModal .status").text(data.data.transportOrderData.status);

						$("#trackingModal .dimensiones").text(truncated_dimensions);
						$("#trackingModal .peso").text(data.data.transportOrderData.weight);

						$("#trackingModal .rut_receptor").text(data.data.deliveryData.receptorRut);
						$("#trackingModal .nombre_receptor").text(data.data.deliveryData.receptorName);
						$("#trackingModal .fecha_entrega").text(data.data.deliveryData.receptorDate);
						$("#trackingModal .hora_entrega").text(data.data.deliveryData.receptorHour);

						if (data.data.trackingEvents.length) {
							let html = '';
							$.each(data.data.trackingEvents, function (index, item) {
								html += '<tr><td align="center">' + item.eventDate + '</td><td align="center">' + item.eventHour.split('.')[0] + '</td><td align="center">' + item.description + '</td></tr>'
							});
							$("#wc-chilexpress-events > tbody").html(html);
						} else {
							$("#wc-chilexpress-events > tbody").html('<tr><td colspan="3" style="text-align:center;">No existen eventos aún para este envio.</td></tr><tr></tr>');
						}
					}
				});

				return false;
			})
		});
	}

	// Funcionalidades Seccion "Habilitar Regiones y Comunas"
	$(".container-regiones-comunas .nombre-region").click(function() {
		let regionId = $(this).attr('id');
		$(".hijo-" + regionId).slideToggle("slow");
	});

	$(".check-region").click(function() {
		let regionId = $(this).attr('id');
   		$('.check-comuna-' + regionId).not(this).prop('checked', this.checked);
 	});

 	$("#check_todo").click(function () {
     	$('.checkboxes').not(this).prop('checked', this.checked);
 	});


    $(".btn-asignar-dimension").click(function() {
		const product_id = $(this).data("product_id");
		const alto = $("#input_alto_" + product_id).val();
		const largo = $("#input_largo_" + product_id).val();
		const ancho = $("#input_ancho_" + product_id).val();
		const peso = $("#input_peso_" + product_id).val();
		let service_ampm = '';

		if ($("#input_servicio_ampm_" + product_id).prop('checked'))
			service_ampm = 'true';

		$.ajax({
			type: "post",
			url: chilexpress_oficial_ajax_url,
			dataType: 'json',
			data: "action=set_dimension&alto=" + alto + "&largo=" + largo + "&ancho=" + ancho + "&peso=" + peso + "&product_id=" + product_id + "&service_ampm=" + service_ampm, // NOSONAR
			success: function(data){
					
				if(data.status == 'success')
				{
					alert(data.response);
				}
				else
				{
					alert("Error: [" + data.response + "]");
				}
			},
			error : function(error){ 
				console.log(error) 
			}

		});
	});

	$(".numero-ce").click(function(e) {
		e.preventDefault();
 		let id_order = $(this).data("id_order");
 		let numero_ce = $(this).data("numero_ce");

 		$.ajax({
			type: "post",
			url: chilexpress_oficial_ajax_url,
			dataType: 'json',
			data: "action=close_certificate&id_order=" + id_order + "&numero_ce=" + numero_ce, // NOSONAR
			success: function(data){

				let obj = data.response;
					
				if(obj.closedCertificate)
				{
					let a = document.createElement("a");
					a.href = "data:application/pdf;base64," + obj.closedCertificate.imagePdf;
					a.download = "certificate_" + obj.closedCertificate.certificateNumber + ".pdf";
					a.click();
				}
				else
				{
					alert("Hubo un error inesperado.!");
				}
			},
			error : function(error){ 
				console.log(error) 
			}

		});

 	});

 	$('.check-comuna').click(function () {
    	let region_id = $(this).data("region_padre");
    	let marcado = true;
    	let contador = 0;

    	$(".check-comuna-" + region_id).each(function(){
       		if( $(this).prop('checked') === false ) 
	    		contador++;		
       	});
    			
    	if( contador == $(".check-comuna-" + region_id).length )
    		marcado = false;		

		$('#' + region_id).prop( "checked", marcado );
 	});


	 $("#input_porcentaje_descuento").on('input', function (evt) {
		// Allow only numbers.
		$(this).val($(this).val().replace(/[^0-9]/g, ''));

		if( parseInt($(this).val()) < 0 || parseInt($(this).val()) > 100 ){
			$(this).val('');
		}
	});


	function actualizarComunaDesdeRegion($region, $comuna) {
		let region = $region.val();
		$comuna.html('<option>CARGANDO...</option>')
		$.ajax({
			type: 'POST',
			url: chilexpress_oficial_ajax_url,
			cache: false,
			dataType: 'json',
			data: {
				action: 'obtener_comunas',
				region: region,
				ajax: true
			},
			success: function (result) {
				let html = '';
				Object.keys(result.comunas).forEach(function (key) {
					html += '<option value="' + key + '">' + result.comunas[key] + '</option>';
				})
				$comuna.html(html);
			}
		});
	}

	function inicializarDataTable(){
		//DataTable
		$('#tablaPedidosCxp').DataTable({
		    "pageLength": 10, // oculta el select para cambiar el numero de registros por pagina
		    "lengthChange": false,
			"order": [[1, 'desc']],
			"language": {
				url: 'https://cdn.datatables.net/plug-ins/1.12.1/i18n/es-ES.json'
			}
		    //"dom": '<"toolbar">frtip',
		});

		$('#tablaProductosCxp').DataTable({
		    "pageLength": 10, // oculta el select para cambiar el numero de registros por pagina
		    "lengthChange": false,
			"language": {
				url: 'https://cdn.datatables.net/plug-ins/1.12.1/i18n/es-ES.json'
			}
		});
	}

	function marcarChekboxes() {
		let sinMarcar = $("input:checkbox:not(:first)").not(':checked').length;
		if(sinMarcar == 0){
		 	$("#check_todo").prop( "checked", true );
		}
		else{
		 	$("#check_todo").prop( "checked", false );
		}
	}
});
