var SearchFilter = (function() {
    'use strict';
    
    var currentSearchedDevice = null;
    var markerState = 3; // 1:all; 2:orange; 3:red
    var filteredDeviceIds = [];
    var isFilterActive = false; 
    
    function searchDevice(deviceId) {
        if (!deviceId || !deviceId.trim()) {
            clearSearch();
            return false;
        }
        
        deviceId = deviceId.trim();
        
        // 多设备
        if (deviceId.indexOf(',') !== -1) {
            return handleMultiDeviceSearch(deviceId);
        }
        
        // 单设备
        currentSearchedDevice = deviceId;
        
        var success = DeviceMarkers.locateDevice(deviceId);
        
        if (success) {
            if (window.layer && typeof window.layer.msg === 'function') {
                window.layer.msg('已定位到设备: ' + deviceId);
            }
            
            // 获取设备信息并显示天气预测（如果启用）
            var targetFeature = DeviceMarkers.findDeviceById(deviceId);
            if (targetFeature && window.WeatherForecast && window.WeatherForecast.isEnabled()) {
                var deviceInfo = targetFeature.get('deviceInfo');
                if (deviceInfo) {
                    window.WeatherForecast.showWeatherForecast(deviceInfo);
                }
            }
        } else {
            if (window.layer && typeof window.layer.msg === 'function') {
                window.layer.msg('未找到设备: ' + deviceId);
            }
        }
        
        return success;
    }
    
    function handleMultiDeviceSearch(deviceIdsString) {
        var deviceIds = deviceIdsString.split(',').map(function(id) {
            return id.trim();
        }).filter(function(id) {
            return id !== '';
        });
        
        if (deviceIds.length === 0) {
            clearSearch();
            return false;
        }
        
        filteredDeviceIds = deviceIds;
        
        var foundDevices = filterDevicesByIds(deviceIds);
        
        if (foundDevices.length > 0) {
            showFilterStatus(deviceIds.length);
            
            isFilterActive = true;

            var firstDevice = foundDevices[0];
            var geometry = firstDevice.getGeometry();
            var coordinates = geometry.getCoordinates();
            
            if (MapCore.getMap()) {
                MapCore.getMap().getView().animate({
                    center: coordinates,
                    zoom: 12,
                    duration: 1000
                });
            }
            
            if (window.layer && typeof window.layer.msg === 'function') {
                window.layer.msg('已过滤显示 ' + foundDevices.length + ' 个设备');
            }
            
            return true;
        } else {
            if (window.layer && typeof window.layer.msg === 'function') {
                window.layer.msg('未找到任何匹配的设备');
            }
            return false;
        }
    }
    
    function filterDevicesByIds(deviceIds) {
        if (!DeviceMarkers.getAllFeatures) return [];
        
        var allFeatures = DeviceMarkers.getAllFeatures();
        var foundDevices = [];
        var vectorSource = MapCore.getVectorSource();
        
        if (!vectorSource) return [];
        
        var myLocationFeature = DeviceMarkers.getMyLocationFeature();
        
        vectorSource.clear();
        
        if (myLocationFeature) {
            vectorSource.addFeature(myLocationFeature);
        }
        
        for (var i = 0; i < allFeatures.length; i++) {
            var feature = allFeatures[i];
            var deviceInfo = feature.get('deviceInfo');
            
            if (deviceInfo) {
                var deviceId = String(deviceInfo.deviceid).trim();
                
                for (var j = 0; j < deviceIds.length; j++) {
                    var searchId = String(deviceIds[j]).trim();
                    
                    if (deviceId === searchId || 
                        deviceId.indexOf(searchId) !== -1 || 
                        deviceId.replace(/\s+/g, '') === searchId.replace(/\s+/g, '')) {
                        vectorSource.addFeature(feature);
                        foundDevices.push(feature);
                        break;
                    }
                }
            }
        }
        
        return foundDevices;
    }
    
    function showFilterStatus(count) {
        var filterStatus = document.getElementById('filterStatus');
        
        if (filterStatus) {
            filterStatus.innerHTML = 
                '<span style="color: #1aa094; font-weight: bold; font-size: 12px;">定位中</span>' +
                '<button class="toolbar-btn" onclick="clearDeviceFilter()" style="background: #f56565; margin-left: 6px;">' +
                '<i class="layui-icon layui-icon-close" style="font-size: 12px;"></i>' +
                '</button>';
            
            filterStatus.style.display = 'flex';
        }
    }
    
    function hideFilterStatus() {
        var filterStatus = document.getElementById('filterStatus');
        if (filterStatus) {
            filterStatus.style.display = 'none';
        }
    }
    
    function clearDeviceFilter() {
        isFilterActive = false;
        filteredDeviceIds = [];
        hideFilterStatus();
        
        applyCurrentFilter();
        
        if (window.layer && typeof window.layer.msg === 'function') {
            window.layer.msg('已清除设备过滤');
        }
    }
    
    function clearSearch() {
        currentSearchedDevice = null;
        var searchInput = document.getElementById('deviceSearchNew');
        if (searchInput) {
            searchInput.value = '';
        }
        
        if (isFilterActive) {
            clearDeviceFilter();
        } else {
            // 恢复到当前的过滤状态
            applyCurrentFilter();
        }
    }
    
    function applyCurrentFilter() {
        switch(markerState) {
            case 1:
                showAllDevices();
                break;
            case 2:
                showWarning1Devices();
                break;
            case 3:
                showWarning2Devices();
                break;
        }
    }
    
    function showAllDevices() {
        currentSearchedDevice = null;
        clearSearchInput();
        DeviceMarkers.showAllDevices();
        markerState = 1;
        updateFilterSelect('all');
    }
    
    function showWarning1Devices() {
        currentSearchedDevice = null;
        clearSearchInput();
        DeviceMarkers.showWarning1Devices();
        markerState = 2;
        updateFilterSelect('warning1');
    }
    function showWarning2Devices() {
        currentSearchedDevice = null;
        clearSearchInput();
        DeviceMarkers.showWarning2Devices();
        markerState = 3;
        updateFilterSelect('warning2');
    }
    function clearSearchInput() {
        var searchInput = document.getElementById('deviceSearchNew');
        if (searchInput) {
            searchInput.value = '';
        }
    }
    
    function updateFilterSelect(filterValue) {
        var filterSelect = document.getElementById('warningFilter');
        if (filterSelect) {
            filterSelect.value = filterValue;
        }
    }
    
    function filterDevicesByStatus(statusType) {
        switch(statusType) {
            case 'warning1':
                showWarning1Devices();
                break;
            case 'warning2':
                showWarning2Devices();
                break;
            case 'offline':
            case 'no_fwd':
            case 'nofixed':
            case 'nogga':
                // 对于这些状态，显示所有设备，让用户在弹窗中选择
                showAllDevices();
                break;
            default:
                showAllDevices();
                break;
        }
    }
    
    function queryDevices(statusType) {
        filterDevicesByStatus(statusType);
        
        // 打开设备列表弹窗
        if (window.layer && typeof window.layer.open === 'function') {
            var index = window.layer.open({
                title: '设备列表',
                type: 2,
                shade: 0.2,
                maxmin: true,
                shadeClose: true,
                anim: 2,
                offset: 'rb',
                area: ['100%', '50%'],
                content: '../page/gnss_q_status?query=' + statusType,
            });
        }
    }
    
    function locateDeviceOnMap(deviceId, latitude, longitude) {
        currentSearchedDevice = deviceId;
        var success = DeviceMarkers.locateDevice(deviceId);
        
        if (success && window.layer && typeof window.layer.closeAll === 'function') {
            window.layer.closeAll();
        }
        
        return success;
    }
    
    function locateDeviceDirectly(deviceId) {
        currentSearchedDevice = deviceId;
        return DeviceMarkers.locateDevice(deviceId);
    }
    
    function getCurrentSearchedDevice() {
        return currentSearchedDevice;
    }
    
    function getMarkerState() {
        return markerState;
    }
    
    function setMarkerState(state) {
        markerState = state;
    }
    
    function isFilterModeActive() {
        return isFilterActive;
    }
    
    function getFilteredDeviceIds() {
        return filteredDeviceIds;
    }
    
    return {
        searchDevice: searchDevice,
        clearSearch: clearSearch,
        showAllDevices: showAllDevices,
        showWarning1Devices: showWarning1Devices,
        showWarning2Devices: showWarning2Devices,
        filterDevicesByStatus: filterDevicesByStatus,
        queryDevices: queryDevices,
        locateDeviceOnMap: locateDeviceOnMap,
        locateDeviceDirectly: locateDeviceDirectly,
        getCurrentSearchedDevice: getCurrentSearchedDevice,
        getMarkerState: getMarkerState,
        setMarkerState: setMarkerState,
        clearDeviceFilter: clearDeviceFilter,
        isFilterModeActive: isFilterModeActive,
        getFilteredDeviceIds: getFilteredDeviceIds
    };
})(); 