<?php
$pageTitle = '天气查询';
require_once 'header.php';

$city = $_GET['city'] ?? '阳泉';
$default_cities = ['阳泉', '杭州', '丽江', '上海', '太原', '石家庄', '南京', '晋城', '北京'];
?>

<main class="site-main">

    <section class="page-banner">
        <div class="container">
            <h1>🌤 天气查询</h1>
            <p>提前掌握婚礼当天天气，做好万全准备</p>
        </div>
    </section>

    <section class="weather-section">
        <div class="container">
            <div class="weather-search-area">
                <form method="get" action="weather.php" class="weather-search-form">
                    <div class="weather-input-group">
                        <input type="text" name="city" value="<?php echo htmlspecialchars($city); ?>" placeholder="输入城市名称查询天气..." class="weather-search-input">
                        <button type="submit" class="btn btn-primary weather-search-btn">🔍 查询</button>
                    </div>
                    <div class="weather-city-tags">
                        <?php foreach ($default_cities as $c): ?>
                        <a href="?city=<?php echo urlencode($c); ?>" class="city-tag <?php echo $city === $c ? 'active' : ''; ?>"><?php echo $c; ?></a>
                        <?php endforeach; ?>
                    </div>
                </form>
            </div>

            <div class="weather-display-area">
                <div class="weather-info-card">
                    <div class="weather-card-header">
                        <h2><?php echo htmlspecialchars($city); ?> · 实时天气</h2>
                        <span class="weather-update-time">更新于 <?php echo date('Y-m-d H:i'); ?></span>
                    </div>

                    <div class="weather-main-display">
                        <div class="weather-icon-big" id="weatherIcon">☀️</div>
                        <div class="weather-temp-big">
                            <span class="temp-number" id="weatherTemp">--</span>
                            <span class="temp-unit">°C</span>
                        </div>
                        <div class="weather-desc" id="weatherDesc">加载中...</div>
                    </div>

                    <div class="weather-details" id="weatherDetails">
                        <div class="weather-detail-item">
                            <span class="detail-icon">💧</span>
                            <span class="detail-label">湿度</span>
                            <span class="detail-value" id="weatherHumidity">--%</span>
                        </div>
                        <div class="weather-detail-item">
                            <span class="detail-icon">🌬</span>
                            <span class="detail-label">风力</span>
                            <span class="detail-value" id="weatherWind">--</span>
                        </div>
                        <div class="weather-detail-item">
                            <span class="detail-icon">👁</span>
                            <span class="detail-label">能见度</span>
                            <span class="detail-value" id="weatherVisibility">--</span>
                        </div>
                        <div class="weather-detail-item">
                            <span class="detail-icon">☁️</span>
                            <span class="detail-label">气压</span>
                            <span class="detail-value" id="weatherPressure">--</span>
                        </div>
                    </div>
                </div>

                <div class="weather-forecast-card">
                    <h3>📅 未来天气预报</h3>
                    <div class="forecast-grid" id="forecastGrid">
                        <?php for ($i = 1; $i <= 5; $i++): ?>
                        <div class="forecast-item">
                            <div class="forecast-date"><?php echo date('m/d', strtotime("+$i day")); ?></div>
                            <div class="forecast-icon">🌈</div>
                            <div class="forecast-temp">
                                <span class="forecast-high">--°</span>
                                <span class="forecast-low">--°</span>
                            </div>
                            <div class="forecast-desc">加载中</div>
                        </div>
                        <?php endfor; ?>
                    </div>
                </div>
            </div>

            <div class="weather-tips">
                <h3>💡 婚礼天气应对指南</h3>
                <div class="weather-tips-grid">
                    <div class="weather-tip-card">
                        <div class="weather-tip-icon">☀️</div>
                        <h4>晴天</h4>
                        <p>理想天气！户外仪式注意防晒，准备遮阳伞和水。新娘妆容注意防汗定妆。</p>
                    </div>
                    <div class="weather-tip-card">
                        <div class="weather-tip-icon">🌧</div>
                        <h4>雨天</h4>
                        <p>准备透明雨伞（拍照好看），搭建防雨棚。婚鞋多备一双，婚纱裙摆注意防泥。</p>
                    </div>
                    <div class="weather-tip-card">
                        <div class="weather-tip-icon">❄️</div>
                        <h4>寒冷</h4>
                        <p>准备暖宝宝、披肩外套。婚车提前热车。室内温度提前调试好，准备热饮。</p>
                    </div>
                    <div class="weather-tip-card">
                        <div class="weather-tip-icon">🌪</div>
                        <h4>大风</h4>
                        <p>头纱和裙摆固定技巧要做好。户外布置物品加重加固。发型多用定型产品。</p>
                    </div>
                </div>
            </div>
        </div>
    </section>

</main>

<script>
(function() {
    var city = <?php echo json_encode($city); ?>;
    var loadingHtml = '<div style="text-align:center;padding:20px;color:#999;">⏳ 正在获取真实天气数据...</div>';

    function fetchWeather() {
        document.getElementById('weatherDesc').textContent = '加载中...';
        document.getElementById('forecastGrid').innerHTML = loadingHtml;

        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'api/api_router.php/weather/all?city=' + encodeURIComponent(city), true);
        xhr.timeout = 15000;
        xhr.onload = function() {
            if (xhr.status === 200) {
                try {
                    var resp = JSON.parse(xhr.responseText);
                    if (resp.success && resp.data) {
                        renderWeather(resp.data);
                    } else {
                        renderMockWeather();
                    }
                } catch(e) {
                    renderMockWeather();
                }
            } else {
                renderMockWeather();
            }
        };
        xhr.onerror = function() {
            renderMockWeather();
        };
        xhr.ontimeout = function() {
            renderMockWeather();
        };
        xhr.send();
    }

    function renderWeather(data) {
        var current = data.current;
        var forecast = data.forecast;
        var source = data.source || 'unknown';

        if (current) {
            document.getElementById('weatherIcon').textContent = current.icon || '🌈';
            document.getElementById('weatherTemp').textContent = current.temperature;
            document.getElementById('weatherDesc').textContent = current.condition || '--';
            document.getElementById('weatherHumidity').textContent = (current.humidity !== undefined && current.humidity !== null ? current.humidity : '--') + (typeof current.humidity === 'number' ? '%' : '');
            document.getElementById('weatherWind').textContent = current.wind || '--';
            document.getElementById('weatherVisibility').textContent = current.visibility || '--';
            document.getElementById('weatherPressure').textContent = current.pressure || '--';

            var updateTime = current.last_update || '';
            if (source) {
                updateTime += ' (数据源: ' + source + ')';
            }
            document.querySelector('.weather-update-time').textContent = '更新于 ' + updateTime;
        }

        if (forecast && forecast.forecasts && forecast.forecasts.length > 0) {
            var forecastHtml = '';
            for (var i = 0; i < forecast.forecasts.length; i++) {
                var f = forecast.forecasts[i];
                var dateStr = f.date || '';
                if (dateStr.length >= 10) {
                    var parts = dateStr.split('-');
                    dateStr = parts[1] + '/' + parts[2];
                }
                forecastHtml += '<div class="forecast-item">' +
                    '<div class="forecast-date">' + dateStr + '</div>' +
                    '<div class="forecast-icon">' + (f.icon || '🌈') + '</div>' +
                    '<div class="forecast-temp">' +
                    '<span class="forecast-high">' + f.high + '°</span>' +
                    '<span class="forecast-low">' + f.low + '°</span>' +
                    '</div>' +
                    '<div class="forecast-desc">' + (f.condition || '') + '</div>' +
                    '</div>';
            }
            document.getElementById('forecastGrid').innerHTML = forecastHtml;
        }
    }

    function renderMockWeather() {
        var mockData = getMockWeatherData(city);
        document.getElementById('weatherIcon').textContent = mockData.icon;
        document.getElementById('weatherTemp').textContent = mockData.temp;
        document.getElementById('weatherDesc').textContent = mockData.desc + ' (模拟数据)';
        document.getElementById('weatherHumidity').textContent = mockData.humidity + '%';
        document.getElementById('weatherWind').textContent = mockData.wind;
        document.getElementById('weatherVisibility').textContent = mockData.visibility;
        document.getElementById('weatherPressure').textContent = mockData.pressure;

        var forecastHtml = '';
        for (var i = 0; i < mockData.forecast.length; i++) {
            var f = mockData.forecast[i];
            forecastHtml += '<div class="forecast-item">' +
                '<div class="forecast-date">' + f.date + '</div>' +
                '<div class="forecast-icon">' + f.icon + '</div>' +
                '<div class="forecast-temp">' +
                '<span class="forecast-high">' + f.high + '°</span>' +
                '<span class="forecast-low">' + f.low + '°</span>' +
                '</div>' +
                '<div class="forecast-desc">' + f.desc + '</div>' +
                '</div>';
        }
        document.getElementById('forecastGrid').innerHTML = forecastHtml;
    }

    function getMockWeatherData(cityName) {
        var seed = 0;
        for (var i = 0; i < cityName.length; i++) {
            seed += cityName.charCodeAt(i);
        }
        var month = new Date().getMonth() + 1;

        var icons = ['☀️', '⛅', '☁️', '🌤', '🌦', '🌧', '⛈', '🌨'];
        var descs = ['晴', '晴间多云', '多云', '晴朗', '阵雨', '小雨', '雷阵雨', '阴天'];
        var iconIndex = seed % icons.length;

        var baseTemp = month >= 4 && month <= 10 ? 22 + (seed % 10) : 5 + (seed % 10);
        var today = new Date();

        var forecast = [];
        for (var i = 0; i < 5; i++) {
            var fDate = new Date(today);
            fDate.setDate(fDate.getDate() + i + 1);
            var fIconIndex = (seed + i) % icons.length;
            var high = baseTemp + ((seed + i * 3) % 5) - 2;
            var low = baseTemp - 4 + ((seed + i * 2) % 4);
            forecast.push({
                date: ('0' + (fDate.getMonth() + 1)).slice(-2) + '/' + ('0' + fDate.getDate()).slice(-2),
                icon: icons[fIconIndex],
                high: high,
                low: low,
                desc: descs[fIconIndex]
            });
        }

        return {
            icon: icons[iconIndex],
            temp: baseTemp,
            desc: descs[iconIndex],
            humidity: 40 + (seed % 45),
            wind: '北风 ' + (2 + seed % 4) + '级',
            visibility: (8 + seed % 12) + 'km',
            pressure: (1010 + seed % 20) + 'hPa',
            forecast: forecast
        };
    }

    fetchWeather();
})();
</script>

<?php require_once 'footer.php'; ?>