var MapCore = (function() {
    'use strict';
    
    var map = null;
    var vectorSource = null;
    var vectorLayer = null;
    var clusterSource = null;
    var clusterLayer = null;
    var currentBaseLayer = null;
    var showDeviceId = true;
    var showCluster = true;
    var minZoomForLabels = 4;
    var maxZoomForClustering = 8;
    var hoveredFeature = null;
    

    function initialize(deviceList) {
        // 创建矢量数据源和图层
        vectorSource = new ol.source.Vector();
        vectorLayer = new ol.layer.Vector({
            source: vectorSource,
            style: function(feature) {
                return DeviceMarkers.createDeviceStyle(feature);
            }
        });

        // 创建集群数据源和图层
        clusterSource = new ol.source.Cluster({
            distance: 40,
            source: vectorSource
        });

        clusterLayer = new ol.layer.Vector({
            source: clusterSource,
            style: function(feature) {
                var size = feature.get('features').length;
                var style = new ol.style.Style({
                    image: new ol.style.Circle({
                        radius: 15,
                        fill: new ol.style.Fill({
                            color: '#3399CC'
                        })
                    }),
                    text: new ol.style.Text({
                        text: size.toString(),
                        fill: new ol.style.Fill({
                            color: '#fff'
                        })
                    })
                });
                return style;
            }
        });

        var initialMapType = document.getElementById('mapTypeSelectNew').value || 'tianditu_satellite';
        currentBaseLayer = MapLayers.getLayer(initialMapType);

        map = new ol.Map({
            target: 'map-container',
            layers: [
                currentBaseLayer,
                clusterLayer,
                vectorLayer
            ],
            view: new ol.View({
                center: ol.proj.fromLonLat([116.404, 39.915]),
                zoom: 7
            })
        });

        DeviceMarkers.init(map, vectorSource, vectorLayer);
        MeasureTools.init(map);
        WeatherForecast.init();

        var scaleLineControl = new ol.control.ScaleLine();
        map.addControl(scaleLineControl);

        var initialZoom = map.getView().getZoom();
        updateLayerVisibility(initialZoom);

        map.getView().on('change:resolution', function() {
            var zoom = map.getView().getZoom();
            updateLayerVisibility(zoom);
            vectorLayer.changed();
        });

        bindMouseEvents();

        if (deviceList && deviceList.length > 0) {
            setCenterFromDevices(deviceList);
            DeviceMarkers.addDeviceMarkers(deviceList);
        }

        DeviceMarkers.getMyLocation();
        DeviceMarkers.startLocationUpdates();
        
        document.getElementById('showDeviceIdSwitch').checked = showDeviceId;
        document.getElementById('showClusterSwitch').checked = showCluster;
    }
    
    function updateLayerVisibility(zoom) {
        if (showCluster) {
            if (zoom >= maxZoomForClustering) {
                clusterLayer.setVisible(false);
                vectorLayer.setVisible(true);
            } else {
                clusterLayer.setVisible(true);
                vectorLayer.setVisible(false);
            }
        } else {
            clusterLayer.setVisible(false);
            vectorLayer.setVisible(true);
        }
    }
    
    function bindMouseEvents() {
        map.on('pointermove', function(evt) {
            if (evt.dragging) {
                return;
            }
            
            var pixel = map.getEventPixel(evt.originalEvent);
            var hit = map.hasFeatureAtPixel(pixel);
            
            map.getTargetElement().style.cursor = hit ? 'pointer' : '';
            
            var feature = map.forEachFeatureAtPixel(pixel, function(feature) {
                return feature;
            });
            
            if (hoveredFeature && hoveredFeature !== feature) {
                hoveredFeature.set('hovered', false);
            }
            
            if (feature) {
                // 处理集群
                var features = feature.get('features');
                if (features && features.length === 1) {
                    features[0].set('hovered', true);
                    hoveredFeature = features[0];
                } else if (!features && feature.get('deviceInfo')) {
                    feature.set('hovered', true);
                    hoveredFeature = feature;
                }
            }
            
            vectorLayer.changed();
        });
        
        map.on('click', function(evt) {
            var feature = map.forEachFeatureAtPixel(evt.pixel, function(feature) {
                return feature;
            });

            if (feature) {
                var features = feature.get('features');
                if (features && features.length > 1) {
                    // 集群点击，扩展视图
                    var extent = vectorSource.getExtent();
                    map.getView().fit(extent, {
                        padding: [50, 50, 50, 50],
                        duration: 1000
                    });
                } else if (features && features.length === 1) {
                    // 单个设备点击
                    var deviceInfo = features[0].get('deviceInfo');
                    if (deviceInfo) {
                        showDeviceInfo(deviceInfo);
                        // 如果天气预测开启，显示天气卡片
                        if (WeatherForecast.isEnabled()) {
                            WeatherForecast.showWeatherForecast(deviceInfo);
                        }
                    }
                } else if (feature.get('deviceInfo')) {
                    var deviceInfo = feature.get('deviceInfo');
                    showDeviceInfo(deviceInfo);
                    // 如果天气预测开启，显示天气卡片
                    if (WeatherForecast.isEnabled()) {
                        WeatherForecast.showWeatherForecast(deviceInfo);
                    }
                }
            }
        });
    }
    

    function showDeviceInfo(deviceInfo) {
        var statusText = '';
        
        if (deviceInfo.warning === 2) {
            statusText = '严重告警';
        } else if (deviceInfo.warning === 1) {
            statusText = '一般告警';
        } else {
            statusText = '正常';
        }
        
        var infoMsg = ' 设备: ' + deviceInfo.deviceid + 
                      ' | 状态: ' + statusText + 
                      ' | 坐标: ' + deviceInfo.latitude.toFixed(4) + ', ' + deviceInfo.longitude.toFixed(4);
        
        if (window.layer && typeof window.layer.msg === 'function') {
            window.layer.msg(infoMsg, {
                time: 3000,
                area: ['auto', 'auto'],
                offset: 'auto'
            });
        }
    }
    
    function setCenterFromDevices(deviceList) {
        if (!deviceList || deviceList.length === 0) return;
        
        var sumLat = 0, sumLon = 0;
        for (var i = 0; i < deviceList.length; i++) {
            sumLat += deviceList[i].latitude;
            sumLon += deviceList[i].longitude;
        }
        var centerLat = sumLat / deviceList.length;
        var centerLon = sumLon / deviceList.length;
        
        map.getView().setCenter(ol.proj.fromLonLat([centerLon, centerLat]));
    }

    function switchMapType(mapType) {
        if (!MapLayers.hasLayer(mapType)) {
            console.error('未知的地图类型:', mapType);
            return;
        }
        
        // 保存当前视图状态
        var currentCenter = map.getView().getCenter();
        var currentZoom = map.getView().getZoom();
        
        map.removeLayer(currentBaseLayer);
        currentBaseLayer = MapLayers.getLayer(mapType);
        map.getLayers().insertAt(0, currentBaseLayer);

        DeviceMarkers.updateMyLocationForMapType(mapType);

        var deviceList = window.deviceList || [];
        DeviceMarkers.addDeviceMarkers(deviceList);

        // 恢复之前的视图状态
        map.getView().setCenter(currentCenter);
        map.getView().setZoom(currentZoom);
    }
    
    function toggleDeviceId() {
        showDeviceId = document.getElementById('showDeviceIdSwitch').checked;
        DeviceMarkers.setShowDeviceId(showDeviceId);
        
        if (window.layer && typeof window.layer.msg === 'function') {
            window.layer.msg(showDeviceId ? '已显示设备信息' : '已隐藏设备信息');
        }
    }
    
    function toggleCluster() {
        showCluster = document.getElementById('showClusterSwitch').checked;
        var zoom = map.getView().getZoom();
        updateLayerVisibility(zoom);
        
        if (window.layer && typeof window.layer.msg === 'function') {
            window.layer.msg(showCluster ? '已启用集群显示' : '已禁用集群显示');
        }
    }
    
    function toggleMapFunctionsMenu() {
        var menu = document.getElementById('mapFunctionsMenu');
        if (menu) {
            menu.classList.toggle('show');
            if (menu.classList.contains('show')) {
                document.addEventListener('click', closeMapFunctionsMenu);
            }
        }
    }

    function closeMapFunctionsMenu(event) {
        var dropdown = document.getElementById('mapFunctionsMenu');
        var toggleBtn = document.querySelector('.dropdown-toggle');
        
        if (dropdown && !dropdown.contains(event.target) && !toggleBtn.contains(event.target)) {
            dropdown.classList.remove('show');
            document.removeEventListener('click', closeMapFunctionsMenu);
        }
    }

    function onMapTypeChange() {
        var mapType = document.getElementById('mapTypeSelectNew').value;
        switchMapType(mapType);
    }
    
    function onWarningFilterChange() {
        var filterValue = document.getElementById('warningFilter').value;
        switch(filterValue) {
            case 'all':
                SearchFilter.showAllDevices();
                break;
            case 'warning1':
                SearchFilter.showWarning1Devices();
                break;
            case 'warning2':
                SearchFilter.showWarning2Devices();
                break;
        }
    }
    
    function searchDeviceNew() {
        var searchInput = document.getElementById('deviceSearchNew');
        if (searchInput) {
            var deviceId = searchInput.value.trim();
            if (deviceId) {
                SearchFilter.searchDevice(deviceId);
            } else {
                if (window.layer && typeof window.layer.msg === 'function') {
                    window.layer.msg('请输入设备编号');
                }
            }
        }
    }
    
    function getMap() {
        return map;
    }

    function getVectorSource() {
        return vectorSource;
    }
    
    function getVectorLayer() {
        return vectorLayer;
    }
    
    return {
        initialize: initialize,
        switchMapType: switchMapType,
        toggleDeviceId: toggleDeviceId,
        toggleCluster: toggleCluster,
        toggleMapFunctionsMenu: toggleMapFunctionsMenu,
        onMapTypeChange: onMapTypeChange,
        onWarningFilterChange: onWarningFilterChange,
        searchDeviceNew: searchDeviceNew,
        getMap: getMap,
        getVectorSource: getVectorSource,
        getVectorLayer: getVectorLayer
    };
})(); 