<script lang="ts" setup>
import type { EchartsUIType } from '@vben/plugins/echarts';

import { onMounted, ref, watch } from 'vue';

import { EchartsUI, useEcharts } from '@vben/plugins/echarts';
import { Button } from 'ant-design-vue';
import { getOrderStatistics } from '#/api/order/order-statistics';

const chartRef = ref<EchartsUIType>();
const { renderEcharts } = useEcharts(chartRef);

// 时间维度状态
const timeDimension = ref<'day' | 'month' | 'year' | 'all'>('day');

// 获取订单统计数据
async function fetchOrderStatistics() {
  try {
    console.log('Fetching order statistics with dimension:', timeDimension.value);
    
    // 使用后端API获取数据
    const response = await getOrderStatistics(timeDimension.value);
    console.log('Order statistics response:', response);
    
    let items = response.items || [];
    
    // 如果后端返回空数据，显示空状态
    if (items.length === 0) {
      console.log('No data from backend, showing empty chart');
      items = [];
    }
    
    console.log('Items for chart:', items);
    
    // 按日期排序
    items.sort((a: any, b: any) => a.date.localeCompare(b.date));
    
    // 提取日期和数量
    const dates = items.map((item: any) => {
      // 根据时间维度格式化日期显示
      const date = new Date(item.date);
      if (timeDimension.value === 'year') {
        return `${date.getFullYear()}`;
      } else if (timeDimension.value === 'month') {
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
      } else {
        return `${date.getMonth() + 1}-${String(date.getDate()).padStart(2, '0')}`;
      }
    });
    
    const orderData = items.map((item: any) => item.count);
    const amountData = items.map((item: any) => item.amount);
    
    // 计算Y轴最大值
    const maxOrderValue = Math.max(...orderData) || 10;
    const maxAmountValue = Math.max(...amountData) || 10;
    
    renderEcharts({
      grid: {
        bottom: 0,
        containLabel: true,
        left: '1%',
        right: '1%',
        top: '10%',
      },
      legend: {
        data: ['订单数', '订单金额'],
        top: 0,
      },
      series: [
        {
          data: orderData,
          type: 'line',
          name: '订单数',
          smooth: true,
          itemStyle: {
            color: '#4f9cff',
          },
          areaStyle: {
            opacity: 0.3,
            color: '#4f9cff',
          },
        },
        {
          data: amountData,
          type: 'line',
          name: '订单金额',
          smooth: true,
          itemStyle: {
            color: '#52c41a',
          },
          areaStyle: {
            opacity: 0.3,
            color: '#52c41a',
          },
        },
      ],
      tooltip: {
        axisPointer: {
          lineStyle: {
            width: 1,
          },
        },
        trigger: 'axis',
        formatter: (params: any) => {
          let result = `${params[0].axisValue}<br/>`;
          params.forEach((param: any) => {
            if (param.seriesName === '订单金额') {
              result += `${param.seriesName}: ¥${param.value.toFixed(2)}<br/>`;
            } else {
              result += `${param.seriesName}: ${param.value}<br/>`;
            }
          });
          return result;
        },
      },
      xAxis: {
        data: dates,
        type: 'category',
        boundaryGap: false,
      },
      yAxis: [
        {
          type: 'value',
          name: '订单数',
          position: 'left',
          max: Math.ceil(maxOrderValue * 1.2),
          splitNumber: 4,
        },
        {
          type: 'value',
          name: '金额(¥)',
          position: 'right',
          max: Math.ceil(maxAmountValue * 1.2),
          splitNumber: 4,
        },
      ],
    });
  } catch (error) {
    console.error('获取订单趋势数据失败:', error);
    
    // 发生错误时显示默认图表
    renderEcharts({
      grid: {
        bottom: 0,
        containLabel: true,
        left: '1%',
        right: '1%',
        top: '10%',
      },
      legend: {
        data: ['订单数', '订单金额'],
        top: 0,
      },
      series: [
        {
          data: Array(30).fill(0),
          type: 'line',
          name: '订单数',
          smooth: true,
          itemStyle: {
            color: '#4f9cff',
          },
          areaStyle: {
            opacity: 0.3,
            color: '#4f9cff',
          },
        },
        {
          data: Array(30).fill(0),
          type: 'line',
          name: '订单金额',
          smooth: true,
          itemStyle: {
            color: '#52c41a',
          },
          areaStyle: {
            opacity: 0.3,
            color: '#52c41a',
          },
        },
      ],
      tooltip: {
        axisPointer: {
          lineStyle: {
            width: 1,
          },
        },
        trigger: 'axis',
      },
      xAxis: {
        data: Array.from({ length: 30 }).map((_, index) => {
          const date = new Date();
          date.setDate(date.getDate() - 29 + index);
          return date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' });
        }),
        type: 'category',
        boundaryGap: false,
      },
      yAxis: [
        {
          type: 'value',
          name: '订单数',
          position: 'left',
          max: 10,
          splitNumber: 4,
        },
        {
          type: 'value',
          name: '金额(¥)',
          position: 'right',
          max: 10,
          splitNumber: 4,
        },
      ],
    });
  }
}


// 组件挂载时获取数据
onMounted(() => {
  fetchOrderStatistics();
});

// 监听时间维度变化
watch(timeDimension, () => {
  fetchOrderStatistics();
});
</script>

<template>
  <div>
    <div class="mb-4 flex justify-end space-x-2">
      <Button 
        :type="timeDimension === 'day' ? 'primary' : 'default'"
        @click="timeDimension = 'day'"
      >
        日
      </Button>
      <Button 
        :type="timeDimension === 'month' ? 'primary' : 'default'"
        @click="timeDimension = 'month'"
      >
        月
      </Button>
      <Button 
        :type="timeDimension === 'year' ? 'primary' : 'default'"
        @click="timeDimension = 'year'"
      >
        年
      </Button>
      <Button 
        :type="timeDimension === 'all' ? 'primary' : 'default'"
        @click="timeDimension = 'all'"
      >
        全部
      </Button>
    </div>
    <EchartsUI ref="chartRef" />
  </div>
</template>