<template>
  <div class="dashboard-container">
    <div class="top-row">
      <el-card class="chart-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <div class="title">
              <el-icon color="#409EFF"><TrendCharts /></el-icon>
              <span>政策建议趋势分布</span>
            </div>
            <el-select v-model="lineChartPeriod" size="small" style="width: 100px">
              <el-option label="近十年" value="10years" />
              <el-option label="近五年" value="5years" />
            </el-select>
          </div>
        </template>
        <div ref="lineChartRef" class="chart-container"></div>
      </el-card>

      <el-card class="chart-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <div class="title">
              <el-icon color="#409EFF"><PieChart /></el-icon>
              <span>政策建议领域分布</span>
            </div>
            <el-select v-model="pieChartYear" size="small" style="width: 100px">
              <el-option label="2025年" value="2025" />
              <el-option label="2024年" value="2024" />
            </el-select>
          </div>
        </template>
        <div ref="pieChartRef" class="chart-container"></div>
      </el-card>
    </div>

    <div class="bottom-row">
      <el-card class="chart-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <div class="title">
              <el-icon color="#409EFF"><Share /></el-icon>
              <span>智库资金流向</span>
            </div>
          </div>
        </template>
        <div ref="sankeyChartRef" class="chart-container"></div>
      </el-card>

      <el-card class="chart-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <div class="title">
              <el-icon color="#409EFF"><Opportunity /></el-icon>
              <span>智库研究热点</span>
            </div>
            <el-select v-model="hotspotPeriod" size="small" style="width: 100px">
              <el-option label="近一年" value="1year" />
              <el-option label="近半年" value="halfyear" />
            </el-select>
          </div>
        </template>
        
        <div class="list-container">
          <div v-for="(item, index) in hotspotList" :key="index" class="list-item">
            <div class="rank-wrapper">
              <span :class="['rank-num', index < 3 ? 'top-rank' : 'normal-rank']">
                {{ index + 1 }}
              </span>
            </div>
            <div class="content-text" :title="item.title">{{ item.title }}</div>
            <div class="report-count">{{ item.count }}份报告 ></div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

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

// --- 状态管理 ---
const lineChartPeriod = ref('10years');
const pieChartYear = ref('2025');
const hotspotPeriod = ref('1year');

// --- DOM 引用 ---
const lineChartRef = ref(null);
const pieChartRef = ref(null);
const sankeyChartRef = ref(null);

// --- 模拟数据 ---

// 列表数据
const hotspotList = ref([
  { title: '人工智能领域竞争发展', count: 11 },
  { title: '美元未来与能源出口挂钩', count: 7 },
  { title: '量子领域国家合作', count: 5 },
  { title: '限制中国产燃油进口', count: 5 },
  { title: '禁止政府部门采购受控半导体或服务', count: 4 },
  { title: '禁止向部分中国实体提供资金', count: 3 },
  { title: '中国生产电池', count: 3 },
  { title: '重视新兴中国技术公司威胁', count: 2 },
  { title: '禁止卫星出口至中国', count: 1 },
  { title: '华为设备', count: 1 },
]);

// ECharts 实例
let lineChart = null;
let pieChart = null;
let sankeyChart = null;

// --- 初始化图表 ---

const initLineChart = () => {
  if (!lineChartRef.value) return;
  lineChart = echarts.init(lineChartRef.value);
  
  const option = {
    color: ['#409EFF', '#67C23A', '#909399', '#E6A23C', '#73C0DE', '#F56C6C'],
    tooltip: { trigger: 'axis' },
    legend: {
      data: ['人工智能', '集成电路', '量子科技', '生物科技', '通信网络', '能源'],
      bottom: 'top',
      icon: 'circle'
    },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['2014', '2015', '2016', '2017', '2018', '2019', '2020', '2021', '2022', '2023', '2024', '2025']
    },
    yAxis: { type: 'value' },
    series: [
      { name: '人工智能', type: 'line', smooth: true, areaStyle: { opacity: 0.1 }, data: [150, 80, 90, 100, 80, 100, 130, 150, 140, 170, 190, 175] },
      { name: '集成电路', type: 'line', smooth: true, areaStyle: { opacity: 0.1 }, data: [70, 100, 125, 115, 135, 150, 168, 165, 165, 172, 172, 185] },
      { name: '量子科技', type: 'line', smooth: true, data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 10] }, // 模拟低数据
      { name: '生物科技', type: 'line', smooth: true, data: [10, 5, 5, 10, 10, 15, 20, 30, 28, 30, 45, 45] },
      { name: '通信网络', type: 'line', smooth: true, areaStyle: { opacity: 0.1 }, data: [40, 35, 45, 50, 50, 48, 55, 75, 65, 65, 68, 60] },
      { name: '能源', type: 'line', smooth: true, areaStyle: { opacity: 0.1 }, data: [100, 75, 65, 85, 65, 75, 85, 120, 118, 150, 140, 110] },
    ]
  };
  lineChart.setOption(option);
};

const initPieChart = () => {
  if (!pieChartRef.value) return;
  pieChart = echarts.init(pieChartRef.value);

  const option = {
    tooltip: { trigger: 'item' },
    legend: {
      orient: 'vertical',
      left: '5%',
      top: 'center',
      itemGap: 20,
      formatter: (name) => {
        // 简单的 mock 数据映射，实际应从 data 动态获取
        const dataMap = {
          '人工智能': '50项 21%',
          '集成电路': '46项 18%',
          '通信网络': '40项 16%',
          '能源': '32项 14%',
          '量子科技': '31项 12%',
          '生物科技': '30项 11%',
          '其他': '24项 8%'
        };
        return `{name|${name}}\n{val|${dataMap[name]}}`;
      },
      textStyle: {
        rich: {
          name: { fontWeight: 'bold', fontSize: 14, padding: [0, 0, 5, 0] },
          val: { color: '#666', fontSize: 12 }
        }
      }
    },
    series: [
      {
        name: '领域分布',
        type: 'pie',
        radius: ['45%', '70%'],
        center: ['65%', '50%'], // 向右偏移，留位置给 Legend
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: { show: false }, // 隐藏连接线上的标签，使用 Legend
        data: [
          { value: 50, name: '人工智能', itemStyle: { color: '#409EFF' } },
          { value: 46, name: '集成电路', itemStyle: { color: '#F56C6C' } },
          { value: 40, name: '通信网络', itemStyle: { color: '#a0cfff' } },
          { value: 32, name: '能源', itemStyle: { color: '#E6A23C' } },
          { value: 31, name: '量子科技', itemStyle: { color: '#cceeff' } },
          { value: 30, name: '生物科技', itemStyle: { color: '#d1bdf2' } },
          { value: 24, name: '其他', itemStyle: { color: '#f2f2f2' } }
        ]
      }
    ]
  };
  pieChart.setOption(option);
};

const initSankeyChart = () => {
  if (!sankeyChartRef.value) return;
  sankeyChart = echarts.init(sankeyChartRef.value);

  // 简化的桑基图节点和连接
  const nodes = [
    { name: '美国', itemStyle: { color: '#1f5cb8' } },
    { name: '英国', itemStyle: { color: '#6f42c1' } },
    { name: '加拿大', itemStyle: { color: '#d9534f' } },
    // 中间层
    { name: '美国能源部', itemStyle: { color: '#a4c639' } },
    { name: '美国财政部', itemStyle: { color: '#f06292' } },
    { name: '美国国务院', itemStyle: { color: '#b08d55' } },
    { name: '美国国际开发署', itemStyle: { color: '#4285f4' } },
    { name: '美国内政部', itemStyle: { color: '#8cae9e' } },
    { name: '美国国家民主基金会', itemStyle: { color: '#a1887f' } },
    // 右侧层 (部分)
    { name: '麻省理工学院科技评论', itemStyle: { color: '#7cb342' } },
    { name: '麦肯锡全球研究院', itemStyle: { color: '#cddc39' } },
    { name: '卡内基国际和平研究院', itemStyle: { color: '#afb42b' } },
    { name: '战略与国际研究中心', itemStyle: { color: '#827717' } },
    { name: '兰德公司', itemStyle: { color: '#689f38' } },
  ];

  const links = [
    { source: '美国', target: '美国能源部', value: 50 },
    { source: '美国', target: '美国财政部', value: 40 },
    { source: '美国', target: '美国国务院', value: 60 },
    { source: '美国', target: '美国国际开发署', value: 20 },
    { source: '美国', target: '美国内政部', value: 15 },
    { source: '英国', target: '美国国务院', value: 10 },
    { source: '加拿大', target: '美国能源部', value: 5 },
    
    // Flow to right
    { source: '美国能源部', target: '麻省理工学院科技评论', value: 20 },
    { source: '美国能源部', target: '麦肯锡全球研究院', value: 25 },
    { source: '美国财政部', target: '卡内基国际和平研究院', value: 30 },
    { source: '美国国务院', target: '战略与国际研究中心', value: 40 },
    { source: '美国国务院', target: '兰德公司', value: 15 },
  ];

  const option = {
    tooltip: { trigger: 'item', triggerOn: 'mousemove' },
    series: [
      {
        type: 'sankey',
        layout: 'none',
        emphasis: { focus: 'adjacency' },
        nodeAlign: 'left',
        data: nodes,
        links: links,
        lineStyle: { color: 'gradient', curveness: 0.5, opacity: 0.3 },
        label: { position: 'right', color: '#666', fontSize: 10 }
      }
    ]
  };
  sankeyChart.setOption(option);
};

// --- 生命周期钩子 ---

onMounted(() => {
  nextTick(() => {
    initLineChart();
    initPieChart();
    initSankeyChart();
  });

  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  lineChart?.dispose();
  pieChart?.dispose();
  sankeyChart?.dispose();
});

const handleResize = () => {
  lineChart?.resize();
  pieChart?.resize();
  sankeyChart?.resize();
};
</script>

<style scoped>
.dashboard-container {
  background-color: #f5f7fa;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  height: 100vh; /* 或根据需要调整高度 */
  box-sizing: border-box;
}

/* 通用布局类 */
.top-row, .bottom-row {
  display: grid;
  grid-template-columns: 1.5fr 1fr; /* 2列等宽 */
  gap: 20px;
  flex: 1; /* 上下平分高度 */
  min-height: 0; /* 防止溢出 */
}

.chart-card {
  display: flex;
  flex-direction: column;
  height: 100%;
  border-radius: 8px;
}

/* Element Plus Card 样式覆盖 */
:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-card__body) {
  flex: 1;
  padding: 10px;
  position: relative;
  height: 0; /* 关键：配合 flex:1 让内部图表自适应高度 */
}

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

.title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

/* 图表容器 */
.chart-container {
  width: 100%;
  height: 100%;
}

/* 列表样式 */
.list-container {
  height: 100%;
  overflow-y: auto;
  padding: 0 10px;
}

.list-item {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px dashed #eee;
  font-size: 14px;
  color: #606266;
}

.list-item:last-child {
  border-bottom: none;
}

.rank-wrapper {
  width: 30px;
  text-align: center;
  margin-right: 10px;
}

.rank-num {
  font-weight: bold;
  font-family: Arial, sans-serif;
}

.top-rank {
  color: #E6A23C; /* 前三名金色 */
  font-size: 16px;
}

.normal-rank {
  color: #909399; /* 其他灰色 */
  font-size: 14px;
}

.content-text {
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #303133;
  cursor: pointer;
}

.content-text:hover {
  color: #409EFF;
}

.report-count {
  color: #909399;
  font-size: 12px;
  margin-left: 10px;
}

/* 响应式调整 (可选) */
@media (max-width: 1024px) {
  .top-row, .bottom-row {
    grid-template-columns: 1fr; /* 小屏幕变为单列 */
  }
  .dashboard-container {
    height: auto; /* 允许滚动 */
  }
  .chart-card {
    height: 400px; /* 固定高度 */
  }
}
</style>