<template>
  <div class="dashboard-container">
    <el-row :gutter="20">
      
      <el-col :span="8" :xs="24">
        <el-card shadow="hover" class="dashboard-card">
          <template #header>
            <div class="card-header">
              <div class="title-group">
                <el-icon class="icon-blue"><PieChart /></el-icon>
                <span class="title">提出建议领域分布</span>
              </div>
              <span class="link">查看数据源 ></span>
            </div>
          </template>
          
          <div class="card-body">
            <div class="filter-row">
              <el-select v-model="yearLeft" size="small" class="year-select">
                <el-option label="2025年" value="2025" />
                <el-option label="2024年" value="2024" />
              </el-select>
            </div>
            <div ref="leftChartRef" class="chart-container"></div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="8" :xs="24">
        <el-card shadow="hover" class="dashboard-card">
          <template #header>
            <div class="card-header">
              <div class="title-group">
                <el-icon class="icon-orange"><Flag /></el-icon>
                <span class="title">相关政策领域分布</span>
              </div>
              <span class="link">查看数据源 ></span>
            </div>
          </template>

          <div class="card-body">
            <div class="filter-row">
              <el-select v-model="yearMiddle" size="small" class="year-select">
                <el-option label="2025年" value="2025" />
                <el-option label="2024年" value="2024" />
              </el-select>
            </div>
            
            <div class="policy-list">
              <div v-for="(item, index) in currentPolicyList" :key="index" class="policy-item">
                <div class="item-label">
                  <span class="dot" :style="{ backgroundColor: item.color }"></span>
                  <span class="name">{{ item.name }}</span>
                </div>
                <div class="progress-track">
                  <div 
                    class="progress-bar" 
                    :style="{ width: item.percent + '%', backgroundColor: item.color }"
                  ></div>
                </div>
                <div class="item-value">
                  <span class="count">{{ item.current }}项 / {{ item.total }}项</span>
                  <span class="percent">{{ item.percent }}%</span>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="8" :xs="24">
        <el-card shadow="hover" class="dashboard-card">
          <template #header>
            <div class="card-header">
              <div class="title-group">
                <el-icon class="icon-orange"><TrendCharts /></el-icon>
                <span class="title">热门研究方向变化趋势</span>
              </div>
              <span class="link">查看数据源 ></span>
            </div>
          </template>

          <div class="card-body">
            <div class="filter-row right-filter">
              <el-select v-model="yearRight" size="small" class="year-select">
                <el-option label="2025年" value="2025" />
                <el-option label="2024年" value="2024" />
              </el-select>
            </div>
            <div ref="rightChartRef" class="chart-container"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick, watch, computed } from 'vue'
import { PieChart, Flag, TrendCharts } from '@element-plus/icons-vue'
import * as echarts from 'echarts'

// ==================== 1. 模拟数据源 (Mock Data) ====================

// 视觉颜色常量 (为了还原图片，不同图表用了不同色系)
const COLORS = {
  pie: ['#409EFF', '#F56C6C', '#a0cfff', '#E6A23C', '#b3e19d', '#d1edc4', '#909399'],
  line: {
    ic: '#409EFF',      // 集成电路
    ai: '#67C23A',      // 人工智能 (青绿)
    comm: '#8e44ad',    // 通信 (紫)
    quantum: '#E6A23C', // 量子 (橙)
    bio: '#a0cfff',     // 生物 (淡蓝)
    energy: '#F56C6C'   // 能源 (红)
  }
}

const mockDatabase = {
  '2025': {
    // 左侧环形图数据
    pieData: [
      { value: 50, name: '集成电路' },
      { value: 46, name: '人工智能' },
      { value: 40, name: '通信网络' },
      { value: 32, name: '量子科技' },
      { value: 31, name: '生物科技' },
      { value: 30, name: '能源' },
      { value: 24, name: '其他' }
    ],
    // 中间列表数据
    policyData: [
      { name: '集成电路', current: 2, total: 10, percent: 20, color: '#c0392b' },
      { name: '人工智能', current: 1, total: 6, percent: 17, color: '#2e7d32' },
      { name: '通信网络', current: 2, total: 7, percent: 26, color: '#f39c12' },
      { name: '量子科技', current: 1, total: 2, percent: 50, color: '#c0392b' },
      { name: '生物科技', current: 3, total: 7, percent: 43, color: '#c0392b' },
      { name: '能源',     current: 11, total: 20, percent: 55, color: '#c0392b' }
    ],
    // 右侧折线图数据
    lineData: {
      xAxis: ['2023\nQ1', '2023\nQ3', '2024\nQ1', '2024\nQ3', '2025\nQ1', '2025\nQ3'],
      series: {
        '集成电路': [32, 13, 20, 28, 37, 40],
        '量子科技': [29, 18, 15, 19, 14, 9],
        '生物科技': [15, 17, 24, 23, 16, 24],
        '能源':     [20, 22, 12, 14, 19, 5],
        '通信网络': [3, 3, 1, 6, 4, 2],
        '人工智能': [5, 15, 25, 10, 15, 18]
      }
    }
  },
  '2024': {
    pieData: [
      { value: 40, name: '集成电路' },
      { value: 35, name: '人工智能' },
      { value: 45, name: '通信网络' },
      { value: 20, name: '量子科技' },
      { value: 25, name: '生物科技' },
      { value: 35, name: '能源' },
      { value: 15, name: '其他' }
    ],
    policyData: [
      { name: '集成电路', current: 5, total: 8, percent: 62, color: '#c0392b' },
      { name: '人工智能', current: 3, total: 5, percent: 60, color: '#2e7d32' },
      { name: '通信网络', current: 1, total: 10, percent: 10, color: '#f39c12' },
      { name: '量子科技', current: 0, total: 2, percent: 0, color: '#c0392b' },
      { name: '生物科技', current: 4, total: 6, percent: 66, color: '#c0392b' },
      { name: '能源',     current: 8, total: 15, percent: 53, color: '#c0392b' }
    ],
    lineData: {
      xAxis: ['2022\nQ1', '2022\nQ3', '2023\nQ1', '2023\nQ3', '2024\nQ1', '2024\nQ3'],
      series: {
        '集成电路': [10, 20, 25, 30, 35, 32],
        '量子科技': [5, 8, 12, 15, 20, 29],
        '生物科技': [20, 18, 15, 17, 15, 15],
        '能源':     [15, 14, 18, 20, 22, 12],
        '通信网络': [8, 7, 6, 5, 3, 1],
        '人工智能': [12, 18, 20, 22, 15, 25]
      }
    }
  }
}

// ==================== 2. 状态管理 ====================

const yearLeft = ref('2025')
const yearMiddle = ref('2025')
const yearRight = ref('2025')

const leftChartRef = ref(null)
const rightChartRef = ref(null)
let leftChart = null
let rightChart = null

// 计算属性：获取当前中间列表的数据
const currentPolicyList = computed(() => {
  return mockDatabase[yearMiddle.value]?.policyData || []
})

// ==================== 3. 图表逻辑 ====================

// --- 左侧环形图 ---
const updateLeftChart = () => {
  if (!leftChart || !leftChartRef.value) return
  const data = mockDatabase[yearLeft.value]?.pieData
  if (!data) return

  const option = {
    color: COLORS.pie,
    tooltip: { trigger: 'item' },
    legend: { show: false }, // 隐藏图例，直接显示Label
    series: [
      {
        name: '建议领域',
        type: 'pie',
        radius: ['45%', '70%'],
        center: ['50%', '55%'],
        avoidLabelOverlap: true,
        itemStyle: {
          borderRadius: 0,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: '{b}\n{c}项  {d}%',
          lineHeight: 16,
          color: '#606266',
          fontSize: 12
        },
        labelLine: {
          show: true,
          length: 15,
          length2: 10
        },
        data: data
      }
    ]
  }
  leftChart.setOption(option)
  // 确保图表正确渲染
  leftChart.resize()
}

// --- 右侧折线图 ---
const updateRightChart = () => {
  if (!rightChart) return
  const data = mockDatabase[yearRight.value].lineData

  const option = {
    tooltip: { trigger: 'axis' },
    legend: {
      data: ['集成电路', '人工智能', '通信网络', '量子科技', '生物科技', '能源'],
      top: 0,
      left: 0,
      icon: 'circle',
      itemWidth: 8,
      itemHeight: 8,
      textStyle: { fontSize: 10, padding: [0, 2, 0, 0] }
    },
    grid: {
      left: '2%',
      right: '3%',
      bottom: '3%',
      top: '28%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false, // 折线图点在轴线上
      data: data.xAxis,
      axisLine: { show: false },
      axisTick: { show: false },
      axisLabel: { color: '#909399', fontSize: 10 }
    },
    yAxis: {
      type: 'value',
      splitLine: {
        lineStyle: { type: 'dotted', color: '#ebeef5' }
      },
      axisLabel: { color: '#909399' }
    },
    series: [
      {
        name: '集成电路', type: 'line', smooth: false, symbol: 'circle', symbolSize: 6,
        itemStyle: { color: COLORS.line.ic },
        data: data.series['集成电路']
      },
      {
        name: '量子科技', type: 'line', smooth: false, symbol: 'circle', symbolSize: 6,
        itemStyle: { color: COLORS.line.quantum },
        data: data.series['量子科技']
      },
      {
        name: '生物科技', type: 'line', smooth: false, symbol: 'circle', symbolSize: 6,
        itemStyle: { color: COLORS.line.bio },
        data: data.series['生物科技']
      },
      {
        name: '能源', type: 'line', smooth: false, symbol: 'circle', symbolSize: 6,
        itemStyle: { color: COLORS.line.energy },
        data: data.series['能源']
      },
      {
        name: '通信网络', type: 'line', smooth: false, symbol: 'circle', symbolSize: 6,
        itemStyle: { color: COLORS.line.comm },
        data: data.series['通信网络']
      },
      {
        name: '人工智能', type: 'line', smooth: false, symbol: 'circle', symbolSize: 6,
        itemStyle: { color: COLORS.line.ai },
        data: data.series['人工智能']
      }
    ]
  }
  rightChart.setOption(option, true) // true = 不合并，完全重绘，避免旧线条残留
}

// ==================== 4. 生命周期与监听 ====================

// 监听年份变化，刷新图表
watch(yearLeft, () => updateLeftChart())
watch(yearRight, () => updateRightChart())
// 中间列表由 computed 自动处理，无需 watch

const resizeHandler = () => {
  leftChart?.resize()
  rightChart?.resize()
}

onMounted(() => {
  nextTick(() => {
    // 确保 DOM 完全渲染后再初始化
    setTimeout(() => {
      // 初始化实例
      if (leftChartRef.value) {
        leftChart = echarts.init(leftChartRef.value)
        updateLeftChart()
        // 确保图表正确渲染
        leftChart.resize()
      }
      
      if (rightChartRef.value) {
        rightChart = echarts.init(rightChartRef.value)
        updateRightChart()
        // 确保图表正确渲染
        rightChart.resize()
      }
      
      window.addEventListener('resize', resizeHandler)
    }, 100)
  })
})

onUnmounted(() => {
  window.removeEventListener('resize', resizeHandler)
  leftChart?.dispose()
  rightChart?.dispose()
})
</script>

<style lang="scss" scoped>
// 变量定义
$card-height: 360px;
$bg-color: #f5f7fa;
$text-main: #303133;
$text-sub: #909399;
$border-color: #ebeef5;

.dashboard-container {
  // background-color: $bg-color;
  padding: 20px;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

.dashboard-card {
  height: $card-height;
  display: flex;
  flex-direction: column;
  border: none;
  border-radius: 8px;
  background: #fff;
  box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 10px; // 移动端换行间距

  :deep(.el-card__header) {
    padding: 15px 20px;
    border-bottom: 1px solid #f0f0f0;
  }
  
  :deep(.el-card__body) {
    flex: 1;
    padding: 15px 20px;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    position: relative;
  }
}

// 头部样式
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .title-group {
    display: flex;
    align-items: center;
    gap: 8px;

    .title {
      font-weight: 700;
      font-size: 16px;
      color: $text-main;
    }

    .el-icon { font-size: 18px; }
    .icon-blue { color: #409EFF; }
    .icon-orange { color: #E6A23C; }
  }

  .link {
    font-size: 12px;
    color: #409EFF;
    cursor: pointer;
    transition: opacity 0.3s;
    &:hover { opacity: 0.8; }
  }
}

// 过滤器区域
.filter-row {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
  z-index: 5;
  
  .year-select {
    width: 90px;
  }

  &.right-filter {
    position: absolute;
    right: 20px;
    top: 15px; // 调整位置以避开图例
  }
}

// ECharts 容器
.chart-container {
  width: 100%;
  flex: 1;
  min-height: 200px; // 确保有最小高度，让图表可以渲染
  height: 0; // 配合 flex: 1 使用
}

// 中间进度列表样式
.policy-list {
  display: flex;
  flex-direction: column;
  justify-content: space-between; // 上下均匀分布
  height: 100%;
  padding-bottom: 5px;

  .policy-item {
    display: flex;
    align-items: center;
    font-size: 12px;
    color: #606266;
    
    .item-label {
      width: 85px; // 固定宽度对齐
      display: flex;
      align-items: center;
      
      .dot {
        width: 6px;
        height: 6px;
        border-radius: 50%;
        margin-right: 8px;
        flex-shrink: 0;
      }
      .name {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        font-weight: 500;
      }
    }

    .progress-track {
      flex: 1;
      height: 6px;
      background-color: #f2f3f5;
      border-radius: 3px;
      margin: 0 15px;
      overflow: hidden;
      
      .progress-bar {
        height: 100%;
        border-radius: 3px;
        transition: width 0.5s ease; // 宽度变化动画
      }
    }

    .item-value {
      width: 110px;
      display: flex;
      justify-content: space-between;
      color: $text-sub;
      
      .count { font-family: Arial, sans-serif; }
      .percent { 
        width: 35px; 
        text-align: right; 
        font-family: Arial, sans-serif; 
      }
    }
  }
}
</style>