<template>
  <div class="product-analysis-view">
    <!-- 页面头部 -->
    <header class="page-header">
      <h1 class="page-title">商品关联透视</h1>
      <p class="page-subtitle">探索商品之间的共现购买关系，发现最佳销售组合。</p>
    </header>

    <!-- 共现购买关系表格 -->
    <div class="table-container">
      <h2 class="table-title">热门商品组合</h2>
      <table>
        <thead>
          <tr>
            <th>商品 A (SKU)</th>
            <th>商品 B (SKU)</th>
            <th>共同购买次数</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="loading">
            <td colspan="3">正在努力加载数据中... 🐾</td>
          </tr>
          <!-- ✨【保持列位置不变，只调整数字位置】✨ -->
          <tr v-else-if="coPurchaseData.length > 0" v-for="(item, index) in paginatedData" :key="index" class="data-row">
            <td class="sku-cell" :title="`商品A: ${item.productA}`">{{ item.productAId }}</td>
            <td class="sku-cell" :title="`商品B: ${item.productB}`">{{ item.productBId }}</td>
            <td class="count-cell" :title="`共同购买次数: ${item.coPurchaseCount}`">
              <div class="count-wrapper">
                {{ item.coPurchaseCount }}
              </div>
            </td>
          </tr>
          <tr v-else-if="!loading && coPurchaseData.length === 0">
            <td colspan="3">暂时没有找到商品组合数据...</td>
          </tr>
        </tbody>
      </table>
      
      <!-- 分页控件 -->
      <div class="pagination">
        <button 
          :disabled="currentPage === 1" 
          @click="prevPage"
          class="page-button"
        >
          上一页
        </button>
        <span class="page-info">
          第 {{ currentPage }} 页，共 {{ totalPages }} 页
        </span>
        <button 
          :disabled="currentPage === totalPages" 
          @click="nextPage"
          class="page-button"
        >
          下一页
        </button>
      </div>
    </div>

    <!-- 网络图部分（保持不变） -->
    <div class="chart-container">
      <h2 class="chart-title">共购规则网络图</h2>
      <div ref="networkChart" style="width: 100%; height: 600px;"></div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { getOrderCoPurchase } from '@/api/order';

export default {
  name: 'OrderRelated',
  data() {
    return {
      coPurchaseData: [],
      loading: true,
      currentPage: 1,
      itemsPerPage: 10
    };
  },
  computed: {
    paginatedData() {
      const start = (this.currentPage - 1) * this.itemsPerPage;
      const end = start + this.itemsPerPage;
      return this.coPurchaseData.slice(start, end);
    },
    totalPages() {
      return Math.ceil(this.coPurchaseData.length / this.itemsPerPage);
    }
  },
  mounted() {
    this.fetchData();
  },
  methods: {
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage -= 1;
      }
    },
    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage += 1;
      }
    },
    async fetchData() {
      try {
        const response = await getOrderCoPurchase();
        this.coPurchaseData = response || [];
        this.renderNetworkChart(this.coPurchaseData);
      } catch (error) {
        console.error("获取共现购买数据失败:", error);
      } finally {
        this.loading = false;
      }
    },
    renderNetworkChart(data) {
      const chartEl = this.$refs.networkChart;
      if (!chartEl || !data) return;
      const myChart = echarts.init(chartEl);
  
  // 统计每个节点的出现次数（核心度）
  const nodeCount = {};
  // 统计每条连线的权重
  const linkWeights = {};
  
  data.forEach(item => {
    // 统计节点出现次数
    nodeCount[item.productAId] = (nodeCount[item.productAId] || 0) + 1;
    nodeCount[item.productBId] = (nodeCount[item.productBId] || 0) + 1;
    
    // 统计连线权重
    const linkKey = `${item.productAId}-${item.productBId}`;
    linkWeights[linkKey] = (linkWeights[linkKey] || 0) + item.coPurchaseCount;
  });
  
  // 创建节点和连线
  const nodes = [];
  const links = [];
  const nodeSet = new Set();
  
  // 用于自动聚类的颜色分类
  const categories = [
    { name: '社群1', itemStyle: { color: '#FF6B6B' } },
    { name: '社群2', itemStyle: { color: '#4ECDC4' } },
    { name: '社群3', itemStyle: { color: '#45B7D1' } },
    { name: '社群4', itemStyle: { color: '#96CEB4' } },
    { name: '社群5', itemStyle: { color: '#FFEAA7' } },
    { name: '社群6', itemStyle: { color: '#DDA0DD' } }
  ];
  
  // 用于社群聚类的简单算法
  const nodeCategories = {};
  let categoryIndex = 0;
  
  data.forEach(item => {
    // 添加节点A
    if (!nodeSet.has(item.productAId)) {
      nodeSet.add(item.productAId);
      // 根据出现次数确定节点大小（核心度）
      const count = nodeCount[item.productAId];
      // 节点大小范围：15-50
      const symbolSize = Math.min(15 + count * 5, 50);
      
      // 简单的社群聚类：根据第一个关联商品确定社群
      if (!nodeCategories[item.productAId]) {
        nodeCategories[item.productAId] = categoryIndex % categories.length;
        categoryIndex++;
      }
      
      nodes.push({ 
        id: item.productAId, 
        name: item.productAId, 
        symbolSize: symbolSize, 
        category: nodeCategories[item.productAId],
        value: count // 用于tooltip显示
      });
    }
    
    // 添加节点B
    if (!nodeSet.has(item.productBId)) {
      nodeSet.add(item.productBId);
      // 根据出现次数确定节点大小（核心度）
      const count = nodeCount[item.productBId];
      // 节点大小范围：15-50
      const symbolSize = Math.min(15 + count * 5, 50);
      
      // 简单的社群聚类：根据第一个关联商品确定社群
      if (!nodeCategories[item.productBId]) {
        nodeCategories[item.productBId] = categoryIndex % categories.length;
        categoryIndex++;
      }
      
      nodes.push({ 
        id: item.productBId, 
        name: item.productBId, 
        symbolSize: symbolSize, 
        category: nodeCategories[item.productBId],
        value: count // 用于tooltip显示
      });
    }
    
    // 添加连线
    const linkKey = `${item.productAId}-${item.productBId}`;
    const weight = linkWeights[linkKey];
    links.push({
      source: item.productAId,
      target: item.productBId,
      // 线条粗细代表关联强度
      value: weight,
      // 使用默认线条粗细
      lineStyle: {
        width: 1 // 恢复到默认线条粗细
      }
    });
  });

  const option = {
    tooltip: {
      formatter: (params) => {
        if (params.dataType === 'node') {
          return `${params.name}<br/>出现次数: ${params.data.value}`;
        } else if (params.dataType === 'edge') {
          return `${params.data.source} ↔ ${params.data.target}<br/>共购次数: ${params.data.value}`;
        }
        return '';
      }
    },
    legend: [{
      data: categories.map(cat => cat.name),
      bottom: 0, // 将图例放置在容器底部
      left: 'center', // 将图例水平居中
      itemGap: 20, // 增加图例项间距
      itemWidth: 15,
      itemHeight: 10,
      backgroundColor: 'white', // 设置图例背景为白色
      borderRadius: [8, 8, 8, 8], // 四周圆角，与页面其他组件保持一致
      shadowColor: 'rgba(0, 0, 0, 0.1)', // 设置阴影
      shadowBlur: 5, // 设置阴影模糊度
      padding: [15, 20, 15, 20] // 设置内边距
    }],
    series: [
      {
        type: 'graph',
        layout: 'force',
        data: nodes,
        links: links,
        categories: categories,
        roam: true,
        label: {
          show: true,
          position: 'right',
          formatter: '{b}',
          fontSize: 12
        },
        force: {
          repulsion: 300, // 适度增加节点间排斥力，使节点在水平方向分散
          edgeLength: [150, 250], // 调整连线长度范围，平衡水平分散效果
          gravity: 0.2, // 增加重力，使节点在垂直方向更集中
          layoutAnimation: true
        },
        // 调整图表中心位置，将图表向上移动一点
        center: ['50%', '40%'],
        // 设置图表左右边界，只在水平方向拉伸
        left: 0,
        right: 0,
        // 节点样式
        itemStyle: {
          borderColor: '#fff',
          borderWidth: 1,
          shadowBlur: 10,
          shadowColor: 'rgba(0, 0, 0, 0.3)'
        },
        // 连线样式
        lineStyle: {
          opacity: 0.9,
          curveness: 0 // 直线连接
        },
        // 鼠标悬停效果
        emphasis: {
          focus: 'adjacency',
          lineStyle: {
            width: 10
          }
        }
      }
    ]
  };
      myChart.setOption(option);
    }
  }
};
</script>

<style scoped>
.product-analysis-view { display: flex; flex-direction: column; gap: 20px; }
.page-header, .table-container, .chart-container { background-color: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05); }
.page-title { font-size: 20px; font-weight: 600; margin: 0; color: #333; }
.page-subtitle { font-size: 14px; color: #666; margin-top: 8px; }
.table-title, .chart-title { font-size: 18px; font-weight: 600; margin-bottom: 20px; color: #333; }
table { width: 100%; border-collapse: collapse; }
th, td { padding: 12px 15px; text-align: left; border-bottom: 1px solid #f0f0f0; }
thead th { background-color: #f8f9fa; font-size: 14px; font-weight: 600; color: #333; }
.data-row:hover { background-color: #f8f9fa; }
.sku-cell { font-family: 'Courier New', monospace; font-size: 14px; }
.count-cell { text-align: left; font-size: 14px; }
.count-wrapper { font-weight: bold; color: #3366CC; text-align: center; display: inline-block; min-width: 90px; }

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  gap: 15px;
}
.page-button {
  padding: 8px 16px;
  background-color: #f0f4f8;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s;
}
.page-button:hover:not(:disabled) {
  background-color: #e1e8f0;
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.page-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
.page-info {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}
</style>
