<template>
  <div class="test-center">
    <!-- 第一行搜索区域 -->
    <div class="search-section">
      <el-tree-select
          v-model="selectedValue"
          :data="treeData"
          :props="treeProps"
          show-checkbox
          @check="handleCheck"
          style="width: 600px"
      />
    </div>

    <!-- 第二行操作区域 -->
    <div class="operation-section">
      <div class="left-area">
        <el-select v-model="value" placeholder="Select" style="width: 240px">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
          />
        </el-select>

        <el-tree-select
            v-model="selectedValue"
            :data="treeData"
            :props="treeProps"
            show-checkbox
            @check="handleCheck"
            style="width: 600px"
        />
      </div>
      <div class="right-area">
        <el-button type="primary" disabled>操作1</el-button>
        <el-button type="success" disabled>操作2</el-button>
        <el-button type="warning" disabled>操作3</el-button>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="date" label="Date" width="180" />
        <el-table-column prop="name" label="Name" width="180" />
        <el-table-column prop="address" label="Address" />
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-section">
      <el-pagination 
        background 
        layout="total, sizes, prev, pager, next, jumper" 
        :total="1000"
        :page-sizes="[10, 20, 50, 100]"
      />
    </div>

    <div class="chart-demo">
      <!-- 柱状图示例 -->
      <ECharts 
        :options="barChartOptions"
        height="300px"
        chartType="bar"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import ECharts from '@/components/ECharts/index.vue'

const value = ref('')
const options = [
  {
    value: 'Option1',
    label: 'Option1',
  },
  {
    value: 'Option2',
    label: 'Option2',
    disabled: true,
  },
  {
    value: 'Option3',
    label: 'Option3',
  },
  {
    value: 'Option4',
    label: 'Option4',
  },
  {
    value: 'Option5',
    label: 'Option5',
  },
]



// 树形数据
const treeData = ref([
  {
    id: 1,
    label: '父级1',
    children: [
      { id: 11, label: '子级1-1' },
      { id: 12, label: '子级1-2' },
      {
        id: 13,
        label: '子级1-3',
        children: [
          { id: 131, label: '子子级1-3-1' },
          { id: 132, label: '子子级1-3-2' },
        ],
      },
    ],
  },
  {
    id: 2,
    label: '父级2',
    children: [
      { id: 21, label: '子级2-1' },
      { id: 22, label: '子级2-2' },
    ],
  },
]);



const tableData = [
  {
    date: '2016-05-03',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles',
  },
  {
    date: '2016-05-02',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles',
  },
  {
    date: '2016-05-04',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles',
  },
  {
    date: '2016-05-01',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles',
  },
  {
    date: '2016-05-03',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles',
  },
  {
    date: '2016-05-02',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles',
  },
  {
    date: '2016-05-04',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles',
  },
  {
    date: '2016-05-01',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles',
  },
]


// 树形选择的配置属性
const treeProps = {
  value: 'id',
  label: 'label',
  children: 'children',
};

// 当前选中的值
const selectedValue = ref(null);

// 处理节点选中事件
const handleCheck = (currentNode, checkedNodes) => {
  // 获取所有选中的节点
  const checked = checkedNodes.checkedNodes;

  // 用于存储最终的叶子节点id
  const finalIds = new Set(); // 使用Set避免重复

  checked.forEach(node => {
    // 判断是否是叶子节点（即没有子节点）
    if (!node.children || node.children.length === 0) {
      finalIds.add(node.id);
    } else {
      // 如果是父级节点，递归获取其下的叶子节点id
      const leafIds = getLeafIds(node, new Set());
      leafIds.forEach(id => finalIds.add(id));
    }
  });

  console.log('最终的叶子节点id列表：', Array.from(finalIds));
};

// 递归获取叶子节点id
const getLeafIds = (node, visited) => {
  const ids = new Set();
  if (node.children) {
    node.children.forEach(child => {
      if (!child.children || child.children.length === 0) {
        // 如果是叶子节点，添加其id
        ids.add(child.id);
      } else {
        // 如果不是叶子节点，继续递归
        if (!visited.has(child.id)) {
          visited.add(child.id);
          const childIds = getLeafIds(child, visited);
          childIds.forEach(id => ids.add(id));
        }
      }
    });
  }
  return ids;
};

// 定义图表数据结构
const chartData = ref({
  categories: ['手机', '电脑', '平板', '耳机', '手表'],
  series: [
    {
      name: '上月销量',
      type: 'bar',
      data: [120, 200, 150, 80, 70],
      color: '#409EFF',
      showLabel: true,
      labelFormatter: '{c}台'
    },
    {
      name: '本月销量',
      type: 'bar',
      data: [140, 180, 180, 120, 90],
      color: '#67C23A',
      showLabel: true,
      labelFormatter: '{c}台'
    },
    {
      name: '环比增长',
      type: 'line',
      yAxisIndex: 1,
      data: [16.7, -10, 20, 50, 28.6],
      color: '#E6A23C',
      showLabel: true,
      labelFormatter: '{c}%'
    }
  ],
  yAxis: [
    {
      name: '销量',
      min: 0,
      nameTextStyle: {
        padding: [0, 0, 0, 50]
      }
    },
    {
      name: '增长率',
      min: 0,
      max: 100,
      axisLabel: '{value}%',
      nameTextStyle: {
        padding: [0, 0, 0, 50]
      }
    }
  ]
})

// 生成图表配置的函数
const generateChartOptions = (chartData) => {
  const barSeries = chartData.series.filter(item => item.type === 'bar')
  const lineSeries = chartData.series.filter(item => item.type === 'line')
  
  return {
    title: {
      text: '各类商品销量对比'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      },
      formatter: function(params) {
        let result = `${params[0].axisValue}<br/>`;
        // 计算同比增长
        const currentValue = params.find(p => p.seriesName === '本月销量')?.value || 0;
        const lastValue = params.find(p => p.seriesName === '上月销量')?.value || 0;
        const growth = params.find(p => p.seriesName === '环比增长')?.value || 0;
        
        // 添加所有系列的数据
        params.forEach(param => {
          const marker = param.marker;
          const seriesName = param.seriesName;
          const value = param.value;
          const unit = param.seriesName.includes('增长') ? '%' : '台';
          result += `${marker}${seriesName}: ${value}${unit}<br/>`;
        });
        
        // 添加额外统计信息
        if (currentValue && lastValue) {
          const diff = currentValue - lastValue;
          result += '<br/>';
          result += `<span style="color: #666">销量差额: ${diff > 0 ? '+' : ''}${diff}台</span><br/>`;
          result += `<span style="color: ${growth >= 0 ? '#67C23A' : '#F56C6C'}">环比: ${growth}%</span>`;
        }
        
        return result;
      }
    },
    legend: {
      data: chartData.series.map(item => item.name),
      selected: chartData.series.reduce((acc, item) => {
        acc[item.name] = true;
        return acc;
      }, {})
    },
    xAxis: {
      type: 'category',
      data: chartData.categories,
      axisLabel: {
        interval: 0,
        rotate: chartData.categories.length > 5 ? 30 : 0
      }
    },
    yAxis: chartData.yAxis.map((axis, index) => ({
      type: 'value',
      name: axis.name,
      min: axis.min,
      max: axis.max,
      position: index === 0 ? 'left' : 'right',
      splitLine: {
        show: index === 0
      },
      axisLabel: axis.axisLabel ? {
        formatter: axis.axisLabel
      } : undefined
    })),
    series: chartData.series.map(item => ({
      name: item.name,
      type: item.type,
      yAxisIndex: item.yAxisIndex || 0,
      data: item.data,
      barMaxWidth: 50,  // 限制柱子最大宽度
      barGap: '30%',    // 柱子之间的间距
      itemStyle: {
        color: item.color,
        borderRadius: item.type === 'bar' ? [4, 4, 0, 0] : 0
      },
      label: item.showLabel ? {
        show: true,
        position: item.type === 'line' ? 'top' : 'inside',
        formatter: item.labelFormatter,
        fontSize: 12,
        color: item.type === 'line' ? item.color : '#fff'
      } : undefined,
      emphasis: {
        focus: 'series',
        label: {
          show: true,
          position: item.type === 'line' ? 'top' : 'inside',
          formatter: item.labelFormatter || '{c}',
          fontSize: 12,
          color: item.type === 'line' ? item.color : '#fff'
        }
      }
    })),
    grid: {
      top: '15%',
      bottom: '15%',
      left: '10%',
      right: '10%',
      containLabel: true
    }
  }
}

// 生成图表配置
const barChartOptions = computed(() => generateChartOptions(chartData.value))
</script>

<style lang="scss" scoped>
.test-center {
  padding: 16px;
  background-color: #f5f7fa;
  min-height: 100vh;

  .search-section {
    background-color: #fff;
    padding: 16px;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
    margin-bottom: 12px;
  }

  .operation-section {
    background-color: #fff;
    padding: 16px;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
    margin-bottom: 12px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .left-area {
      display: flex;
      gap: 12px;
      align-items: center;
    }

    .right-area {
      display: flex;
      gap: 8px;
    }
  }

  .table-section {
    background-color: #fff;
    padding: 12px 16px;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
    margin-bottom: 12px;

    :deep(.el-table) {
      // 移除表格的外边框
      --el-table-border: none;
      // 减小表格行的上下padding
      --el-table-row-height: 45px;
    }
  }

  .pagination-section {
    background-color: #fff;
    padding: 12px 16px;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
    display: flex;
    justify-content: center;
  }

  .chart-demo {
    background-color: #fff;
    padding: 16px;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
    margin-bottom: 12px;
  }
}
</style>
