<template>
  <div class="trading-chart">
    <a-card title="交易统计分析" :bordered="false">
      <div class="chart-controls">
        <a-space>
          <a-select v-model:value="timeRange" @change="handleTimeRangeChange" style="width: 120px">
            <a-select-option value="7d">近7天</a-select-option>
            <a-select-option value="30d">近30天</a-select-option>
            <a-select-option value="90d">近3个月</a-select-option>
            <a-select-option value="1y">近1年</a-select-option>
          </a-select>
          <a-radio-group v-model:value="viewType" @change="handleViewTypeChange" button-style="solid" size="small">
            <a-radio-button value="amount">交易金额</a-radio-button>
            <a-radio-button value="count">交易笔数</a-radio-button>
            <a-radio-button value="both">综合视图</a-radio-button>
          </a-radio-group>
        </a-space>
      </div>
      <div ref="chartContainer" class="chart-container"></div>
    </a-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue';
import * as echarts from 'echarts';
import { tradingAPI } from '../../services/api.js';

const chartContainer = ref(null);
const timeRange = ref('30d');
const viewType = ref('both');
let chartInstance = null;

const chartData = ref({
  dates: [],
  totalAmount: [],
  totalCount: [],
  successAmount: [],
  successCount: [],
  pendingAmount: [],
  pendingCount: [],
  cancelledCount: []
});

const loading = ref(false);

// 初始化图表
const initChart = () => {
  if (chartContainer.value) {
    chartInstance = echarts.init(chartContainer.value);
    updateChart();
    
    // 监听窗口大小变化
    window.addEventListener('resize', handleResize);
  }
};

// 更新图表
const updateChart = () => {
  if (!chartInstance || !chartData.value.dates.length) return;

  let option = {};

  if (viewType.value === 'amount') {
    // 交易金额视图
    option = {
      title: {
        text: '交易金额趋势',
        left: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'normal'
        }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        },
        formatter: function(params) {
          let result = `<div style="font-weight: bold; margin-bottom: 5px;">${params[0].axisValue}</div>`;
          params.forEach(param => {
            result += `<div style="margin: 2px 0;">
              <span style="display: inline-block; width: 10px; height: 10px; background-color: ${param.color}; border-radius: 50%; margin-right: 5px;"></span>
              ${param.seriesName}: ¥${(param.value / 10000).toFixed(2)}万
            </div>`;
          });
          return result;
        }
      },
      legend: {
        data: ['总交易额', '成功交易额', '待处理交易额'],
        top: 30
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        top: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: chartData.value.dates,
        axisLabel: {
          formatter: function(value) {
            return echarts.format.formatTime('MM-dd', new Date(value));
          }
        }
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: function(value) {
            return '¥' + (value / 10000).toFixed(1) + '万';
          }
        }
      },
      series: [
        {
          name: '总交易额',
          type: 'line',
          data: chartData.value.totalAmount,
          itemStyle: { color: '#1890ff' },
          areaStyle: { opacity: 0.3 }
        },
        {
          name: '成功交易额',
          type: 'line',
          data: chartData.value.successAmount,
          itemStyle: { color: '#52c41a' }
        },
        {
          name: '待处理交易额',
          type: 'line',
          data: chartData.value.pendingAmount,
          itemStyle: { color: '#faad14' }
        }
      ]
    };
  } else if (viewType.value === 'count') {
    // 交易笔数视图
    option = {
      title: {
        text: '交易笔数趋势',
        left: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'normal'
        }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        },
        formatter: function(params) {
          let result = `<div style="font-weight: bold; margin-bottom: 5px;">${params[0].axisValue}</div>`;
          params.forEach(param => {
            result += `<div style="margin: 2px 0;">
              <span style="display: inline-block; width: 10px; height: 10px; background-color: ${param.color}; border-radius: 50%; margin-right: 5px;"></span>
              ${param.seriesName}: ${param.value}笔
            </div>`;
          });
          return result;
        }
      },
      legend: {
        data: ['总交易笔数', '成功交易', '待处理', '已取消'],
        top: 30
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        top: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: chartData.value.dates
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: '{value} 笔'
        }
      },
      series: [
        {
          name: '总交易笔数',
          type: 'bar',
          data: chartData.value.totalCount,
          itemStyle: { color: '#1890ff' }
        },
        {
          name: '成功交易',
          type: 'bar',
          data: chartData.value.successCount,
          itemStyle: { color: '#52c41a' }
        },
        {
          name: '待处理',
          type: 'bar',
          data: chartData.value.pendingCount,
          itemStyle: { color: '#faad14' }
        },
        {
          name: '已取消',
          type: 'bar',
          data: chartData.value.cancelledCount,
          itemStyle: { color: '#ff4d4f' }
        }
      ]
    };
  } else {
    // 综合视图 - 双Y轴
    option = {
      title: {
        text: '交易综合分析',
        left: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'normal'
        }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        },
        formatter: function(params) {
          let result = `<div style="font-weight: bold; margin-bottom: 5px;">${params[0].axisValue}</div>`;
          params.forEach(param => {
            const unit = param.seriesName.includes('金额') ? '万元' : '笔';
            const value = param.seriesName.includes('金额') ? (param.value / 10000).toFixed(2) : param.value;
            result += `<div style="margin: 2px 0;">
              <span style="display: inline-block; width: 10px; height: 10px; background-color: ${param.color}; border-radius: 50%; margin-right: 5px;"></span>
              ${param.seriesName}: ${value}${unit}
            </div>`;
          });
          return result;
        }
      },
      legend: {
        data: ['交易金额', '交易笔数'],
        top: 30
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        top: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: chartData.value.dates
      },
      yAxis: [
        {
          type: 'value',
          name: '交易金额',
          position: 'left',
          axisLabel: {
            formatter: function(value) {
              return '¥' + (value / 10000).toFixed(1) + '万';
            }
          }
        },
        {
          type: 'value',
          name: '交易笔数',
          position: 'right',
          axisLabel: {
            formatter: '{value} 笔'
          }
        }
      ],
      series: [
        {
          name: '交易金额',
          type: 'line',
          yAxisIndex: 0,
          data: chartData.value.totalAmount,
          itemStyle: { color: '#1890ff' },
          areaStyle: { opacity: 0.3 }
        },
        {
          name: '交易笔数',
          type: 'bar',
          yAxisIndex: 1,
          data: chartData.value.totalCount,
          itemStyle: { color: '#52c41a', opacity: 0.8 }
        }
      ]
    };
  }

  chartInstance.setOption(option);
};

// 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    const response = await tradingAPI.getChartData({
      timeRange: timeRange.value,
      type: 'statistics'
    });

    if (response.success) {
      chartData.value = response.data;
      await nextTick();
      updateChart();
    } else {
      // 使用模拟数据
      generateMockData();
    }
  } catch (error) {
    console.error('加载交易统计数据失败:', error);
    generateMockData();
  } finally {
    loading.value = false;
  }
};

// 生成模拟数据
const generateMockData = () => {
  const days = timeRange.value === '7d' ? 7 : timeRange.value === '30d' ? 30 : timeRange.value === '90d' ? 90 : 365;
  const dates = [];
  const totalAmount = [];
  const totalCount = [];
  const successAmount = [];
  const successCount = [];
  const pendingAmount = [];
  const pendingCount = [];
  const cancelledCount = [];

  for (let i = days - 1; i >= 0; i--) {
    const date = new Date();
    date.setDate(date.getDate() - i);
    dates.push(date.toISOString().split('T')[0]);
    
    // 模拟交易数据
    const dailyCount = Math.floor(Math.random() * 50) + 20;
    const dailyAmount = dailyCount * (Math.random() * 50000 + 10000); // 每笔1-6万
    
    const successRate = 0.7 + Math.random() * 0.2; // 70-90%成功率
    const pendingRate = 0.1 + Math.random() * 0.1; // 10-20%待处理
    const cancelledRate = 1 - successRate - pendingRate;
    
    totalCount.push(dailyCount);
    totalAmount.push(Math.floor(dailyAmount));
    successCount.push(Math.floor(dailyCount * successRate));
    successAmount.push(Math.floor(dailyAmount * successRate));
    pendingCount.push(Math.floor(dailyCount * pendingRate));
    pendingAmount.push(Math.floor(dailyAmount * pendingRate));
    cancelledCount.push(Math.floor(dailyCount * cancelledRate));
  }

  chartData.value = {
    dates,
    totalAmount,
    totalCount,
    successAmount,
    successCount,
    pendingAmount,
    pendingCount,
    cancelledCount
  };

  updateChart();
};

// 处理时间范围变化
const handleTimeRangeChange = () => {
  loadData();
};

// 处理视图类型变化
const handleViewTypeChange = () => {
  updateChart();
};

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

onMounted(() => {
  nextTick(() => {
    initChart();
    loadData();
  });
});

onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose();
  }
  window.removeEventListener('resize', handleResize);
});

// 监听数据变化
watch(() => chartData.value, () => {
  updateChart();
}, { deep: true });
</script>

<style scoped>
.trading-chart {
  width: 100%;
  height: 100%;
}

.chart-controls {
  margin-bottom: 16px;
  text-align: right;
}

.chart-container {
  width: 100%;
  height: 400px;
}

:deep(.ant-card-head-title) {
  font-size: 16px;
  font-weight: 500;
}

:deep(.ant-card-body) {
  padding: 20px;
}
</style>