$(document).ready(function() { let map; let marker; let infoWindow; $('.mk-select-options').removeClass('openOptions'); // Abrir el modal de dirección de entrega $('#delivery-button-open').on('click', function() { $('#delivery').fadeIn(100); }); // Cerrar el modal de dirección de entrega $('.delivery-button-return, .delivery_close').on('click', function() { $('#delivery').fadeOut(300); $('#overlay').fadeOut(300); }); // Mostrar el modal de confirmación de dirección $('#confirm-button-open').on('click', function() { $('#confirm__method__delivery').fadeIn(300); }); // Cerrar el modal de confirmación de dirección $('.delivery__button__gotochange, .delivery__button__gotocart, .delivery_close').on('click', function() { $('#confirm__method__delivery').fadeOut(300); }); // $("body").off('click', "#mk-address-delivery").on('click', "#mk-address-delivery", function (e) { // $('#delivery').off('click', ".delivery-button-confirm").on('click', ".delivery-button-confirm", function (e) { $(document).on("click", ".autocomplete-list li", function() { let coverage = $(this).data("coverage"); Object.keys(coverage).forEach(key => { let item = coverage[key]; console.log('item',item); console.log('item.dispatch_address',item.dispatch_address); $('#city_address_dispatch').val(item.dispatch_address); $('#city_dispatch_latitude').val(item.latitude); $('#city_dispatch_longitude').val(item.longitude); console.log('item.city_id',item.city_id); console.log('item.latitude',item.latitude); console.log('item.longitude',item.longitude); }); }); $(".delivery-button-confirm").on('click', function (e) { e.preventDefault(); // Validar si Google Autocomplete está activo var cityName = $('#selected_city_name').val(); var city = $('#selected_city_id').val(); var latitude = $('#latitude').val(); var longitude = $('#longitude').val(); var addressformat = $('#address-format').val(); var address = $('#address').val(); var city_address_dispatch = $('#city_address_dispatch').val(); var city_dispatch_latitude = $('#city_dispatch_latitude').val(); var city_dispatch_longitude = $('#city_dispatch_longitude').val(); // Si Google Autocomplete NO está presente, tomamos los datos manuales if (!isGoogleAutocomplete) { var via = $('#selected_via').val(); var number1 = $('#delivery-number').val(); var number2 = $('#delivery-number-two').val(); var number3 = $('#delivery-number-three').val(); if (!city || !via || !number1 || !number2 || !number3){ console.log('entro validacion de direccion'); showError(); return false; } address = `${via} ${number1} # ${number2} - ${number3}`; addressformat = address; } const params = { latitude: latitude, longitude: longitude, addressformat: addressformat, address: address, cityName: cityName, cityId: city, cityAddressDispatch: city_address_dispatch, cityDispatchLatitude: city_dispatch_latitude, cityDispatchLongitude: city_dispatch_longitude }; // Validación para que no envíe campos vacíos if (!params.cityId || !params.address) { showError(); return false; } // Envío de la solicitud AJAX $.ajax({ url: default_url + '/delivery/update-address', type: 'POST', contentType: 'application/json', data: JSON.stringify(params), beforeSend: function() { $('.mk-delivery-loader').show(); }, success: function(response) { if (response.success) { let address = `${response.location.city_name} ${response.location.address}`.replace(/\b\w/g, char => char.toUpperCase()); let city = response.location.city_name; let checkout = response.location.address; $(".mk-address-text").text(address); $(".checkout_adress_update").text(city); $(".checkout_shipment_update").text(checkout); toastr.success('Tu dirección ha sido actualizada correctamente.', 'Dirección Actualizada', { closeButton: true, progressBar: true, positionClass: "toast-top-right", timeOut: 2000 }); let currentUrl = window.location.href; // console.log('currentUrl',currentUrl); if (currentUrl.includes("cart")) { window.livewire.emit("renderCart"); } else if (currentUrl.includes("checkout")) { let cart = response.cart; let matrix = response.companyMatrix if(cart ){ $(".header__cart__price").text("$" + cart.cartTotal); $("#checkout__order__subtotal span").text("$" + cart.cartSubtotal); $("#checkout__order__discount span").text("$" + cart.cartDiscount); $("#checkout__order__shipment span").text("$" + cart.cartDelivery); $(".checkout__order__total span").text("$" + cart.cartTotal); } } else { window.livewire.emit("renderShopCart"); } if(response.companyMatrix){ window.location.reload(); } } else { let message = "Hubo un problema al actualizar la dirección."; if(response.message){ message = response.message } Swal.fire({ title: 'Oops', text: message, icon: 'error', confirmButtonText: 'OK' }); } }, error: function(xhr) { Swal.fire({ title: 'Error', text: 'Ocurrió un error al procesar tu solicitud.', icon: 'error', confirmButtonText: 'OK' }); }, complete: function() { $('.mk-delivery-loader').hide(); $('#delivery').fadeOut(300); $('#overlay').fadeOut(300); } }); }); // Mostrar o ocultar ciudades $(document).ready(function () { $('.select-delivery-city').on('click', function(event){ $('.autocomplete-list').toggle(); event.stopPropagation(); // Evita que el evento se propague al document }); // Evento en document para ocultar si se hace clic fuera de .select-delivery-city o .autocomplete-list $(document).on('click', function(event) { if (!$(event.target).closest('.select-delivery-city, .autocomplete-list').length) { $('.autocomplete-list').hide(); } }); }); $('#city, #via').on('click', function() { $(this).siblings('.mk-select-options').toggleClass('openOptions'); }); $('.mk-select-options ul li').on('click', function() { var $parent = $(this).closest('.mk-select'); var selectedValue = $(this).data('id') || $(this).data('value'); var selectedText = $(this).text(); $parent.find('.selected-city-display, .selected-via-display').text(selectedText); $parent.find('input[type="hidden"]').val(selectedValue); $(this).closest('.mk-select-options').removeClass('openOptions'); }); $(document).on('click', function(event) { if (!$(event.target).closest('.mk-select').length) { $('.mk-select-options').removeClass('openOptions'); } }); $('.mk-select-options li').on('click', function() { var selectedValue = $(this).data('id') || $(this).data('value'); if ($(this).parent().is('#via-options')) { $('#selected_via').val(selectedValue); $('#via .selected-via-display').text($(this).text()); } else { $('#selected_city_id').val(selectedValue); $('#city .selected-city-display').text($(this).text()); $('#selected_city_name').val($(this).data('name')); } }); $("body").on('click', ".delivery__button__gotocart", function (e){ e.preventDefault(); console.log("delivery__button__gotocart",$(".address").text()); window.location.href = default_url+'/cart'; }); $("body").on('click', ".delivery__button__gotochange", function (e){ e.preventDefault(); $('#delivery').fadeIn(300); $('#confirm__method__delivery').fadeOut(300); return false; }); $("body").on('click', ".delivery-button-return", function (e){ e.preventDefault(); $('#overlay').fadeOut(300); $('#delivery').fadeOut(300); return false; }); $("body").off('click', ".mk-address-delivery").on('click', ".mk-address-delivery", function (e) { e.preventDefault(); $.ajax({ url: default_url+'/delivery/get-location', method: 'GET', success: function(response) { if (response.hasOwnProperty('show_delivery_modal') && response.show_delivery_modal) { $('#overlay').fadeIn(300); $('#delivery').fadeIn(300); return false; } if(response.hasOwnProperty('show_delivery_modal_confirm') && response.show_delivery_modal_confirm){ $('.address').text(response.location.address); $('#overlay').fadeIn(300); $('#confirm__method__delivery').fadeIn(300); return false; } }, error: function(xhr, status, error) { console.error('Error obteniendo la ubicación:', error); }, }); }); $("body").on('click', ".delivery__button__close", function(e){ e.preventDefault(); $('#overlay').fadeOut(300); $('#confirm__method__delivery').fadeOut(300); }); // Verifica si el input ya existe antes de añadirlo let placeAutocomplete = document.getElementById("place-autocomplete-input"); $("body").off('click', '.city-option').on('click', '.city-option', function () { // console.log("Click en ciudad seleccionada"); resetEverything(); const cityId = $(this).data('id'); // Obtiene el ID de la ciudad const cityName = $(this).data('name'); // Obtiene el nombre de la ciudad const cityLat = parseFloat($(this).data('lat')); // Obtiene la latitud const cityLng = parseFloat($(this).data('lng')); // Obtiene la longitud const coverage = JSON.parse($(this).attr('data-coverage') || "{}"); if (coverage.length > 0) { // Si hay cobertura, la recorremos coverage.forEach(function(coverageCity) { // console.log('Direccion despacho:', coverageCity.dispatch_address); $('#city_address_dispatch').val(coverageCity.dispatch_address); $('#city_dispatch_latitude').val(coverageCity.latitude); $('#city_dispatch_longitude').val(coverageCity.longitude); }); } else { console.warn('No hay cobertura para esta ciudad.'); } // console.log('coverage',coverage); // console.log(`Ciudad seleccionada: ${cityName}, Latitud: ${cityLat}, Longitud: ${cityLng}`); // console.log('city_id',cityId ); $('#selected_city_id').val(cityId); $('#selected_city_name').val(cityName); // Oculta la lista de ciudades $('.autocomplete-list').hide(); $('.select-delivery-city').hide(); // Muestra la sección del mapa $('#place-autocomplete-card').show(); // Mostrar el contenedor $('#map').show(); // Mostrar el mapa $('#change_city').show(); // Inicializa el mapa con la latitud y longitud de la ciudad // initMap(cityLat, cityLng); if (!map) { initMap(cityLat, cityLng); // Inicializa el mapa si no existe } else { // Si ya existe el mapa, solo actualiza la ubicación y el zoom map.setCenter({ lat: cityLat, lng: cityLng }); map.setZoom(13); updateMapAndMarker(cityLat, cityLng); updateAutocompleteBounds(cityLat, cityLng); } }); $('#change_city').on('click', function (e) { e.preventDefault(); $('#change_city').hide(); $('#place-autocomplete-card').hide(); $('#map').hide(); $('.autocomplete-list').show(); $('.select-delivery-city').show(); }); async function initMap(cityLat, cityLng) { // Request needed libraries. //@ts-ignore const [{ Map }, { AdvancedMarkerElement }] = await Promise.all([ google.maps.importLibrary("marker"), google.maps.importLibrary("places"), ]); // Initialize the map. map = new google.maps.Map(document.getElementById("map"), { center: { lat: cityLat, lng: cityLng }, zoom: 13, mapId: "4504f8b37365c3d0", mapTypeControl: false, }); if (!placeAutocomplete) { placeAutocomplete = new google.maps.places.PlaceAutocompleteElement({ componentRestrictions: { country: countryGoogle ? countryGoogle : 'CO' }, locationRestriction: new google.maps.LatLngBounds( new google.maps.LatLng(cityLat - 0.1, cityLng - 0.1), // Suroeste new google.maps.LatLng(cityLat + 0.1, cityLng + 0.1) // Noreste ), types: ["address"], }); placeAutocomplete.id = "place-autocomplete-input"; placeAutocomplete.className = "place-autocomplete-input-class"; // Buscar el contenedor correcto let card = document.getElementById("place-autocomplete-card-matrix"); // home if (!card) { card = document.getElementById("place-autocomplete-card"); // modal } if (card) { card.innerHTML = '
Ingresa tu dirección:
'; card.appendChild(placeAutocomplete); if(document.getElementById("place-autocomplete-card-matrix")){ $(placeAutocomplete).css({ 'color': '#000', 'background': '#fff', 'border': 'none' }); $(card).css({ 'color': '#fff', 'background': 'transparent', 'box-shadow': 'none', 'position': 'relative', 'top': '-14px' }); } map.controls[google.maps.ControlPosition.TOP_LEFT].push(card); } } // Create the marker and infowindow marker = new google.maps.marker.AdvancedMarkerElement({ map, }); infoWindow = new google.maps.InfoWindow({}); // Add the gmp-placeselect listener, and display the results on the map. //@ts-ignore placeAutocomplete.addEventListener('gmp-select', async ({ placePrediction }) => { const place = placePrediction.toPlace(); await place.fetchFields({ fields: ['displayName', 'formattedAddress', 'location'] }); // If the place has a geometry, then present it on a map. if (place.viewport) { map.fitBounds(place.viewport); } else { map.setCenter(place.location); map.setZoom(17); } let content = '