<!--
 * @Author: chris
 * @Date: 2025-08-25 15:51:13
 * @LastEditors: chris
 * @LastEditTime: 2025-10-14 15:36:47
-->
<script setup>
import { Sunny, Pouring, WindPower, Sunrise, Guide } from '@element-plus/icons-vue';
import { weatherTypes, weatherDict } from '../config.js';

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

const props = defineProps({
  weatherData: {
    type: Array,
    default: () => []
  }
});

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

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

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

// 更新图表数据
const updateChart = () => {
  if (!chartInstance || !echarts) return;
  
  const config = weatherDict[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: chartData.value.dates,
      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: chartData.value.values,
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        itemStyle: {
          color: config.color
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: `${config.color}40`
            },
            {
              offset: 1,
              color: `${config.color}10`
            }
          ])
        },
        emphasis: {
          focus: 'series'
        }
      }
    ]
  };
  
  chartInstance.setOption(option);
};

watch(() =>props.weatherData, (value) => {
  formateData.value = formatData(value)
  chartData.value = createChartData(formateData.value, selectedMetric.value)
  updateChart();
})

const liveData = computed(() => {
  const res ={}
  weatherTypes.forEach(type => {
    res[type] = formateData.value[type]?.[0] || '--'
  })
  return res
})

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

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

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

function createChartData(data, type) {
  const dates = []
  const values = []
  const typeList = data[type] || []
  typeList.forEach(item => {
    dates.push(proxy.$utils.formatTime(item.createTime, '{h}:{m}'))
    values.push(item.value)
  }) 
  return { dates, values }
}

function formatData(data) {
  const obj = {};
  const res = {};
  // data.sort((a,b) => soilTypes.indexOf(a.identifier) - soilTypes.indexOf(b.identifier))
  data.forEach(item => {
    const identifier = item.identifier;
    if (!identifier || identifier === 'null') return false;
    obj[identifier] ? obj[identifier].push(item) : (obj[identifier] = [item])
  })
  weatherTypes.forEach(type => {
    res[type] = obj[type] || []
  })
  return res;
}
</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">{{ liveData.Temperature }}°C</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">{{ liveData.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">{{ liveData.WindDirection }}</div>
        </div>
      </div>
      
      <div class="info-item" :class="{ 'info-item-selected': selectedMetric === 'DailyRainfall' }" @click="handleMetricClick('DailyRainfall')">
        <div class="icon-container">
          <Pouring class="icon" />
        </div>
        <div class="info-content">
          <div class="info-label">降雨量</div>
          <div class="info-value">{{ liveData.DailyRainfall }} mm</div>
        </div>
      </div>
      
      <div class="info-item" :class="{ 'info-item-selected': selectedMetric === 'Illuminance' }" @click="handleMetricClick('Illuminance')">
        <div class="icon-container">
          <Sunny class="icon" />
        </div>
        <div class="info-content">
          <div class="info-label">光照</div>
          <div class="info-value">{{ liveData.Illuminance }}级</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>
