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

import { onMounted, ref } from 'vue';

import { EchartsUI, useEcharts } from '@vben/plugins/echarts';

import { getOrderList } from '#/api/order/order';

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


onMounted(async () => {
  try {
    // 准备图表数据
    const dates = 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' });
    });
    
    // 准备日期数组，用于查询订单数据
    const queryDates = Array.from({ length: 30 }).map((_, index) => {
      const date = new Date();
      date.setDate(date.getDate() - 29 + index);
      return date.toISOString().split('T')[0]; // YYYY-MM-DD格式
    });
    
    // 获取每日订单数据
    const orderDataPromises = queryDates.map(async (date) => {
      try {
        // 获取当天的开始和结束时间
        const startTime = `${date} 00:00:00`;
        const endTime = `${date} 23:59:59`;
        
        // 获取当天的订单数据
        const response = await getOrderList({
          page: 1,
          pageSize: 1,
          create_time_start: startTime,
          create_time_end: endTime
        });
        
        return response.total || 0;
      } catch (error) {
        console.error(`获取${date}的订单数据失败:`, error);
        return 0;
      }
    });
    
    // 等待所有请求完成
    const orderData = await Promise.all(orderDataPromises);
    
    // 计算Y轴最大值
    const maxValue = Math.max(...orderData) || 10;
    
    renderEcharts({
      grid: {
        bottom: 0,
        containLabel: true,
        left: '1%',
        right: '1%',
        top: '2%',
      },
      series: [
        {
          data: orderData,
          type: 'line',
          name: '订单数',
          smooth: true,
          itemStyle: {
            color: '#4f9cff',
          },
          areaStyle: {
            opacity: 0.3,
            color: '#4f9cff',
          },
        },
      ],
      tooltip: {
        axisPointer: {
          lineStyle: {
            width: 1,
          },
        },
        trigger: 'axis',
        formatter: (params: any) => {
          const param = params[0];
          return `${param.axisValue}<br/>${param.seriesName}: ${param.value}`;
        },
      },
      xAxis: {
        data: dates,
        type: 'category',
        boundaryGap: false,
      },
      yAxis: {
        max: Math.ceil(maxValue * 1.2), // 比最大值大20%作为Y轴上限
        splitNumber: 4,
        type: 'value',
      },
    });
  } catch (error) {
    console.error('获取订单趋势数据失败:', error);
    
    // 发生错误时显示默认图表
    renderEcharts({
      grid: {
        bottom: 0,
        containLabel: true,
        left: '1%',
        right: '1%',
        top: '2%',
      },
      series: [
        {
          data: Array(30).fill(0),
          type: 'line',
          name: '订单数',
          smooth: true,
          itemStyle: {
            color: '#4f9cff',
          },
          areaStyle: {
            opacity: 0.3,
            color: '#4f9cff',
          },
        },
      ],
      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: {
        max: 10,
        splitNumber: 4,
        type: 'value',
      },
    });
  }
});
</script>

<template>
  <EchartsUI ref="chartRef" />
</template>
