var DeviceMarkers = (function() {
    'use strict';
    
    var greenFeatures = [];
    var orangeFeatures = [];
    var redFeatures = [];
    var allFeatures = [];
    var myLocationFeature = null;
    var myLocationInterval = null;
    var showDeviceId = true;
    var minZoomForLabels = 4;
    

    var map = null;
    var vectorSource = null;
    var vectorLayer = null;
    

    function init(mapInstance, vectorSourceInstance, vectorLayerInstance) {
        map = mapInstance;
        vectorSource = vectorSourceInstance;
        vectorLayer = vectorLayerInstance;
    }
    

    function createDeviceStyle(feature) {
        if (feature.get('isMyLocation')) {
            return new ol.style.Style({
                image: new ol.style.Icon({
                    anchor: [0.5, 1],
                    src: '../images/loc_blue.png',
                    scale: 0.7
                })
            });
        }
        
        var deviceInfo = feature.get('deviceInfo');
        if (!deviceInfo) return null;
        
        var iconSrc;
        var color = '#000';
        var isHovered = feature.get('hovered') === true;
        var scale = isHovered ? 0.85 : 0.7;

        // 根据告警级别选择图标
        if (deviceInfo.warning == 2) {
            iconSrc = '../images/loc1_red.png';
        } else if (deviceInfo.warning == 1) {
            iconSrc = '../images/loc1_orange.png';
        } else {
            iconSrc = '../images/loc1_green.png';
        }

        var style = new ol.style.Style({
            image: new ol.style.Icon({
                anchor: [0.5, 1],
                src: iconSrc,
                scale: scale
            })
        });

        // 根据缩放级别和设置决定是否显示设备ID
        if (showDeviceId && map && map.getView().getZoom() >= minZoomForLabels) {
            style.setText(new ol.style.Text({
                text: deviceInfo.deviceid,
                offsetY: -30,
                fill: new ol.style.Fill({ 
                    color: isHovered ? '#1aa094' : color 
                }),
                stroke: new ol.style.Stroke({ 
                    color: '#fff', 
                    width: isHovered ? 3 : 2 
                }),
                font: isHovered ? 'bold 12px Arial' : '12px Arial'
            }));
        }

        return style;
    }
    

    function addDeviceMarkers(deviceList) {
        if (!vectorSource || !deviceList) return;
        
        var savedMyLocationFeature = myLocationFeature;

        vectorSource.clear();
        greenFeatures = [];
        orangeFeatures = [];
        redFeatures = [];
        allFeatures = [];

        for (var i = 0; i < deviceList.length; i++) {
            var device = deviceList[i];
            var currentMapType = getCurrentMapType();
            var mapCoordinates = CoordinateUtils.getMapCoordinates(
                device.latitude, 
                device.longitude, 
                currentMapType
            );

            var feature = new ol.Feature({
                geometry: new ol.geom.Point(mapCoordinates),
                deviceInfo: device
            });

            // 按告警级别分类
            if (device.warning == 2) {
                redFeatures.push(feature);
            } else if (device.warning == 1) {
                orangeFeatures.push(feature);
            } else {
                greenFeatures.push(feature);
            }

            allFeatures.push(feature);
            vectorSource.addFeature(feature);
        }

        if (savedMyLocationFeature) {
            vectorSource.addFeature(savedMyLocationFeature);
        }

        // 强制更新样式
        if (vectorLayer) {
            vectorLayer.changed();
        }
    }
    

    function getCurrentMapType() {
        var mapTypeSelect = document.getElementById('mapTypeSelectNew');
        return mapTypeSelect ? mapTypeSelect.value : 'tianditu_satellite';
    }
    

    function showAllDevices() {
        if (!vectorSource) return;
        
        var savedMyLocationFeature = myLocationFeature;
        vectorSource.clear();

        if (savedMyLocationFeature) {
            vectorSource.addFeature(savedMyLocationFeature);
        }

        for (var i = 0; i < allFeatures.length; i++) {
            vectorSource.addFeature(allFeatures[i]);
        }
    }
    
    function showWarning1Devices() {
        if (!vectorSource) return;
        
        var savedMyLocationFeature = myLocationFeature;
        vectorSource.clear();

        if (savedMyLocationFeature) {
            vectorSource.addFeature(savedMyLocationFeature);
        }

        for (var i = 0; i < allFeatures.length; i++) {
            vectorSource.addFeature(allFeatures[i]);
        }

        hideGreenFeatures();
        hideRedFeatures();
    }
    

    function showWarning2Devices() {
        if (!vectorSource) return;
        
        var savedMyLocationFeature = myLocationFeature;
        vectorSource.clear();

        if (savedMyLocationFeature) {
            vectorSource.addFeature(savedMyLocationFeature);
        }

        for (var i = 0; i < allFeatures.length; i++) {
            vectorSource.addFeature(allFeatures[i]);
        }

        hideGreenFeatures();
        hideOrangeFeatures();
    }
    
    function hideGreenFeatures() {
        for (var i = 0; i < greenFeatures.length; i++) {
            vectorSource.removeFeature(greenFeatures[i]);
        }
    }

    function hideOrangeFeatures() {
        for (var i = 0; i < orangeFeatures.length; i++) {
            vectorSource.removeFeature(orangeFeatures[i]);
        }
    }
    
    function hideRedFeatures() {
        for (var i = 0; i < redFeatures.length; i++) {
            vectorSource.removeFeature(redFeatures[i]);
        }
    }
    
    function findDeviceById(deviceId) {
        // console.log('搜索设备:', deviceId, '(类型:', typeof deviceId, ')');
        // console.log('当前设备总数:', allFeatures.length);
        
        var searchTerm = String(deviceId).trim();
        
        for (var i = 0; i < allFeatures.length; i++) {
            var feature = allFeatures[i];
            var deviceInfo = feature.get('deviceInfo');
            if (deviceInfo) {
                var currentDeviceId = String(deviceInfo.deviceid);
                // console.log('检查设备:', currentDeviceId, '(类型:', typeof deviceInfo.deviceid, ')');
                
                if (currentDeviceId === searchTerm) {
                    // console.log('精确匹配找到设备:', currentDeviceId);
                    return feature;
                }
                
                if (currentDeviceId.indexOf(searchTerm) !== -1) {
                    // console.log('部分匹配找到设备:', currentDeviceId);
                    return feature;
                }
                
                if (currentDeviceId.replace(/\s+/g, '') === searchTerm.replace(/\s+/g, '')) {
                    // console.log('去除空格后匹配找到设备:', currentDeviceId);
                    return feature;
                }
            }
        }
        console.log('未找到设备:', deviceId);
        return null;
    }

    function locateDevice(deviceId) {
        var feature = findDeviceById(deviceId);
        if (feature && map) {
            var geometry = feature.getGeometry();
            var coordinates = geometry.getCoordinates();
            
            map.getView().animate({
                center: coordinates,
                zoom: Math.max(map.getView().getZoom(), 15),
                duration: 1000
            });
            return true;
        }
        return false;
    }
    
    /**
     * 获取我的位置
     */
    function getMyLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
                function(position) {
                    var lat = position.coords.latitude;
                    var lon = position.coords.longitude;
                    
                    var currentMapType = getCurrentMapType();
                    var coordinates = CoordinateUtils.getMapCoordinates(lat, lon, currentMapType);
                    
                    if (myLocationFeature) {
                        vectorSource.removeFeature(myLocationFeature);
                    }
                    
                    myLocationFeature = new ol.Feature({
                        geometry: new ol.geom.Point(coordinates),
                        isMyLocation: true
                    });
                    
                    vectorSource.addFeature(myLocationFeature);

                    // map.getView().animate({
                    //     center: coordinates,
                    //     zoom: 15,
                    //     duration: 1000
                    // });
                },
                function(error) {
                    console.error('获取位置失败:', error);
                }
            );
        }
    }

    function locateMyLocation() {
        if (myLocationFeature) {
            var geometry = myLocationFeature.getGeometry();
            var coordinates = geometry.getCoordinates();
            
            map.getView().animate({
                center: coordinates,
                zoom: 15,
                duration: 1000
            });
            return true;
        } else {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(
                    function(position) {
                        var lat = position.coords.latitude;
                        var lon = position.coords.longitude;
                        
                        var currentMapType = getCurrentMapType();
                        var coordinates = CoordinateUtils.getMapCoordinates(lat, lon, currentMapType);
                        
                        if (myLocationFeature) {
                            vectorSource.removeFeature(myLocationFeature);
                        }
                        
                        myLocationFeature = new ol.Feature({
                            geometry: new ol.geom.Point(coordinates),
                            isMyLocation: true
                        });
                        
                        vectorSource.addFeature(myLocationFeature);
                        
                        map.getView().animate({
                            center: coordinates,
                            zoom: 15,
                            duration: 1000
                        });
                    },
                );
            }
        }
        return false;
    }
    

    function startLocationUpdates() {
        if (navigator.geolocation) {
            myLocationInterval = setInterval(function() {
                getMyLocation();
            }, 30000);
        }
    }
    

    function stopLocationUpdates() {
        if (myLocationInterval) {
            clearInterval(myLocationInterval);
            myLocationInterval = null;
        }
    }
    

    function updateMyLocationForMapType(mapType) {
        if (myLocationFeature) {
            var geometry = myLocationFeature.getGeometry();
            var coordinates = geometry.getCoordinates();
            var lonLat = ol.proj.toLonLat(coordinates);
            
            var newCoordinates = CoordinateUtils.getMapCoordinates(lonLat[1], lonLat[0], mapType);
            
            myLocationFeature.setGeometry(new ol.geom.Point(newCoordinates));
        }
    }

    function setShowDeviceId(show) {
        showDeviceId = show;
        if (vectorLayer) {
            vectorLayer.changed();
        }
    }
    

    function getDeviceStats() {
        return {
            total: allFeatures.length,
            green: greenFeatures.length,
            orange: orangeFeatures.length,
            red: redFeatures.length
        };
    }

    return {
        init: init,
        createDeviceStyle: createDeviceStyle,
        addDeviceMarkers: addDeviceMarkers,
        showAllDevices: showAllDevices,
        showWarning1Devices: showWarning1Devices,
        showWarning2Devices: showWarning2Devices,
        hideGreenFeatures: hideGreenFeatures,
        hideOrangeFeatures: hideOrangeFeatures,
        hideRedFeatures: hideRedFeatures,
        findDeviceById: findDeviceById,
        locateDevice: locateDevice,
        getMyLocation: getMyLocation,
        locateMyLocation: locateMyLocation,
        startLocationUpdates: startLocationUpdates,
        stopLocationUpdates: stopLocationUpdates,
        updateMyLocationForMapType: updateMyLocationForMapType,
        setShowDeviceId: setShowDeviceId,
        getDeviceStats: getDeviceStats,
        
        getAllFeatures: function() { return allFeatures; },
        getGreenFeatures: function() { return greenFeatures; },
        getOrangeFeatures: function() { return orangeFeatures; },
        getRedFeatures: function() { return redFeatures; },
        getMyLocationFeature: function() { return myLocationFeature; }
    };
})(); 