var WeatherForecast = (function() {
    'use strict';
    
    var weatherEnabled = false;
    var weatherData = null;
    var currentForecastIndex = 0;
    var currentWeatherDevice = null;
    
    function init() {
        // 天气预报模块初始化完成
    }
    
    function toggleWeatherForecast() {
        var role = window.userRole || 'USER';
        if (role !== 'SUPER_ADMIN') {
            if (window.layer && typeof window.layer.msg === 'function') {
                window.layer.msg('您没有权限使用此功能');
            }
            return; 
        }
        
        var enableSwitch = document.getElementById('enableWeatherSwitch');
        weatherEnabled = enableSwitch ? enableSwitch.checked : false;
        
        if (weatherEnabled) {
            if (window.layer && typeof window.layer.msg === 'function') {
                window.layer.msg(
                    '搜索设备或点击地图设备图标即可自动查询天气预测',
                    {time: 3000, area: ['300px', '80px']}
                );
            }
        } else {
            if (window.layer && typeof window.layer.msg === 'function') {
                window.layer.msg('天气预测功能已关闭');
            }
            closeWeatherCard();
        }
        
        var menu = document.getElementById('mapFunctionsMenu');
        if (menu) {
            menu.classList.remove('show');
        }
    }
    
    function showWeatherForecast(deviceInfo) {
        currentWeatherDevice = deviceInfo;
        weatherData = null;
        
        var role = window.userRole || 'USER';
        if (role !== 'SUPER_ADMIN') {
            return;
        }
                
        if (!weatherEnabled) {
            if (window.layer && typeof window.layer.msg === 'function') {
                window.layer.msg('天气预测功能未启用', {time: 2000});
            }
            return;
        }
        
        var deviceIdElement = document.getElementById('weatherDeviceId');
        var deviceCoordsElement = document.getElementById('weatherDeviceCoords');
        
        if (deviceIdElement) {
            deviceIdElement.textContent = '设备: ' + deviceInfo.deviceid;
        }
        
        if (deviceCoordsElement) {
            deviceCoordsElement.textContent = 
                '坐标: ' + deviceInfo.latitude.toFixed(4) + ', ' + deviceInfo.longitude.toFixed(4);
        }
        
        var weatherCard = document.getElementById('weatherForecastCard');
        if (weatherCard) {
            weatherCard.style.display = 'block';
        }
        
        var contentElement = document.getElementById('weatherForecastContent');
        if (contentElement) {
            contentElement.innerHTML = 
                '<div class="weather-loading">' +
                '<i class="layui-icon layui-icon-loading layui-icon-anim-rotate"></i>' +
                '<p>正在获取天气预测数据...</p>' +
                '</div>';
        }
        
        var prevBtn = document.getElementById('prevForecast');
        var nextBtn = document.getElementById('nextForecast');
        var timeDisplay = document.getElementById('forecastTimeDisplay');
        
        if (prevBtn) prevBtn.disabled = true;
        if (nextBtn) nextBtn.disabled = true;
        if (timeDisplay) timeDisplay.textContent = '--:--';
        
        fetchWeatherData(deviceInfo.latitude, deviceInfo.longitude);
    }
    
    function closeWeatherCard() {
        var weatherCard = document.getElementById('weatherForecastCard');
        if (weatherCard) {
            weatherCard.style.display = 'none';
        }
        currentWeatherDevice = null;
        weatherData = null;
    }
    
    function showPrevForecast() {
        if (!weatherData || currentForecastIndex <= 0) return;
        
        currentForecastIndex--;
        displayCurrentForecast();
        updateForecastNavigation();
    }
    
    function showNextForecast() {
        if (!weatherData || !weatherData.ts || currentForecastIndex >= weatherData.ts.length - 1) return;
        
        currentForecastIndex++;
        displayCurrentForecast();
        updateForecastNavigation();
    }
    
    function updateForecastNavigation() {
        if (!weatherData || !weatherData.ts) return;
        
        var prevBtn = document.getElementById('prevForecast');
        var nextBtn = document.getElementById('nextForecast');
        var timeDisplay = document.getElementById('forecastTimeDisplay');
        
        if (prevBtn) prevBtn.disabled = (currentForecastIndex <= 0);
        if (nextBtn) nextBtn.disabled = (currentForecastIndex >= weatherData.ts.length - 1);
        
        if (timeDisplay) {
            var timestamp = weatherData.ts[currentForecastIndex];
            var date = new Date(timestamp);
            timeDisplay.textContent = formatDateTime(date);
        }
    }

    function fetchWeatherData(lat, lon) {
        var url = 'https://api.open-meteo.com/v1/forecast?' +
            'latitude=' + lat.toFixed(4) + 
            '&longitude=' + lon.toFixed(4) +
            '&current=temperature_2m,wind_speed_10m,wind_direction_10m,relative_humidity_2m,surface_pressure' +
            '&hourly=temperature_2m,relative_humidity_2m,wind_speed_10m,wind_direction_10m,precipitation,surface_pressure,wind_gusts_10m' +
            '&forecast_days=3' +
            '&timezone=auto';
        
        fetch(url, {
            method: 'GET',
            headers: {
                'Accept': 'application/json'
            }
        })
        .then(function(response) {
            if (!response.ok) {
                throw new Error('网络响应状态: ' + response.status);
            }
            return response.json();
        })
        .then(function(data) {
            weatherData = transformOpenMeteoData(data);
            
            var currentTime = new Date().getTime();
            var closestIndex = 0;
            var futureIndex = -1;
            
            if (weatherData.ts && weatherData.ts.length > 0) {
                for (var i = 0; i < weatherData.ts.length; i++) {
                    if (weatherData.ts[i] > currentTime) {
                        futureIndex = i;
                        break;
                    }
                }
                
                if (futureIndex >= 0) {
                    closestIndex = futureIndex;
                } else {
                    var smallestDiff = Number.MAX_VALUE;
                    for (var i = 0; i < weatherData.ts.length; i++) {
                        var diff = Math.abs(weatherData.ts[i] - currentTime);
                        if (diff < smallestDiff) {
                            smallestDiff = diff;
                            closestIndex = i;
                        }
                    }
                }
            }
            
            currentForecastIndex = closestIndex;
            displayCurrentForecast();
            updateForecastNavigation();
        })
        .catch(function(error) {
            console.error('天气数据获取失败:', error);
            displayWeatherError('获取天气数据失败: ' + error.message);
        });
    }
    
    function transformOpenMeteoData(data) {
        var transformed = {
            ts: [],
            'temp-surface': [],
            'wind-speed': [],
            'wind-direction': [],
            'precipitation': [],
            'rh-surface': [],
            'pressure-surface': [],
            'gust-surface': []
        };
        
        if (!data.hourly || !data.hourly.time) {
            return transformed;
        }
        
        for (var i = 0; i < data.hourly.time.length; i++) {
            transformed.ts.push(new Date(data.hourly.time[i]).getTime());
            
            transformed['temp-surface'].push(data.hourly.temperature_2m[i]);
            
            var windSpeedMs = data.hourly.wind_speed_10m[i] ? data.hourly.wind_speed_10m[i] / 3.6 : null;
            transformed['wind-speed'].push(windSpeedMs);
            transformed['wind-direction'].push(data.hourly.wind_direction_10m[i]);
            transformed['precipitation'].push(data.hourly.precipitation[i]);
            transformed['rh-surface'].push(data.hourly.relative_humidity_2m[i]);
            transformed['pressure-surface'].push(data.hourly.surface_pressure[i]);
            var gustMs = data.hourly.wind_gusts_10m[i] ? data.hourly.wind_gusts_10m[i] / 3.6 : null;
            transformed['gust-surface'].push(gustMs);
        }
        
        return transformed;
    }
    
    function displayCurrentForecast() {
        if (!weatherData || !weatherData.ts || weatherData.ts.length === 0) {
            displayWeatherError('无可用的天气预测数据');
            return;
        }
        
        var i = currentForecastIndex;
        var forecastHtml = '<div class="weather-forecast-item"><div class="weather-param-grid">';
        
        if (weatherData['temp-surface'] && weatherData['temp-surface'][i] !== null) {
            var temp = weatherData['temp-surface'][i].toFixed(1);
            forecastHtml += createWeatherParam('温度', temp + '°C');
        }
        
        if (weatherData['wind-speed'] && weatherData['wind-speed'][i] !== null) {
            var windSpeed = weatherData['wind-speed'][i].toFixed(1);
            forecastHtml += createWeatherParam('风速', windSpeed + ' m/s');
        }
        
        if (weatherData['wind-direction'] && weatherData['wind-direction'][i] !== null) {
            var windDir = getWindDirectionFromDegrees(weatherData['wind-direction'][i]);
            forecastHtml += createWeatherParam('风向', windDir);
        }
        
        if (weatherData['precipitation'] && weatherData['precipitation'][i] !== null) {
            var precip = weatherData['precipitation'][i].toFixed(1);
            forecastHtml += createWeatherParam('降水', precip + ' mm');
        }
        
        if (weatherData['rh-surface'] && weatherData['rh-surface'][i] !== null) {
            var humidity = weatherData['rh-surface'][i].toFixed(0);
            forecastHtml += createWeatherParam('湿度', humidity + '%');
        }
        
        if (weatherData['pressure-surface'] && weatherData['pressure-surface'][i] !== null) {
            var pressure = weatherData['pressure-surface'][i].toFixed(0);
            forecastHtml += createWeatherParam('气压', pressure + ' hPa');
        }
        
        if (weatherData['gust-surface'] && weatherData['gust-surface'][i] !== null) {
            var gust = weatherData['gust-surface'][i].toFixed(1);
            forecastHtml += createWeatherParam('阵风', gust + ' m/s');
        }
        
        forecastHtml += '</div></div>';
        
        var contentElement = document.getElementById('weatherForecastContent');
        if (contentElement) {
            contentElement.innerHTML = forecastHtml;
        }
    }
    
    function displayWeatherError(message) {
        var contentElement = document.getElementById('weatherForecastContent');
        if (contentElement) {
            contentElement.innerHTML = 
                '<div class="weather-error">' +
                '<i class="layui-icon layui-icon-close"></i>' +
                '<p>' + message + '</p>' +
                '</div>';
        }
    }
    
    function createWeatherParam(label, value) {
        return '<div class="weather-param">' +
               '<span class="weather-param-label">' + label + '</span>' +
               '<span class="weather-param-value">' + value + '</span>' +
               '</div>';
    }
    
    function formatDateTime(date) {
        var month = (date.getMonth() + 1).toString().padStart(2, '0');
        var day = date.getDate().toString().padStart(2, '0');
        var hours = date.getHours().toString().padStart(2, '0');
        var minutes = date.getMinutes().toString().padStart(2, '0');
        
        return month + '-' + day + ' ' + hours + ':' + minutes;
    }
    
    function getWindDirection(u, v) {
        var angle = Math.atan2(-u, -v) * 180 / Math.PI;
        angle = (angle + 360) % 360;
        
        var directions = ['北', '东北', '东', '东南', '南', '西南', '西', '西北'];
        var index = Math.round(angle / 45) % 8;
        return directions[index];
    }
    
    function getWindDirectionFromDegrees(degrees) {
        if (degrees === null || degrees === undefined) return '无风';
        
        var directions = ['北', '东北', '东', '东南', '南', '西南', '西', '西北'];
        var index = Math.round(degrees / 45) % 8;
        return directions[index];
    }
    
    function isEnabled() {
        return weatherEnabled;
    }
    
    return {
        init: init,
        toggleWeatherForecast: toggleWeatherForecast,
        showWeatherForecast: showWeatherForecast,
        closeWeatherCard: closeWeatherCard,
        showPrevForecast: showPrevForecast,
        showNextForecast: showNextForecast,
        isEnabled: isEnabled
    };
})(); 