mapas_legacy.html 28.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
<!DOCTYPE html>
<html lang="es">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SISTEMA GIS - MapLibre 3D Elite</title>
    <script>
        if (!localStorage.getItem('jwt')) {
            window.location.href = '/gis-geoserver/login';
        }
    </script>
    <!-- MapLibre GL JS -->
    <script src="https://unpkg.com/maplibre-gl@3.6.2/dist/maplibre-gl.js"></script>
    <link href="https://unpkg.com/maplibre-gl@3.6.2/dist/maplibre-gl.css" rel="stylesheet" />
    <style>
        body,
        html {
            height: 100%;
            margin: 0;
            font-family: 'Inter', Arial, sans-serif;
            background-color: #0f172a;
            color: #fff;
            overflow: hidden;
        }

        .header {
            height: 60px;
            background: #1e293b;
            display: flex;
            align-items: center;
            padding: 0 20px;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.5);
            font-weight: bold;
            justify-content: space-between;
            position: relative;
            z-index: 1001;
        }

        .logout-btn {
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.3);
            color: white;
            padding: 8px 16px;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.2s;
        }

        .logout-btn:hover {
            background: #ef4444;
            border-color: #ef4444;
        }

        .app-container {
            display: flex;
            height: calc(100vh - 60px);
        }

        .sidebar {
            width: 340px;
            background: #0f172a;
            border-right: 1px solid rgba(255, 255, 255, 0.1);
            overflow-y: auto;
            padding: 20px;
            flex-shrink: 0;
        }

        .menu-title {
            font-size: 11px;
            color: #64748b;
            font-weight: 700;
            text-transform: uppercase;
            margin: 25px 0 10px;
            letter-spacing: 1px;
        }

        .menu-item {
            padding: 12px 16px;
            border-radius: 10px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 12px;
            color: #94a3b8;
            transition: all 0.2s;
            margin-bottom: 4px;
            border: 1px solid transparent;
            text-decoration: none;
        }

        .menu-item:hover {
            background: rgba(255, 255, 255, 0.05);
            color: #fff;
        }

        .menu-item.active {
            background: rgba(59, 130, 246, 0.1);
            color: #3b82f6;
            border-color: rgba(59, 130, 246, 0.3);
        }

        .submenu {
            padding-left: 10px;
            margin-bottom: 15px;
        }

        #map {
            flex: 1;
            position: relative;
        }

        /* Stats Dashboard Overlay */
        .stats-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
            margin-bottom: 20px;
        }

        .stat-card {
            background: rgba(255, 255, 255, 0.03);
            padding: 15px;
            border-radius: 12px;
            border: 1px solid rgba(255, 255, 255, 0.05);
        }

        .stat-label {
            font-size: 11px;
            color: #64748b;
            text-transform: uppercase;
            font-weight: 600;
        }

        .stat-value {
            font-size: 18px;
            font-weight: 700;
            color: #fff;
            margin-top: 5px;
        }

        /* Map Title Overlay */
        .map-title-overlay {
            position: absolute;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            background: rgba(15, 23, 42, 0.9);
            padding: 8px 24px;
            border-radius: 50px;
            border: 1px solid rgba(255, 255, 255, 0.1);
            color: #fff;
            font-weight: 700;
            font-size: 13px;
            z-index: 1000;
            backdrop-filter: blur(8px);
            text-transform: uppercase;
            letter-spacing: 1px;
        }

        /* Toggle 3D Control */
        .map-controls-floating {
            position: absolute;
            top: 20px;
            right: 20px;
            z-index: 1000;
            display: flex;
            flex-direction: column;
            gap: 10px;
        }

        .map-btn {
            background: rgba(15, 23, 42, 0.9);
            border: 1px solid rgba(255, 255, 255, 0.1);
            color: white;
            padding: 10px;
            border-radius: 10px;
            cursor: pointer;
            backdrop-filter: blur(8px);
            display: flex;
            align-items: center;
            gap: 8px;
            font-weight: 600;
            font-size: 12px;
            transition: all 0.2s;
        }

        .map-btn:hover {
            background: #1e293b;
            border-color: #3b82f6;
        }

        .map-btn.active {
            background: #3b82f6;
            border-color: #3b82f6;
        }

        /* Legend */
        .legend {
            position: absolute;
            bottom: 30px;
            right: 30px;
            background: rgba(15, 23, 42, 0.9);
            padding: 15px;
            border-radius: 12px;
            border: 1px solid rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            color: white;
            font-size: 12px;
            z-index: 1000;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.5);
            display: none;
        }

        .legend-item {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 5px;
        }

        .legend-color {
            width: 12px;
            height: 12px;
            border-radius: 3px;
        }

        /* Custom Popup Style */
        .maplibregl-popup-content {
            background: #1e293b;
            color: white;
            border-radius: 12px;
            padding: 0;
            border: 1px solid rgba(255, 255, 255, 0.1);
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
        }

        .maplibregl-popup-tip {
            border-top-color: #1e293b;
        }

        .popup-header {
            background: #3b82f6;
            padding: 12px;
            border-radius: 10px 10px 0 0;
            font-weight: 700;
            font-size: 13px;
            text-transform: uppercase;
        }

        .popup-body {
            padding: 15px;
        }

        .popup-stat {
            margin-bottom: 10px;
        }

        .popup-label {
            font-size: 10px;
            color: #64748b;
            text-transform: uppercase;
        }

        .popup-value {
            font-size: 13px;
            font-weight: 600;
        }

        /* Leyenda de morosidad con Glassmorphism */
        .map-legend {
            position: absolute;
            bottom: 30px;
            right: 20px;
            background: rgba(15, 23, 42, 0.85);
            padding: 18px;
            border-radius: 16px;
            border: 1px solid rgba(255, 255, 255, 0.1);
            color: #f1f5f9;
            font-size: 11px;
            z-index: 1000;
            backdrop-filter: blur(12px);
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
            max-width: 240px;
        }

        .legend-item {
            display: flex;
            align-items: center;
            margin-bottom: 8px;
            gap: 10px;
        }

        .legend-color {
            width: 30px;
            height: 12px;
            border-radius: 4px;
            border: 1px solid rgba(255, 255, 255, 0.1);
        }

        /* Capas Switcher */
        .layer-switcher {
            position: absolute;
            top: 20px;
            right: 50px;
            background: rgba(13, 17, 23, 0.9);
            padding: 10px;
            border-radius: 8px;
            border: 1px solid rgba(255, 255, 255, 0.1);
            z-index: 10;
        }
    </style>
</head>

<body>
    <div class="header">
        <div>🌍 SIGEM GIS <span id="user-greeting"
                style="font-size: 13px; font-weight: normal; margin-left: 10px; opacity: 0.7;"></span></div>
        <button class="logout-btn" onclick="logout()">Cerrar Sesión</button>
    </div>
    <div class="app-container">
        <div class="sidebar">
            <div id="stats-dashboard">
                <div class="menu-title">Resumen Municipal</div>
                <div class="stats-grid">
                    <div class="stat-card">
                        <div class="stat-label">Total Lotes</div>
                        <div id="stat-lotes" class="stat-value">...</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-label">Morosidad</div>
                        <div id="stat-morosos" class="stat-value" style="color: #f87171;">...</div>
                    </div>
                </div>
            </div>

            <div class="menu-title">Control de Gestión</div>
            <div id="menu-reset" class="menu-item active" onclick="resetMap()">🌍 Capas Base</div>

            <div class="menu-title">Mapas Tributarios</div>
            <div class="submenu">
                <div id="menu-ultimo-pago" class="menu-item" onclick="setHeatmap('ultimo-pago')">📅 Por Último Pago
                </div>
                <div id="menu-percentiles" class="menu-item" onclick="setHeatmap('percentiles')">📈 Por Total
                    (Percentiles)</div>
                <div id="menu-wms-test" class="menu-item" onclick="toggleWmsLayer()"
                    style="color: #fbbf24; border-top: 1px dashed #444; margin-top: 5px; font-weight: bold; display: none;">
                    🖼️ Vista PNG (Full) <span id="wms-status" style="font-size: 9px; opacity: 0.6;">[OFF]</span>
                </div>
            </div>

            <div class="menu-title">Administración</div>
            <div id="btn-update-data" class="menu-item" onclick="updateMunicipalData()" style="color: #60a5fa;">
                <span id="update-icon">🔄</span> <span id="update-text">Actualizar Datos MUNI</span>
            </div>

        </div>

        <div id="map">
            <!-- Leyenda Dinámica -->
            <div class="map-legend" id="legend" style="display: none;">
                <div id="legend-content"></div>
                <div
                    style="font-size: 10px; margin-top: 10px; border-top: 1px solid #333; padding-top: 5px; color: #888;">
                    Fuente: Sistema SIGEM</div>
            </div>

            <!-- Selector de Capas Base -->
            <div class="layer-switcher" style="position: absolute; top: 15px; left: 15px; z-index: 1000;">
                <select id="base-layer-select"
                    style="background: rgba(15, 23, 42, 0.9); color: white; border: 1px solid rgba(255,255,255,0.2); padding: 5px 10px; border-radius: 8px; font-size: 11px; cursor: pointer; backdrop-filter: blur(8px);">
                    <option value="dark">🌙 CartoDB Dark</option>
                    <option value="streets">🗺️ OpenStreetMap</option>
                    <option value="satellite">📡 Esri Satélite</option>
                </select>
            </div>
            <div id="map-title" class="map-title-overlay">Vista Cartográfica General</div>
        </div>
    </div>

    <script>
        const userName = localStorage.getItem('user_name');
        if (userName) document.getElementById('user-greeting').innerText = `| Bienvenido, ${userName}`;

        const entidad = localStorage.getItem('entidad') || '505';
        const token = localStorage.getItem('jwt');
        const geoserverBase = 'gwc/service/wmts';

        function logout() {
            localStorage.clear();
            window.location.href = '/gis-geoserver/login';
        }

        // --- Inicialización del Mapa ---
        const lat = parseFloat(localStorage.getItem('map_lat')) || -25.449;
        const lng = parseFloat(localStorage.getItem('map_lng')) || -56.443;
        const zoom = parseInt(localStorage.getItem('map_zoom')) || 15;

        const map = new maplibregl.Map({
            container: 'map',
            style: {
                version: 8,
                sources: {
                    'raster-tiles': {
                        type: 'raster',
                        tiles: ['https://a.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png'],
                        tileSize: 256,
                        attribution: '&copy; CartoDB'
                    }
                },
                layers: [{
                    id: 'basemap',
                    type: 'raster',
                    source: 'raster-tiles',
                    minzoom: 0,
                    maxzoom: 20
                }]
            },
            center: [lng, lat],
            zoom: zoom,
            pitch: 0,
            bearing: 0,
            antialias: true
        });

        map.addControl(new maplibregl.NavigationControl({ position: 'bottom-left' }));

        // --- Carga de Capas Vectoriales ---
        map.on('load', () => {
            initGisSources();
            loadMunicipalStats();
        });

        function initGisSources() {
            console.log("Cargando fuentes vectoriales (MVT)...");

            // Fuente de Lotes (MVT) - TMS Nativo de GeoServer
            if (!map.getSource('lotes-mvt')) {
                map.addSource('lotes-mvt', {
                    type: 'vector',
                    tiles: [
                        `${window.location.origin}/gis-geoserver/gwc/service/tms/1.0.0/sigem:vw_lotes_morosidad_${entidad}@XYZ-900913@pbf/{z}/{x}/{y}.pbf`
                    ],
                    scheme: 'tms'
                });
            }

            // Capa de Lotes (2D) - Visibilidad Inicial Mejorada
            if (!map.getLayer('lotes-layer')) {
                map.addLayer({
                    id: 'lotes-layer',
                    type: 'fill',
                    source: 'lotes-mvt',
                    'source-layer': `vw_lotes_morosidad_${entidad}`,
                    paint: {
                        'fill-color': 'rgba(59, 130, 246, 0.1)', // Azul tenue inicial
                        'fill-outline-color': 'rgba(255, 255, 255, 0.3)' // Borde blanco visible
                    }
                });
            }

            // Fuente de Mejoras (MVT) - TMS Nativo de GeoServer
            if (!map.getSource('mejoras-mvt')) {
                map.addSource('mejoras-mvt', {
                    type: 'vector',
                    tiles: [
                        `${window.location.origin}/gis-geoserver/gwc/service/tms/1.0.0/sigem:e${entidad}_mejoras@XYZ-900913@pbf/{z}/{x}/{y}.pbf`
                    ],
                    scheme: 'tms'
                });
            }

            // [PRUEBA CONTROLADA] Fuente Raster WMS (Renderizado en Servidor)
            if (!map.getSource('lotes-wms')) {
                map.addSource('lotes-wms', {
                    'type': 'raster',
                    'tiles': [
                        `${window.location.origin}/gis-geoserver/sigem/wms?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&LAYERS=sigem:vw_lotes_morosidad_${entidad}&STYLES=morosidad_style_wms&FORMAT=image/png&TRANSPARENT=TRUE&WIDTH=256&HEIGHT=256&SRS=EPSG:3857&BBOX={bbox-epsg-3857}`
                    ],
                    'tileSize': 256
                });
            }

            if (!map.getLayer('lotes-wms-layer')) {
                map.addLayer({
                    'id': 'lotes-wms-layer',
                    'type': 'raster',
                    'source': 'lotes-wms',
                    'paint': { 'raster-opacity': 0.8 },
                    'layout': { 'visibility': 'none' } 
                }); // Agregamos al final
            }

            // Capa de Mejoras (Inicialmente oculta o 2D)
            if (!map.getLayer('mejoras-layer')) {
                map.addLayer({
                    id: 'mejoras-layer',
                    type: 'fill',
                    source: 'mejoras-mvt',
                    'source-layer': `e${entidad}_mejoras`,
                    paint: {
                        'fill-color': 'rgba(59, 130, 246, 0.2)',
                        'fill-outline-color': 'rgba(59, 130, 246, 0.5)'
                    }
                });
            }
        }

        // --- Lógica de Capas Base ---
        const baseLayers = {
            'dark': 'https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json',
            'streets': 'https://basemaps.cartocdn.com/gl/voyager-gl-style/style.json',
            'satellite': {
                'version': 8,
                'sources': {
                    'raster-tiles': {
                        'type': 'raster',
                        'tiles': ['https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}'],
                        'tileSize': 256,
                        'attribution': 'Tiles &copy; Esri'
                    }
                },
                'layers': [{ 'id': 'simple-tiles', 'type': 'raster', 'source': 'raster-tiles', 'minzoom': 0, 'maxzoom': 18 }]
            }
        };

        document.getElementById('base-layer-select').addEventListener('change', (e) => {
            const style = baseLayers[e.target.value];
            map.setStyle(style);
            map.once('style.load', () => {
                initGisSources();
            });
        });

        // Lógica de 3D eliminada por requerimiento de usuario


        // --- Mapa de Calor (Heatmap) via Expresiones ---
        function setHeatmap(type) {
            document.querySelectorAll('.menu-item').forEach(el => el.classList.remove('active'));
            const titleEl = document.getElementById('map-title');
            const legendEl = document.getElementById('legend');
            const legendContent = document.getElementById('legend-content');
            legendEl.style.display = 'block';

            if (type === 'ultimo-pago') {
                document.getElementById('menu-ultimo-pago').classList.add('active');
                titleEl.textContent = '🗺️ Morosidad - Último Adeudado';
                map.setLayoutProperty('lotes-layer', 'visibility', 'visible');
                
                // Mostrar botón de prueba WMS solo en este modo
                document.getElementById('menu-wms-test').style.display = 'block';

                legendContent.innerHTML = `
                    <strong style="color: #60a5fa;">ÚLTIMO ADEUDADO</strong><br><br>
                    <div class="legend-item"><div class="legend-color" style="background: #6b9070;"></div> = 2026</div>
                    <div class="legend-item"><div class="legend-color" style="background: #b5c47a;"></div> <= 2025</div>
                    <div class="legend-item"><div class="legend-color" style="background: #ffd966;"></div> <= 2024</div>
                    <div class="legend-item"><div class="legend-color" style="background: #f08060;"></div> <= 2023</div>
                    <div class="legend-item"><div class="legend-color" style="background: #d05660;"></div> <= 2022</div>
                    <div class="legend-item"><div class="legend-color" style="background: #a91d1d;"></div> <= 2021</div>
                    <div class="legend-item"><div class="legend-color" style="background: #64748b;"></div> SIN DEUDA / PRESCRIPTAS</div>
                `;

                map.setPaintProperty('lotes-layer', 'fill-color', [
                    'step',
                    ['get', 'ultimo_pago'],
                    '#a91d1d', // < 2021
                    2021, '#a91d1d',
                    2022, '#d05660',
                    2023, '#f08060',
                    2024, '#ffd966',
                    2025, '#b5c47a',
                    2026, '#6b9070'
                ]);
            } else if (type === 'percentiles') {
                document.getElementById('menu-percentiles').classList.add('active');
                titleEl.textContent = '🗺️ Morosidad - Total Adeudado';
                map.setLayoutProperty('lotes-layer', 'visibility', 'visible');

                // Ocultar botón de prueba WMS
                document.getElementById('menu-wms-test').style.display = 'none';

                legendContent.innerHTML = `
                    <strong style="color: #60a5fa;">TOTAL ADEUDADO</strong><br><br>
                    <div class="legend-item"><div class="legend-color" style="background: #a91d1d;"></div> > 2.099.321 Gs</div>
                    <div class="legend-item"><div class="legend-color" style="background: #f08060;"></div> <= 2.099.321 Gs</div>
                    <div class="legend-item"><div class="legend-color" style="background: #ffd966;"></div> <= 1.226.945 Gs</div>
                    <div class="legend-item"><div class="legend-color" style="background: #b5c47a;"></div> <= 714.968 Gs</div>
                    <div class="legend-item"><div class="legend-color" style="background: #6b9070;"></div> <= 351.584 Gs</div>
                    <div class="legend-item"><div class="legend-color" style="background: #64748b;"></div> NO REGISTRADOS</div>
                `;

                map.setPaintProperty('lotes-layer', 'fill-color', [
                    'step',
                    ['get', 'trb_total_deuda'],
                    '#6b9070', // < 351k
                    351585, '#b5c47a',
                    714969, '#ffd966',
                    1226946, '#f08060',
                    2099322, '#a91d1d'
                ]);
            }
            // Aseguramos que el borde sea visible en modo heatmap
            map.setPaintProperty('lotes-layer', 'fill-outline-color', 'rgba(255, 255, 255, 0.4)');
        }

        function resetMap() {
            document.querySelectorAll('.menu-item').forEach(el => el.classList.remove('active'));
            document.getElementById('menu-reset').classList.add('active');
            document.getElementById('map-title').textContent = 'Vista Cartográfica General';
            document.getElementById('legend').style.display = 'none';
            map.setPaintProperty('lotes-layer', 'fill-color', 'rgba(255, 255, 255, 0.05)');
            
            // Ocultamos WMS si está activo al resetear
            if(map.getLayer('lotes-wms-layer')) {
                map.setLayoutProperty('lotes-wms-layer', 'visibility', 'none');
                document.getElementById('wms-status').innerText = '[OFF]';
                document.getElementById('menu-wms-test').classList.remove('active');
            }
            // Ocultar botón de prueba WMS al resetear
            document.getElementById('menu-wms-test').style.display = 'none';
        }

        // --- Control de Prueba Controlada WMS ---
        function toggleWmsLayer() {
            const entidad = localStorage.getItem('entidad') || '505';
            
            // Si la capa no existe, la creamos
            if (!map.getSource('lotes-wms')) {
                map.addSource('lotes-wms', {
                    'type': 'raster',
                    'tiles': [
                        `${window.location.origin}/gis-geoserver/sigem/wms?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&LAYERS=sigem:vw_lotes_morosidad_${entidad}&STYLES=morosidad_style_wms&FORMAT=image/png&TRANSPARENT=TRUE&WIDTH=256&HEIGHT=256&SRS=EPSG:3857&BBOX={bbox-epsg-3857}`
                    ],
                    'tileSize': 256
                });

                map.addLayer({
                    'id': 'lotes-wms-layer',
                    'type': 'raster',
                    'source': 'lotes-wms',
                    'layout': { 'visibility': 'none' },
                    'paint': { 'raster-opacity': 0.8 }
                }, 'lotes-layer'); // Debajo de la capa de interacción MVT
            }

            const isVisible = map.getLayoutProperty('lotes-wms-layer', 'visibility') === 'visible';
            const nextVisibility = isVisible ? 'none' : 'visible';
            const statusEl = document.getElementById('wms-status');
            const menuEl = document.getElementById('menu-wms-test');

            map.setLayoutProperty('lotes-wms-layer', 'visibility', nextVisibility);
            
            if (nextVisibility === 'visible') {
                statusEl.innerText = '[ON]';
                menuEl.classList.add('active');
                // Opcional: Ocultar MVT para mejor rendimiento visual en PNG Full
                // map.setLayoutProperty('lotes-layer', 'visibility', 'none');
            } else {
                statusEl.innerText = '[OFF]';
                menuEl.classList.remove('active');
                map.setLayoutProperty('lotes-layer', 'visibility', 'visible');
            }
        }

        // --- Popups Instantáneos (MVT Data) ---
        map.on('click', 'lotes-layer', (e) => {
            const props = e.features[0].properties;
            const content = `
                <div class="popup-header">ESTADO DE CUENTA: ${props.ccc || 'N/A'}</div>
                <div class="popup-body">
                    <div class="popup-grid" style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
                        <div class="popup-stat">
                            <div class="popup-label">Nro Ficha</div>
                            <div class="popup-value">${props.inm_ficha || '0'}</div>
                        </div>
                        <div class="popup-stat">
                            <div class="popup-label">Cta. Catastral</div>
                            <div class="popup-value" style="font-size: 11px;">${props.inm_ctacatastral || 'N/A'}</div>
                        </div>
                    </div>
                    <hr style="opacity: 0.1; margin: 10px 0;">
                    <div class="popup-stat">
                        <div class="popup-label">Total Adeudado</div>
                        <div class="popup-value" style="color: #f87171; font-size: 16px;">Gs. ${props.trb_total_deuda ? parseFloat(props.trb_total_deuda).toLocaleString('es-PY') : '0'}</div>
                    </div>
                    <div class="popup-grid" style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-top: 10px;">
                        <div class="popup-stat">
                            <div class="popup-label">Total Pagado</div>
                            <div class="popup-value" style="color: #10b981;">Gs. ${props.trb_total_pago ? parseFloat(props.trb_total_pago).toLocaleString('es-PY') : '0'}</div>
                        </div>
                        <div class="popup-stat">
                            <div class="popup-label">Último Pago</div>
                            <div class="popup-value">${props.ultimo_pago || 'Nunca'}</div>
                        </div>
                    </div>
                    <button class="logout-btn" style="width: 100%; margin-top: 15px; font-size: 11px; background: #60a5fa; color: #fff;">📄 Ver Detalles SIGEM</button>
                </div>
            `;

            new maplibregl.Popup()
                .setLngLat(e.lngLat)
                .setHTML(content)
                .addTo(map);
        });

        map.on('mouseenter', 'lotes-layer', () => map.getCanvas().style.cursor = 'pointer');
        map.on('mouseleave', 'lotes-layer', () => map.getCanvas().style.cursor = '');

        async function updateMunicipalData() {
            const btn = document.getElementById('btn-update-data');
            const icon = document.getElementById('update-icon');
            const text = document.getElementById('update-text');

            btn.style.pointerEvents = 'none';
            btn.style.opacity = '0.5';
            text.innerText = 'Procesando FDW...';
            icon.classList.add('rotating'); // Podríamos añadir CSS para rotar

            try {
                const res = await fetch(`/gis-geoserver/api/admin/fdw/update/${entidad}`, {
                    method: 'POST',
                    headers: { 'Authorization': `Bearer ${token}` }
                });
                const data = await res.json();

                if (data.success) {
                    alert("✅ Éxito: " + data.message);
                    location.reload(); // Recargamos para ver los cambios
                } else {
                    alert("❌ Error: " + data.message);
                }
            } catch (err) {
                console.error("Error en update:", err);
                alert("❌ Error de conexión con el servidor de administración.");
            } finally {
                btn.style.pointerEvents = 'auto';
                btn.style.opacity = '1';
                text.innerText = 'Actualizar Datos MUNI';
            }
        }

        async function loadMunicipalStats() {
            try {
                const res = await fetch(`/gis-geoserver/api/gis/entidad/${entidad}/resumen`, {
                    headers: { 'Authorization': `Bearer ${token}` }
                });
                const data = await res.json();
                document.getElementById('stat-lotes').innerText = data.total_lotes.toLocaleString();
                document.getElementById('stat-morosos').innerText = data.lotes_con_deuda.toLocaleString();
            } catch (err) { console.error("Error stats:", err); }
        }
    </script>
</body>

</html>
GitLab Appliance - Powered by TurnKey Linux