{% extends 'base.html' %}
{% block content %}
    <meta name="referrer" content="no-referrer-when-downgrade">

<div class="container-fluid" style="background: #12122b; color: #fff; border-radius: 20px; padding: 25px; margin-top: 10px;">
    <div class="row mb-4">
        <div class="col-12 d-flex justify-content-between align-items-center">
            <h3 class="fw-bold text-transparent bg-clip-text bg-gradient-to-r from-blue-400 to-purple-500">
                <i class="bi bi-broadcast me-2 text-primary"></i>全国茄子病虫害监测大数据中心
            </h3>
            <div id="refresh-status" class="badge bg-primary-subtle text-primary rounded-pill px-3 py-2">
                <span class="spinner-grow spinner-grow-sm me-2"></span>实时数据同步中...
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-lg-4">
            <div class="card bg-dark text-white border-secondary mb-4 p-3 shadow-lg chart-card">
                <h5 class="fw-bold"><i class="bi bi-pie-chart me-2 text-info"></i>病虫害构成</h5>
                <div id="diseasePie" style="height: 300px;"></div>
            </div>

            <div class="card bg-dark text-white border-secondary p-3 shadow-lg chart-card">
                <h5 class="fw-bold"><i class="bi bi-graph-up me-2 text-success"></i>全网监测趋势</h5>
                <div id="trendLine" style="height: 300px;"></div>
            </div>
        </div>

        <div class="col-lg-8">
            <div class="card bg-dark text-white border-secondary p-3 shadow-lg h-100 map-card">
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <h5 class="fw-bold m-0"><i class="bi bi-geo-alt me-2 text-danger"></i>全量用户病虫害地理分布</h5>
                    <small class="text-muted">数据来源：所有注册农户实时上传</small>
                </div>
                <div id="mainMap" style="height: 650px; border-radius: 15px; border: 1px solid #333;"></div>
            </div>
        </div>
    </div>
</div>

<style>
    .chart-card, .map-card {
        background-color: rgba(30, 30, 50, 0.6) !important;
        backdrop-filter: blur(10px);
        transition: transform 0.3s ease;
    }
    .chart-card:hover { transform: translateY(-5px); }
    .leaflet-popup-content-wrapper { background: rgba(255,255,255,0.9); border-radius: 10px; }
    .bg-clip-text { -webkit-background-clip: text; background-clip: text; color: transparent; background-image: linear-gradient(to right, #60a5fa, #a855f7); }
</style>

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>

<script>
    document.addEventListener('DOMContentLoaded', function() {

        var map = L.map('mainMap').setView([36.65, 118.5], 7);
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; OpenStreetMap'
        }).addTo(map);

        var pieChart = echarts.init(document.getElementById('diseasePie'));
        var lineChart = echarts.init(document.getElementById('trendLine'));

        function updateDashboard() {
            fetch('/api/dashboard_data/')
                .then(res => res.json())
                .then(data => {

                    map.eachLayer((layer) => {
                        if (layer instanceof L.CircleMarker) map.removeLayer(layer);
                    });
                    data.map_points.forEach(p => {
                        L.circleMarker([p.latitude, p.longitude], {
                            radius: 7, color: '#ff4757', fillColor: '#ff4757', fillOpacity: 0.8, weight: 1
                        }).bindPopup(`
                            <div style="color:#333; font-family: 'Noto Sans SC';">
                                <b class="text-danger">监测发现：${p.description}</b><br>
                                <small class="text-muted">坐标：${p.longitude.toFixed(3)}, ${p.latitude.toFixed(3)}</small><br>
                                <hr class="my-1">
                                <span>上传时间：${new Date(p.created_at).toLocaleString()}</span>
                            </div>
                        `).addTo(map);
                    });

                    pieChart.setOption({
                        tooltip: { trigger: 'item', formatter: '{b}: {c}次 ({d}%)' },
                        legend: {
                            type: 'scroll',
                            orient: 'horizontal',
                            bottom: '1%',
                            left: 'center',
                            textStyle: { color: '#ccc' },
                            icon: 'circle',
                            itemGap: 20
                        },
                        color: ['#ff4757', '#ffa502', '#2ed573', '#1e90ff', '#eccc68'],
                        series: [{
                            name: '病虫害占比',
                            type: 'pie',
                            radius: ['30%', '55%'],
                            roseType: 'radius',
                            center: ['50%', '50%'],
                            itemStyle: { borderRadius: 10, borderColor: '#12122b', borderWidth: 2 },
                            label: { show: true, color: '#fff', formatter: '{d}%', position: 'outside'},
                            data: data.disease_stats.map(i => ({name: i.description, value: i.count}))
                        }]
                    });

                    lineChart.setOption({
                        tooltip: { trigger: 'axis', axisPointer: { type: 'cross', label: { backgroundColor: '#6a7985' } } },
                        grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
                        xAxis: [{
                            type: 'category', boundaryGap: false,
                            data: data.trend_stats.map(i => i.date),
                            axisLabel: { color: '#888' }
                        }],
                        yAxis: [{ type: 'value', splitLine: { lineStyle: { color: '#333' } }, axisLabel: { color: '#888' } }],
                        series: [{
                            name: '每日监测次数',
                            type: 'line',
                            smooth: true,
                            lineStyle: { width: 3, color: '#2ed573' },
                            showSymbol: false,
                            areaStyle: {
                                opacity: 0.8,
                                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                    { offset: 0, color: 'rgba(46, 213, 115, 0.4)' },
                                    { offset: 1, color: 'rgba(46, 213, 115, 0)' }
                                ])
                            },
                            data: data.trend_stats.map(i => i.count)
                        }]
                    });
                });
        }

        updateDashboard();

        setInterval(updateDashboard, 30000);

        window.addEventListener('resize', function() {
            pieChart.resize();
            lineChart.resize();
        });
    });
</script>
{% endblock %}