<!--
 * @Author: chris
 * @Date: 2025-08-25 15:51:13
 * @LastEditors: chris
 * @LastEditTime: 2025-09-04 11:02:47
-->
<script setup>
import { Sunny, Pouring, WindPower, Odometer, Sunrise, Guide } from '@element-plus/icons-vue';

// 使用proxy访问全局$echarts
const { proxy } = getCurrentInstance();
const echarts = proxy?.$echarts;

const props = defineProps({
  weatherInfo: {
    type: Object,
    default: () => ({
      // 默认模拟数据
      current: {
        temperature: 25.5,
        humidity: 65,
        windSpeed: 3.2,
        windDirection: '东北',
        rainfall: 0,
        pressure: 1013,
        uvIndex: 5,
        visibility: 10
      },
      forecast: Array(24).fill().map((_, index) => ({
        time: `${(new Date().getHours() + index) % 24}:00`,
        temperature: 20 + Math.sin(index / 3) * 8 + Math.random() * 2,
        humidity: 50 + Math.cos(index / 3) * 20 + Math.random() * 5,
        rainfall: Math.random() > 0.8 ? Math.random() * 2 : 0,
        windSpeed: 2 + Math.sin(index / 2) * 2 + Math.random() * 1,
        uvIndex: 3 + Math.sin(index / 4) * 3 + Math.random() * 1
      }))
    })
  },
});

const chartRef = ref(null);
let chartInstance = null;
// 当前选中的气象指标类型
const selectedMetric = ref('temperature');

// 气象指标配置
const metricConfig = {
  temperature: {
    name: '温度',
    unit: '°C',
    color: '#ff6b6b',
    dataKey: 'temperature',
    min: 0,
    max: 40,
    interval: 10,
    gradient: echarts ? new echarts.graphic.LinearGradient(0, 0, 0, 1, [
      { offset: 0, color: 'rgba(255, 107, 107, 0.5)' },
      { offset: 1, color: 'rgba(255, 107, 107, 0.1)' }
    ]) : null
  },
  humidity: {
    name: '湿度',
    unit: '%',
    color: '#4dabf7',
    dataKey: 'humidity',
    min: 0,
    max: 100,
    interval: 20,
    gradient: echarts ? new echarts.graphic.LinearGradient(0, 0, 0, 1, [
      { offset: 0, color: 'rgba(77, 171, 247, 0.5)' },
      { offset: 1, color: 'rgba(77, 171, 247, 0.1)' }
    ]) : null
  },
  windSpeed: {
    name: '风速',
    unit: 'm/s',
    color: '#00b894',
    dataKey: 'windSpeed',
    min: 0,
    max: 10,
    interval: 2,
    gradient: echarts ? new echarts.graphic.LinearGradient(0, 0, 0, 1, [
      { offset: 0, color: 'rgba(0, 184, 148, 0.5)' },
      { offset: 1, color: 'rgba(0, 184, 148, 0.1)' }
    ]) : null
  },
  rainfall: {
    name: '降雨量',
    unit: 'mm',
    color: '#74b9ff',
    dataKey: 'rainfall',
    min: 0,
    max: 10,
    interval: 2,
    gradient: echarts ? new echarts.graphic.LinearGradient(0, 0, 0, 1, [
      { offset: 0, color: 'rgba(116, 185, 255, 0.5)' },
      { offset: 1, color: 'rgba(116, 185, 255, 0.1)' }
    ]) : null
  },
  uvIndex: {
    name: '紫外线',
    unit: '级',
    color: '#fdcb6e',
    dataKey: 'uvIndex',
    min: 0,
    max: 10,
    interval: 2,
    gradient: echarts ? new echarts.graphic.LinearGradient(0, 0, 0, 1, [
      { offset: 0, color: 'rgba(253, 203, 110, 0.5)' },
      { offset: 1, color: 'rgba(253, 203, 110, 0.1)' }
    ]) : null
  }
};

// 处理指标点击事件
const handleMetricClick = (metric) => {
  selectedMetric.value = metric;
  updateChart();
};

// 初始化图表
const initChart = () => {
  if (chartRef.value && echarts) {
    // 销毁已存在的图表实例
    if (chartInstance) {
      chartInstance.dispose();
    }
    
    chartInstance = echarts.init(chartRef.value);
    updateChart();
  }
};

// 更新图表数据
const updateChart = () => {
  if (!chartInstance || !echarts || !props.weatherInfo.forecast) return;
  
  const config = metricConfig[selectedMetric.value];
  
  const option = {
    title: {
      text: `24小时${config.name}趋势`,
      textStyle: {
        color: '#fff',
        fontSize: 16,
        fontWeight: 'bold'
      },
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(0, 0, 0, 0.7)',
      borderColor: '#333',
      textStyle: {
        color: '#fff'
      },
      formatter: function(params) {
        const data = params[0];
        return `${data.name}<br/>${config.name}: ${data.value}${config.unit}`;
      },
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: props.weatherInfo.forecast.map(item => item.time),
      axisLine: {
        lineStyle: {
          color: '#464646'
        }
      },
      axisLabel: {
        color: '#ddd'
      }
    },
    yAxis: [
      {
        type: 'value',
        name: config.name,
        nameTextStyle: {
          color: '#ddd'
        },
        min: config.min,
        max: config.max,
        interval: config.interval,
        axisLine: {
          lineStyle: {
            color: '#464646'
          }
        },
        axisLabel: {
          color: '#ddd',
          formatter: `{value} ${config.unit}`
        },
        splitLine: {
          lineStyle: {
            color: '#2a2a2a',
            type: 'dashed'
          }
        }
      }
    ],
    series: [
      {
        name: `${config.name}(${config.unit})`,
        type: 'line',
        data: props.weatherInfo.forecast.map(item => {
          // 风速数据可能不完整，需要添加默认值
          if (selectedMetric.value === 'windSpeed' && typeof item[config.dataKey] === 'undefined') {
            return (2 + Math.sin(props.weatherInfo.forecast.indexOf(item) / 2) * 2).toFixed(1);
          }
          // 紫外线数据可能不完整，需要添加默认值
          if (selectedMetric.value === 'uvIndex' && typeof item[config.dataKey] === 'undefined') {
            return (3 + Math.sin(props.weatherInfo.forecast.indexOf(item) / 4) * 3).toFixed(1);
          }
          return item[config.dataKey] ? item[config.dataKey].toFixed(1) : '0';
        }),
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        itemStyle: {
          color: config.color
        },
        areaStyle: {
          color: config.gradient
        },
        emphasis: {
          focus: 'series'
        }
      }
    ]
  };
  
  chartInstance.setOption(option);
};

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

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

onMounted(() => {
  initChart();
  window.addEventListener('resize', handleResize);
});

// 组件卸载时清理资源
const onUnmounted = () => {
  window.removeEventListener('resize', handleResize);
  if (chartInstance) {
    chartInstance.dispose();
  }
};
</script>

<template>
  <div class="weather-info">
    <div class="info-list">
      <div class="info-item" :class="{ 'info-item-selected': selectedMetric === 'temperature' }" @click="handleMetricClick('temperature')">
        <div class="icon-container">
          <Sunrise class="icon" />
        </div>
        <div class="info-content">
          <div class="info-label">温度</div>
          <div class="info-value">{{ weatherInfo.current.temperature }}°C</div>
        </div>
      </div>
      
      <div class="info-item" :class="{ 'info-item-selected': selectedMetric === 'humidity' }" @click="handleMetricClick('humidity')">
        <div class="icon-container">
          <Odometer class="icon" />
        </div>
        <div class="info-content">
          <div class="info-label">湿度</div>
          <div class="info-value">{{ weatherInfo.current.humidity }}%</div>
        </div>
      </div>
      
      <div class="info-item" :class="{ 'info-item-selected': selectedMetric === 'windSpeed' }" @click="handleMetricClick('windSpeed')">
        <div class="icon-container">
          <WindPower class="icon" />
        </div>
        <div class="info-content">
          <div class="info-label">风速</div>
          <div class="info-value">{{ weatherInfo.current.windSpeed }} m/s</div>
        </div>
      </div>
      
      <div class="info-item">
        <div class="icon-container">
          <Guide class="icon" />
        </div>
        <div class="info-content">
          <div class="info-label">风向</div>
          <div class="info-value">{{ weatherInfo.current.windDirection }}</div>
        </div>
      </div>
      
      <div class="info-item" :class="{ 'info-item-selected': selectedMetric === 'rainfall' }" @click="handleMetricClick('rainfall')">
        <div class="icon-container">
          <Pouring class="icon" />
        </div>
        <div class="info-content">
          <div class="info-label">降雨量</div>
          <div class="info-value">{{ weatherInfo.current.rainfall }} mm</div>
        </div>
      </div>
      
      <div class="info-item" :class="{ 'info-item-selected': selectedMetric === 'uvIndex' }" @click="handleMetricClick('uvIndex')">
        <div class="icon-container">
          <Sunny class="icon" />
        </div>
        <div class="info-content">
          <div class="info-label">紫外线</div>
          <div class="info-value">{{ weatherInfo.current.uvIndex }}级</div>
        </div>
      </div>
    </div>
    
    <div class="info-chart">
      <div ref="chartRef" class="chart"></div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
// 定义SCSS变量
$primary-color: #4dabf7;
$hover-bg: rgba(255, 255, 255, 0.1);
$selected-bg: rgba(77, 171, 247, 0.2);
$border-radius: 12px;
$transition: all 0.3s ease;

// 使用UnoCSS的@apply语法
.weather-info {
  @apply rounded-xl p-5 shadow-lg h-full flex flex-col gap-5;
  // background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
}

.info-list {
  @apply grid grid-cols-[repeat(auto-fit,minmax(150px,1fr))] gap-3;
}

.info-item {
  @apply bg-[rgba(255,255,255,0.05)] rounded-lg p-[14px] flex items-center gap-2.5 backdrop-blur-sm border border-[rgba(255,255,255,0.1)] cursor-pointer transition-all duration-300;
  
  &:hover {
    @apply -translate-y-0.5 shadow-[0_4px_20px_rgba(255,255,255,0.1)] border-[rgba(255,255,255,0.2)];
  }
}

// 选中状态样式
.info-item-selected {
  @apply bg-[rgba(77,171,247,0.2)] border-$primary-color -translate-y-0.5 shadow-[0_4px_20px_rgba(77,171,247,0.3)];
  
  .icon {
    @apply text-$primary-color scale-110;
  }
}

.icon-container {
  @apply w-[48px] h-[48px] rounded-full bg-[rgba(255,255,255,0.1)] flex items-center justify-center text-base;
}

.icon {
  @apply w-5 h-5 text-$primary-color transition-all duration-300;
}

.info-content {
  @apply flex-1;
}

.info-label {
  @apply text-sm text-[#a0a0a0] mb-1;
}

.info-value {
  @apply text-xl font-bold text-white;
}

.info-chart {
  @apply flex-1 min-h-[300px];
}

.chart {
  @apply w-full h-full rounded-lg overflow-hidden;
}
</style>
