var WeatherForecast = (function() {
    'use strict';
    
    var weatherApiKey = 'Uxh4IdMuAvhSiBnsf4UUDVGF4e3YAp2B';
    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>请确保网络可访问 Windy API 服务</p>' +
                '<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 requestBody = {
            "lat": parseFloat(lat.toFixed(2)),
            "lon": parseFloat(lon.toFixed(2)),
            "model": "gfs",
            "parameters": ["temp", "wind", "precip", "pressure", "rh", "windGust"],
            "levels": ["surface"],
            "key": weatherApiKey,
            "hours": 72
        };
        
        fetch('https://api.windy.com/api/point-forecast/v2', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            body: JSON.stringify(requestBody)
        })
        .then(function(response) {
            if (!response.ok) {
                throw new Error('网络响应状态: ' + response.status);
            }
            return response.json();
        })
        .then(function(data) {
            weatherData = 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 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] - 273.15).toFixed(1);
            forecastHtml += createWeatherParam('温度', temp + '°C');
        }
        
        if (weatherData['wind_u-surface'] && weatherData['wind_v-surface'] && 
            weatherData['wind_u-surface'][i] !== null && weatherData['wind_v-surface'][i] !== null) {
            var windU = weatherData['wind_u-surface'][i];
            var windV = weatherData['wind_v-surface'][i];
            var windSpeed = Math.sqrt(windU * windU + windV * windV).toFixed(1);
            var windDir = getWindDirection(windU, windV);
            forecastHtml += createWeatherParam('风速', windSpeed + ' m/s');
            forecastHtml += createWeatherParam('风向', windDir);
        }
        
        if (weatherData['past3hprecip-surface'] && weatherData['past3hprecip-surface'][i] !== null) {
            var precip = weatherData['past3hprecip-surface'][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] / 100).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 isEnabled() {
        return weatherEnabled;
    }
    
    return {
        init: init,
        toggleWeatherForecast: toggleWeatherForecast,
        showWeatherForecast: showWeatherForecast,
        closeWeatherCard: closeWeatherCard,
        showPrevForecast: showPrevForecast,
        showNextForecast: showNextForecast,
        isEnabled: isEnabled
    };
})(); 