<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" @click="navigateToStaticTop('match')">
        <div class="card-header">比赛场次</div>
        <div class="card-value">{{ matchCount }}</div>
        <!-- 添加点击反馈图标 -->
        <div class="click-indicator">
          <i class="el-icon el-icon-arrow-right"></i>
        </div>
      </div>
      <div class="stat-card" @click="navigateToStaticTop('rechargeCount')">
        <div class="card-header">充值数</div>
        <div class="card-value">{{ rechargeCount }}</div>
      </div>
      <div class="stat-card" @click="navigateToStaticTop('rechargeAmount')">
        <div class="card-header">充值金额</div>
        <div class="card-value">{{ rechargeAmount }}</div>
      </div>
      <!--      <div class="stat-card" @click="navigateToStaticTop('qualificationIssued')">
        <div class="card-header">三湘杯参赛资格发放数</div>
        <div class="card-value">{{ qualificationIssued }}</div>
      </div>
      <div class="stat-card" @click="navigateToStaticTop('qualificationUsed')">
        <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 { proxy } = getCurrentInstance() as ComponentInternalInstance;
// 图表相关
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',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        data: data.payOrderCountIds || []
      },
      {
        name: '充值金额',
        type: 'line',
        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',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        data: data.sanXiangCardCountIds || []
      },
      {
        name: '三湘杯参赛资格核销数',
        type: 'line',
        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 || 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(); // 获取图表数据
});

// 跳转到 staticTop 页面并携带参数
const navigateToStaticTop = (cardType: string) => {
  // 根据 cardType 的值跳转到不同的路由
  switch (cardType) {
    case 'match':
      proxy?.$router.push({
        path: '/datas/tournamentTop',
        query: {
          cardType: cardType,
          timeFilter: timeFilter.value,
          startTime: startTime.value,
          endTime: endTime.value
        }
      });
      break;
    case 'rechargeCount':
    case 'rechargeAmount':
      proxy?.$router.push({
        path: '/datas/rechargeTop',
        query: {
          cardType: cardType,
          timeFilter: timeFilter.value,
          startTime: startTime.value,
          endTime: endTime.value
        }
      });
      break; /*
    case 'qualificationIssued':
      proxy?.$router.push({
        path: '/service/toolsTop',
        query: {
          cardType: cardType,
          timeFilter: timeFilter.value,
          startTime: startTime.value,
          endTime: endTime.value
        }
      });
      break;*/
    /*    case 'qualificationUsed':
      proxy?.$router.push({
        path: '/service/checkRecord',
        query: {
          cardType: cardType,
          timeFilter: timeFilter.value,
          startTime: startTime.value,
          endTime: endTime.value
        }
      });
      break;*/
    default:
      // 默认跳转到 tournamentTop 页面
      proxy?.$router.push({
        path: '/service/tournamentTop',
        query: {
          cardType: cardType,
          timeFilter: timeFilter.value,
          startTime: startTime.value,
          endTime: endTime.value
        }
      });
  }
};
</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;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    background: #e6f7ff;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }

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

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

/* 为不同类型的统计数字设置不同颜色 */
.stat-card:nth-child(1) .card-value {
  /* 比赛场次 */
  color: #409eff; /* 蓝色 */
}

.stat-card:nth-child(2) .card-value {
  /* 充值数 */
  color: #67c23a; /* 绿色 */
}

.stat-card:nth-child(3) .card-value {
  /* 充值金额 */
  color: #e6a23c; /* 橙色 */
}

.stat-card:nth-child(4) .card-value {
  /* 三湘杯参赛资格发放数 */
  color: #f56c6c; /* 红色 */
}

.stat-card:nth-child(5) .card-value {
  /* 三湘杯参赛资格核销数 */
  color: #909399; /* 灰色 */
}

.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;
}

.stat-card {
  background: #f5f5f5;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  cursor: pointer; /* 添加小手光标 */
  transition: all 0.3s ease; /* 添加过渡效果 */

  &:hover {
    background: #e6f7ff; /* 悬停时背景变色 */
    transform: translateY(-2px); /* 轻微上移效果 */
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); /* 添加阴影 */
  }

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

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