<script setup lang="ts">
import { ref, onMounted } from "vue";
import * as echarts from "echarts";
import { getMarketingOverview } from "@/api/marketing";

defineOptions({
  name: "StatisticsOverview"
});

const loading = ref(false);
const overviewData = ref({
  totalActivities: 0,
  ongoingActivities: 0,
  totalCoupons: 0,
  issuedCoupons: 0,
  usedCoupons: 0,
  totalOrders: 0,
  totalRevenue: 0,
  avgOrderValue: 0
});

const chartRefs = ref({
  activityTrend: null as HTMLElement | null,
  couponUsage: null as HTMLElement | null,
  revenueTrend: null as HTMLElement | null
});

let activityChart: echarts.ECharts | null = null;
let couponChart: echarts.ECharts | null = null;
let revenueChart: echarts.ECharts | null = null;

async function fetchOverviewData() {
  loading.value = true;
  try {
    const { data } = await getMarketingOverview();
    overviewData.value = data;
    initCharts();
  } catch (error) {
    console.error("获取统计概览数据失败:", error);
  } finally {
    loading.value = false;
  }
}

function initCharts() {
  setTimeout(() => {
    initActivityTrendChart();
    initCouponUsageChart();
    initRevenueTrendChart();
  }, 100);
}

function initActivityTrendChart() {
  const chartDom = chartRefs.value.activityTrend;
  if (!chartDom) return;
  
  if (activityChart) {
    activityChart.dispose();
  }
  
  activityChart = echarts.init(chartDom);
  
  const option: echarts.EChartsOption = {
    title: {
      text: "活动参与趋势",
      left: "center",
      textStyle: { fontSize: 14, fontWeight: "normal" }
    },
    tooltip: {
      trigger: "axis",
      backgroundColor: "rgba(255, 255, 255, 0.9)",
      borderColor: "#e5e7eb",
      borderWidth: 1
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      data: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
    },
    yAxis: {
      type: "value"
    },
    series: [
      {
        name: "参与人数",
        type: "line",
        smooth: true,
        data: [120, 132, 101, 134, 90, 230, 210],
        itemStyle: { color: "#409eff" }
      }
    ]
  };
  
  activityChart.setOption(option);
}

function initCouponUsageChart() {
  const chartDom = chartRefs.value.couponUsage;
  if (!chartDom) return;
  
  if (couponChart) {
    couponChart.dispose();
  }
  
  couponChart = echarts.init(chartDom);
  
  const option: echarts.EChartsOption = {
    title: {
      text: "优惠券使用情况",
      left: "center",
      textStyle: { fontSize: 14, fontWeight: "normal" }
    },
    tooltip: {
      trigger: "item",
      formatter: "{a} <br/>{b}: {c} ({d}%)"
    },
    legend: {
      bottom: "5%",
      left: "center"
    },
    series: [
      {
        name: "优惠券状态",
        type: "pie",
        radius: ["40%", "70%"],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: "#fff",
          borderWidth: 2
        },
        label: {
          show: false,
          position: "center"
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 20,
            fontWeight: "bold"
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: overviewData.value.issuedCoupons, name: "已发放", itemStyle: { color: "#409eff" } },
          { value: overviewData.value.usedCoupons, name: "已使用", itemStyle: { color: "#67c23a" } },
          { value: overviewData.value.totalCoupons - overviewData.value.issuedCoupons, name: "未发放", itemStyle: { color: "#909399" } }
        ]
      }
    ]
  };
  
  couponChart.setOption(option);
}

function initRevenueTrendChart() {
  const chartDom = chartRefs.value.revenueTrend;
  if (!chartDom) return;
  
  if (revenueChart) {
    revenueChart.dispose();
  }
  
  revenueChart = echarts.init(chartDom);
  
  const option: echarts.EChartsOption = {
    title: {
      text: "营收趋势",
      left: "center",
      textStyle: { fontSize: 14, fontWeight: "normal" }
    },
    tooltip: {
      trigger: "axis",
      backgroundColor: "rgba(255, 255, 255, 0.9)",
      borderColor: "#e5e7eb",
      borderWidth: 1
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      data: ["1月", "2月", "3月", "4月", "5月", "6月"]
    },
    yAxis: {
      type: "value"
    },
    series: [
      {
        name: "营收",
        type: "bar",
        data: [12000, 19000, 15000, 25000, 22000, 30000],
        itemStyle: { color: "#67c23a" }
      }
    ]
  };
  
  revenueChart.setOption(option);
}

function resizeCharts() {
  activityChart?.resize();
  couponChart?.resize();
  revenueChart?.resize();
}

onMounted(() => {
  fetchOverviewData();
  window.addEventListener("resize", resizeCharts);
});

// 组件卸载时清理事件监听器和图表实例
// 这里省略了清理逻辑以保持简洁
</script>

<template>
  <div class="statistics-overview">
    <!-- 数据概览卡片 -->
    <el-row :gutter="20" class="mb-6">
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-card">
            <div class="stat-icon bg-blue">
              <i class="ri-calendar-event-line"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ overviewData.totalActivities }}</div>
              <div class="stat-label">总活动数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-card">
            <div class="stat-icon bg-green">
              <i class="ri:play-circle-line"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ overviewData.ongoingActivities }}</div>
              <div class="stat-label">进行中活动</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-card">
            <div class="stat-icon bg-purple">
              <i class="ri:coupon-3-line"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ overviewData.totalCoupons }}</div>
              <div class="stat-label">总优惠券</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-card">
            <div class="stat-icon bg-orange">
              <i class="ri:money-cny-circle-line"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ overviewData.totalRevenue.toLocaleString() }}</div>
              <div class="stat-label">总营收</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card shadow="hover" class="chart-card">
          <div ref="chartRefs.activityTrend" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="chart-card">
          <div ref="chartRefs.couponUsage" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="chart-card">
          <div ref="chartRefs.revenueTrend" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style lang="scss" scoped>
.statistics-overview {
  .stat-card {
    display: flex;
    align-items: center;
    
    .stat-icon {
      width: 50px;
      height: 50px;
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 16px;
      
      i {
        font-size: 24px;
        color: white;
      }
      
      &.bg-blue { background: linear-gradient(135deg, #409eff, #337ecc); }
      &.bg-green { background: linear-gradient(135deg, #67c23a, #529b2e); }
      &.bg-purple { background: linear-gradient(135deg, #722ed1, #531dab); }
      &.bg-orange { background: linear-gradient(135deg, #fa8c16, #d46b08); }
    }
    
    .stat-info {
      flex: 1;
      
      .stat-value {
        font-size: 24px;
        font-weight: 600;
        color: var(--el-text-color-primary);
        margin-bottom: 4px;
      }
      
      .stat-label {
        font-size: 14px;
        color: var(--el-text-color-secondary);
      }
    }
  }
  
  .chart-card {
    height: 350px;
    
    .chart-container {
      width: 100%;
      height: 300px;
    }
  }
}
</style>