<template>
  <div class="app-container home">
    <!-- 时间筛选区域 -->
    <!-- 时间筛选区域 -->
    <div class="time-filter">
      <el-button size="small" :type="timeFilter === 'day' ? 'primary' : 'default'" @click="handleTimeFilter('day')"> 今日 </el-button>
      <el-button size="small" :type="timeFilter === 'three' ? 'primary' : 'default'" @click="handleTimeFilter('three')"> 近三天 </el-button>
      <el-button size="small" :type="timeFilter === 'week' ? 'primary' : 'default'" @click="handleTimeFilter('week')"> 近七天 </el-button>
      <el-button size="small" :type="timeFilter === 'month' ? 'primary' : 'default'" @click="handleTimeFilter('month')"> 本月 </el-button>

      <span class="filter-label">选择时间：</span>
      <el-date-picker v-model="startTime" type="datetime" placeholder="请选择开始时间" value-format="YYYY-MM-DD HH:mm:ss" style="width: 180px" />
      <span>至</span>
      <el-date-picker v-model="endTime" type="datetime" placeholder="请选择结束时间" value-format="YYYY-MM-DD HH:mm:ss" style="width: 180px" />
      <el-button size="small" type="primary" @click="queryData">查询</el-button>
      <el-button size="small" @click="resetFilter">重置</el-button>
    </div>

    <!-- 统计卡片区域 -->
    <div class="statistic-cards">
      <div class="stat-card">
        <div class="card-header">比赛场次</div>
        <div class="card-value">{{ matchCount }}</div>
      </div>
      <div class="stat-card">
        <div class="card-header">充值数</div>
        <div class="card-value">{{ rechargeCount }}</div>
      </div>
      <div class="stat-card">
        <div class="card-header">充值金额</div>
        <div class="card-value">{{ rechargeAmount }}</div>
      </div>
      <div class="stat-card">
        <div class="card-header">三湘杯参赛资格发放数</div>
        <div class="card-value">{{ qualificationIssued }}</div>
      </div>
      <div class="stat-card">
        <div class="card-header">三湘杯参赛资格核销数</div>
        <div class="card-value">{{ qualificationUsed }}</div>
      </div>
    </div>

    <!-- 折线图区域 -->
    <div class="chart-container">
      <div class="chart-header">
        <div class="chart-title">折线图</div>
      </div>
      <div class="chart-content">
        <div ref="chartRef" class="chart"></div>
      </div>
    </div>
  </div>
</template>

<script setup name="Index" lang="ts">
import { ref, onMounted } from 'vue';
import * as echarts from 'echarts';
import { getStatisticsInfo, getStatisticsGraphInfo } from '@/api/system/business/statistics'; // 导入API
// 时间筛选相关
const startTime = ref('');
const endTime = ref('');
// 修改 timeFilter 的定义
const timeFilter = ref<'day' | 'three' | 'week' | 'month' | 'otherTime'>('day');

// 统计数据
const matchCount = ref(0);
const rechargeCount = ref(0);
const rechargeAmount = ref('0');
const qualificationIssued = ref(0);
const qualificationUsed = ref(0);

// 图表相关
const chartRef = ref<HTMLDivElement | null>(null);
let chartInstance: any;

// 时间筛选处理
const handleTimeFilter = (type: string) => {
  timeFilter.value = type as 'day' | 'three' | 'week' | 'month' | 'otherTime';
  startTime.value = '';
  endTime.value = '';
  // 这里可以设置对应的时间范围
  fetchStatisticsData();
  fetchGraphData(); // 获取图表数据
};

// 重置筛选条件
const resetFilter = () => {
  startTime.value = '';
  endTime.value = '';
  timeFilter.value = 'day';
};

// 获取图表数据
const fetchGraphData = async () => {
  try {
    const params = {
      flagType: timeFilter.value,
      startTime: startTime.value || undefined,
      endTime: endTime.value || undefined
    };

    const res = await getStatisticsGraphInfo(params);
    if (res.code === 200) {
      const data = res.data;

      // 更新图表数据
      updateChart(data);
    }
  } catch (error) {
    console.error('获取图表数据失败:', error);
  }
};

// 在 updateChart 函数中添加数据验证
const updateChart = (data: any) => {
  // 使用从后端获取的日期数据
  const timeData = data.dates || [];

  // 设置图表选项
  const option = {
    title: {
      /* text: 'Stacked Line',*/
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['充值数', '充值金额', '三湘杯参赛资格发放数', '三湘杯参赛资格核销数']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: timeData
    },
    yAxis: {
      type: 'value',
      minInterval: 1 // 设置最小间隔为1
    },
    series: [
      {
        name: '充值数',
        type: 'line',
        stack: 'Total',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        data: data.payOrderCountIds || []
      },
      {
        name: '充值金额',
        type: 'line',
        stack: 'Total',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        data:
          data.payOrderAmountIds?.map((item: any) => {
            if (item && typeof item === 'object') {
              // 使用 BigDecimal 的 toPlainString() 方法转换为字符串
              return item.toPlainString ? item.toPlainString() : Number(item);
            }
            return Number(item);
          }) || []
      },
      {
        name: '三湘杯参赛资格发放数',
        type: 'line',
        stack: 'Total',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        data: data.sanXiangCardCountIds || []
      },
      {
        name: '三湘杯参赛资格核销数',
        type: 'line',
        stack: 'Total',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        data: data.selectCheckRecordSanXiangCountIds || []
      }
    ]
  };

  // 设置图表选项
  chartInstance.setOption(option);
};


// 初始化图表
const initChart = () => {
  if (!chartInstance && chartRef.value) {
    chartInstance = echarts.init(chartRef.value);

    // 初始化时设置基本配置
    const option = {
      title: {
       /* text: '',*/
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: ['充值数', '充值金额', '三湘杯参赛资格发放数', '三湘杯参赛资格核销数']
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: []
      },
      yAxis: {
        type: 'value'
      },
      series: []
    };

    chartInstance.setOption(option);
  }
};
// 获取统计数据
const fetchStatisticsData = async () => {
  try {
    const params = {
      flagType: timeFilter.value, // 根据实际需求调整
      startTime: startTime.value || undefined,
      endTime: endTime.value || undefined
    };

    const res = await getStatisticsInfo(params);
    if (res.code === 200) {
      const data = res.data;
      matchCount.value = data.tournamentCount || 0;
      rechargeCount.value = data.payOrderCount || 0;
      rechargeAmount.value = data.payOrderAmount ? data.payOrderAmount.toFixed(0) : '0';
      qualificationIssued.value = data.sanXiangCardCount || 0;
      qualificationUsed.value = data.selectCheckRecordSanXiangCount || 0;
    }
  } catch (error) {
    console.error('获取统计数据失败:', error);
  }
};
// 查询数据
const queryData = () => {
  timeFilter.value = 'otherTime';
  fetchStatisticsData();
  fetchGraphData(); // 获取图表数据
};
// 页面加载完成后初始化图表
onMounted(() => {
  initChart();
  timeFilter.value = 'month';
  fetchStatisticsData();
  fetchGraphData(); // 获取图表数据
});
</script>

<style lang="scss" scoped>
.home {
  padding: 20px;
}

.time-filter {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;

  .filter-label {
    margin: 0 10px;
  }
}

.statistic-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
  margin-bottom: 20px;
}

.stat-card {
  background: #f5f5f5;
  border-radius: 8px;
  padding: 20px;
  text-align: center;

  .card-header {
    font-size: 14px;
    color: #666;
    margin-bottom: 10px;
  }

  .card-value {
    font-size: 36px;
    font-weight: bold;
    color: #333;
  }
}

.chart-container {
  background: #f5f5f5;
  border-radius: 8px;
  padding: 20px;
  margin-top: 20px;
}

.chart-header {
  margin-bottom: 15px;
}

.chart-title {
  font-size: 24px;
  color: #333;
}

.chart-content {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
}

.chart {
  width: 100%;
  height: 400px;
}
</style>
