<template>
  <div class="environment-chart">
    <a-card title="环境监测数据" :bordered="false">
      <div class="chart-controls">
        <a-space>
          <a-select v-model:value="timeRange" @change="handleTimeRangeChange" style="width: 120px">
            <a-select-option value="24h">近24小时</a-select-option>
            <a-select-option value="7d">近7天</a-select-option>
            <a-select-option value="30d">近30天</a-select-option>
          </a-select>
          <a-checkbox-group v-model:value="selectedMetrics" @change="handleMetricsChange">
            <a-checkbox value="temperature">温度</a-checkbox>
            <a-checkbox value="humidity">湿度</a-checkbox>
            <a-checkbox value="airQuality">空气质量</a-checkbox>
            <a-checkbox value="soilMoisture">土壤湿度</a-checkbox>
          </a-checkbox-group>
        </a-space>
      </div>
      <div ref="chartContainer" class="chart-container"></div>
      
      <!-- 实时数据卡片 -->
      <div class="realtime-data">
        <a-row :gutter="16">
          <a-col :span="6">
            <a-statistic
              title="当前温度"
              :value="realtimeData.temperature"
              suffix="°C"
              :value-style="{ color: getTemperatureColor(realtimeData.temperature) }"
            />
          </a-col>
          <a-col :span="6">
            <a-statistic
              title="当前湿度"
              :value="realtimeData.humidity"
              suffix="%"
              :value-style="{ color: getHumidityColor(realtimeData.humidity) }"
            />
          </a-col>
          <a-col :span="6">
            <a-statistic
              title="空气质量指数"
              :value="realtimeData.airQuality"
              :value-style="{ color: getAirQualityColor(realtimeData.airQuality) }"
            />
          </a-col>
          <a-col :span="6">
            <a-statistic
              title="土壤湿度"
              :value="realtimeData.soilMoisture"
              suffix="%"
              :value-style="{ color: getSoilMoistureColor(realtimeData.soilMoisture) }"
            />
          </a-col>
        </a-row>
      </div>
    </a-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue';
import * as echarts from 'echarts';
import { environmentAPI } from '../../services/api.js';

const chartContainer = ref(null);
const timeRange = ref('24h');
const selectedMetrics = ref(['temperature', 'humidity', 'airQuality', 'soilMoisture']);
let chartInstance = null;

const chartData = ref({
  timestamps: [],
  temperature: [],
  humidity: [],
  airQuality: [],
  soilMoisture: []
});

const realtimeData = ref({
  temperature: 22.5,
  humidity: 65,
  airQuality: 85,
  soilMoisture: 45
});

const loading = ref(false);

// 初始化图表
const initChart = () => {
  if (chartContainer.value) {
    chartInstance = echarts.init(chartContainer.value);
    updateChart();
    
    // 监听窗口大小变化
    window.addEventListener('resize', handleResize);
  }
};

// 更新图表
const updateChart = () => {
  if (!chartInstance || !chartData.value.timestamps.length) return;

  const series = [];
  const yAxes = [];
  let yAxisIndex = 0;

  // 温度系列
  if (selectedMetrics.value.includes('temperature')) {
    series.push({
      name: '温度',
      type: 'line',
      yAxisIndex: yAxisIndex,
      data: chartData.value.temperature,
      itemStyle: { color: '#ff4d4f' },
      smooth: true
    });
    yAxes.push({
      type: 'value',
      name: '温度(°C)',
      position: yAxisIndex % 2 === 0 ? 'left' : 'right',
      axisLabel: {
        formatter: '{value}°C'
      },
      splitLine: { show: yAxisIndex === 0 }
    });
    yAxisIndex++;
  }

  // 湿度系列
  if (selectedMetrics.value.includes('humidity')) {
    series.push({
      name: '湿度',
      type: 'line',
      yAxisIndex: yAxisIndex,
      data: chartData.value.humidity,
      itemStyle: { color: '#1890ff' },
      smooth: true
    });
    yAxes.push({
      type: 'value',
      name: '湿度(%)',
      position: yAxisIndex % 2 === 0 ? 'left' : 'right',
      axisLabel: {
        formatter: '{value}%'
      },
      splitLine: { show: false }
    });
    yAxisIndex++;
  }

  // 空气质量系列
  if (selectedMetrics.value.includes('airQuality')) {
    series.push({
      name: '空气质量',
      type: 'line',
      yAxisIndex: yAxisIndex,
      data: chartData.value.airQuality,
      itemStyle: { color: '#52c41a' },
      smooth: true
    });
    yAxes.push({
      type: 'value',
      name: '空气质量指数',
      position: yAxisIndex % 2 === 0 ? 'left' : 'right',
      axisLabel: {
        formatter: '{value}'
      },
      splitLine: { show: false }
    });
    yAxisIndex++;
  }

  // 土壤湿度系列
  if (selectedMetrics.value.includes('soilMoisture')) {
    series.push({
      name: '土壤湿度',
      type: 'line',
      yAxisIndex: yAxisIndex,
      data: chartData.value.soilMoisture,
      itemStyle: { color: '#faad14' },
      smooth: true
    });
    yAxes.push({
      type: 'value',
      name: '土壤湿度(%)',
      position: yAxisIndex % 2 === 0 ? 'left' : 'right',
      axisLabel: {
        formatter: '{value}%'
      },
      splitLine: { show: false }
    });
  }

  const option = {
    title: {
      text: '环境监测趋势',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      },
      formatter: function(params) {
        let result = `<div style="font-weight: bold; margin-bottom: 5px;">${params[0].axisValue}</div>`;
        params.forEach(param => {
          let unit = '';
          if (param.seriesName === '温度') unit = '°C';
          else if (param.seriesName === '湿度' || param.seriesName === '土壤湿度') unit = '%';
          
          result += `<div style="margin: 2px 0;">
            <span style="display: inline-block; width: 10px; height: 10px; background-color: ${param.color}; border-radius: 50%; margin-right: 5px;"></span>
            ${param.seriesName}: ${param.value}${unit}
          </div>`;
        });
        return result;
      }
    },
    legend: {
      data: selectedMetrics.value.map(metric => {
        const names = {
          temperature: '温度',
          humidity: '湿度',
          airQuality: '空气质量',
          soilMoisture: '土壤湿度'
        };
        return names[metric];
      }),
      top: 30
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: chartData.value.timestamps,
      axisLabel: {
        formatter: function(value) {
          const date = new Date(value);
          if (timeRange.value === '24h') {
            return echarts.format.formatTime('hh:mm', date);
          } else {
            return echarts.format.formatTime('MM-dd', date);
          }
        }
      }
    },
    yAxis: yAxes,
    series: series
  };

  chartInstance.setOption(option);
};

// 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    const response = await environmentAPI.getChartData({
      timeRange: timeRange.value,
      metrics: selectedMetrics.value
    });

    if (response.success) {
      chartData.value = response.data.historical;
      realtimeData.value = response.data.realtime;
      await nextTick();
      updateChart();
    } else {
      // 使用模拟数据
      generateMockData();
    }
  } catch (error) {
    console.error('加载环境监测数据失败:', error);
    generateMockData();
  } finally {
    loading.value = false;
  }
};

// 生成模拟数据
const generateMockData = () => {
  const points = timeRange.value === '24h' ? 24 : timeRange.value === '7d' ? 7 * 24 : 30 * 24;
  const interval = timeRange.value === '24h' ? 1 : timeRange.value === '7d' ? 1 : 1; // 小时间隔
  
  const timestamps = [];
  const temperature = [];
  const humidity = [];
  const airQuality = [];
  const soilMoisture = [];

  for (let i = points - 1; i >= 0; i--) {
    const date = new Date();
    date.setHours(date.getHours() - i * interval);
    timestamps.push(date.toISOString());
    
    // 模拟环境数据 - 添加一些周期性和随机性
    const hourOfDay = date.getHours();
    const dayOfYear = Math.floor((date - new Date(date.getFullYear(), 0, 0)) / (1000 * 60 * 60 * 24));
    
    // 温度：白天高，夜晚低，夏季高，冬季低
    const baseTemp = 20 + 10 * Math.sin((dayOfYear / 365) * 2 * Math.PI); // 季节变化
    const dailyTemp = baseTemp + 8 * Math.sin((hourOfDay / 24) * 2 * Math.PI); // 日变化
    temperature.push(Math.round((dailyTemp + (Math.random() - 0.5) * 4) * 10) / 10);
    
    // 湿度：与温度相反的趋势
    const baseHumidity = 60 + 20 * Math.sin(((dayOfYear + 180) / 365) * 2 * Math.PI);
    const dailyHumidity = baseHumidity + 15 * Math.sin(((hourOfDay + 12) / 24) * 2 * Math.PI);
    humidity.push(Math.round(Math.max(30, Math.min(90, dailyHumidity + (Math.random() - 0.5) * 10))));
    
    // 空气质量：随机波动，偶尔有污染
    const baseAQ = 80 + (Math.random() - 0.5) * 30;
    const pollution = Math.random() < 0.1 ? -30 : 0; // 10%概率有污染
    airQuality.push(Math.round(Math.max(20, Math.min(100, baseAQ + pollution))));
    
    // 土壤湿度：相对稳定，偶尔有灌溉
    const baseSoil = 45 + (Math.random() - 0.5) * 10;
    const irrigation = Math.random() < 0.05 ? 20 : 0; // 5%概率有灌溉
    soilMoisture.push(Math.round(Math.max(20, Math.min(80, baseSoil + irrigation))));
  }

  chartData.value = {
    timestamps,
    temperature,
    humidity,
    airQuality,
    soilMoisture
  };

  // 更新实时数据为最新值
  realtimeData.value = {
    temperature: temperature[temperature.length - 1],
    humidity: humidity[humidity.length - 1],
    airQuality: airQuality[airQuality.length - 1],
    soilMoisture: soilMoisture[soilMoisture.length - 1]
  };

  updateChart();
};

// 处理时间范围变化
const handleTimeRangeChange = () => {
  loadData();
};

// 处理指标选择变化
const handleMetricsChange = () => {
  updateChart();
};

// 处理窗口大小变化
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};

// 获取温度颜色
const getTemperatureColor = (temp) => {
  if (temp < 10) return '#1890ff';
  if (temp < 25) return '#52c41a';
  if (temp < 35) return '#faad14';
  return '#ff4d4f';
};

// 获取湿度颜色
const getHumidityColor = (humidity) => {
  if (humidity < 40) return '#ff4d4f';
  if (humidity < 70) return '#52c41a';
  return '#1890ff';
};

// 获取空气质量颜色
const getAirQualityColor = (aqi) => {
  if (aqi >= 80) return '#52c41a';
  if (aqi >= 60) return '#faad14';
  return '#ff4d4f';
};

// 获取土壤湿度颜色
const getSoilMoistureColor = (moisture) => {
  if (moisture < 30) return '#ff4d4f';
  if (moisture < 60) return '#faad14';
  return '#52c41a';
};

onMounted(() => {
  nextTick(() => {
    initChart();
    loadData();
  });
});

onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose();
  }
  window.removeEventListener('resize', handleResize);
});

// 监听数据变化
watch(() => chartData.value, () => {
  updateChart();
}, { deep: true });

watch(() => selectedMetrics.value, () => {
  updateChart();
}, { deep: true });
</script>

<style scoped>
.environment-chart {
  width: 100%;
  height: 100%;
}

.chart-controls {
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  width: 100%;
  height: 400px;
  margin-bottom: 20px;
}

.realtime-data {
  background: #fafafa;
  padding: 16px;
  border-radius: 6px;
}

:deep(.ant-card-head-title) {
  font-size: 16px;
  font-weight: 500;
}

:deep(.ant-card-body) {
  padding: 20px;
}

:deep(.ant-statistic-title) {
  font-size: 12px;
  color: #666;
}

:deep(.ant-statistic-content) {
  font-size: 18px;
  font-weight: 600;
}
</style>