<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from "vue";
import * as echarts from "echarts";
import { getCategoryOverview, getCategoryTrend } from "@/api/statistics";
import type { EChartsOption } from "echarts";

defineOptions({
  name: "CategoryStatistics"
});

interface CategoryStat {
  category: string;
  quantity: number;
  salesAmount: number;
  costAmount: number;
  profitAmount: number;
  profitRate: number;
  orderCount: number;
  percentage: number;
}

const loading = ref(false);
const dateRange = ref<[Date, Date]>([
  new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
  new Date()
]);
const activeShortcut = ref("30d");

const shortcuts = [
  { key: "today", label: "今日" },
  { key: "week", label: "本周" },
  { key: "month", label: "本月" },
  { key: "30d", label: "近30天" }
];

const categoryList = ref<CategoryStat[]>([]);
const selectedCategory = ref("");

const totalSales = computed(() => categoryList.value.reduce((s, i) => s + (i.salesAmount || 0), 0));
const totalProfit = computed(() => categoryList.value.reduce((s, i) => s + (i.profitAmount || 0), 0));
const avgProfitRate = computed(() => {
  if (totalSales.value === 0) return 0;
  return Number(((totalProfit.value / totalSales.value) * 100).toFixed(2));
});

// 图表引用
const pieChartRef = ref<HTMLElement | null>(null);
const barChartRef = ref<HTMLElement | null>(null);
const trendChartRef = ref<HTMLElement | null>(null);
let pieChart: echarts.ECharts | null = null;
let barChart: echarts.ECharts | null = null;
let trendChart: echarts.ECharts | null = null;

function formatDate(date: Date): string {
  return date.toISOString().split("T")[0];
}

function setDateShortcut(type: string) {
  activeShortcut.value = type;
  const today = new Date();
  today.setHours(23, 59, 59, 999);
  let start: Date;
  switch (type) {
    case "today": start = new Date(); start.setHours(0, 0, 0, 0); break;
    case "week": start = new Date(today); start.setDate(today.getDate() - 6); start.setHours(0, 0, 0, 0); break;
    case "month": start = new Date(today.getFullYear(), today.getMonth(), 1); break;
    case "30d": default: start = new Date(today); start.setDate(today.getDate() - 29); start.setHours(0, 0, 0, 0); break;
  }
  dateRange.value = [start, today];
  fetchData();
}

async function fetchData() {
  loading.value = true;
  try {
    const params = { startDate: formatDate(dateRange.value[0]), endDate: formatDate(dateRange.value[1]) };
    const res = await getCategoryOverview(params);
    if (res.code === 200 && res.data) {
      categoryList.value = res.data;
    }
    initCharts();
    fetchTrendData();
  } catch (error) {
    console.error("获取品类统计数据失败:", error);
  } finally {
    loading.value = false;
  }
}

async function fetchTrendData() {
  try {
    const params: any = {
      startDate: formatDate(dateRange.value[0]),
      endDate: formatDate(dateRange.value[1]),
      period: "day"
    };
    if (selectedCategory.value) params.category = selectedCategory.value;
    const res = await getCategoryTrend(params);
    if (res.code === 200 && res.data) {
      initTrendChart(res.data);
    }
  } catch (error) {
    console.error("获取品类趋势数据失败:", error);
  }
}

function handleCategoryClick(category: string) {
  selectedCategory.value = selectedCategory.value === category ? "" : category;
  fetchTrendData();
}

function handleDateChange() {
  activeShortcut.value = "";
  fetchData();
}

// ==================== 图表 ====================
function initCharts() {
  setTimeout(() => { initPieChart(); initBarChart(); }, 100);
}

const COLORS = ["#5470c6", "#91cc75", "#fac858", "#ee6666", "#73c0de", "#3ba272", "#fc8452", "#9a60b4"];

function initPieChart() {
  if (!pieChartRef.value) return;
  pieChart?.dispose();
  pieChart = echarts.init(pieChartRef.value);
  const option: EChartsOption = {
    title: { text: "品类销售额占比", left: "center", top: 10, textStyle: { fontSize: 14, fontWeight: "bold" } },
    tooltip: { trigger: "item", formatter: (p: any) => `${p.name}: ¥${p.value?.toLocaleString() || 0} (${p.percent}%)` },
    legend: { orient: "vertical", left: 10, top: "middle", itemWidth: 12, itemHeight: 12 },
    series: [{
      type: "pie", radius: ["45%", "72%"], center: ["58%", "55%"],
      avoidLabelOverlap: false, itemStyle: { borderRadius: 6, borderColor: "#fff", borderWidth: 2 },
      label: { show: false }, emphasis: { label: { show: true, fontSize: 16, fontWeight: "bold" } }, labelLine: { show: false },
      data: categoryList.value.slice(0, 8).map((item, i) => ({
        value: item.salesAmount, name: item.category, itemStyle: { color: COLORS[i % COLORS.length] }
      }))
    }]
  };
  pieChart.setOption(option);
}

function initBarChart() {
  if (!barChartRef.value) return;
  barChart?.dispose();
  barChart = echarts.init(barChartRef.value);
  const list = [...categoryList.value].sort((a, b) => (b.profitAmount || 0) - (a.profitAmount || 0)).slice(0, 10);
  const option: EChartsOption = {
    title: { text: "品类利润对比 (TOP10)", left: "center", top: 10, textStyle: { fontSize: 14, fontWeight: "bold" } },
    tooltip: { trigger: "axis", axisPointer: { type: "shadow" }, formatter: (p: any) => `${p[0].name}<br/>利润: ¥${p[0].value?.toLocaleString()}` },
    grid: { left: "3%", right: "8%", bottom: "3%", top: "15%", containLabel: true },
    xAxis: { type: "category", data: list.map(i => i.category), axisLabel: { rotate: 30, fontSize: 11 } },
    yAxis: { type: "value", name: "利润(元)", axisLabel: { formatter: (v: number) => v >= 10000 ? (v / 10000).toFixed(1) + "万" : String(v) } },
    series: [{ name: "利润额", type: "bar", data: list.map(i => i.profitAmount),
      itemStyle: { borderRadius: [4, 4, 0, 0], color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{ offset: 0, color: "#91cc75" }, { offset: 1, color: "#3ba272" }]) }
    }]
  };
  barChart.setOption(option);
}

function initTrendChart(data: any) {
  if (!trendChartRef.value) return;
  trendChart?.dispose();
  trendChart = echarts.init(trendChartRef.value);
  const series = (data.series || []).map((s: any) => ({ name: s.name, type: "line" as const, smooth: true, data: s.data, symbol: "circle", symbolSize: 4 }));
  const option: EChartsOption = {
    title: { text: selectedCategory.value ? `${selectedCategory.value} 销售趋势` : "品类销售趋势", left: "center", top: 10, textStyle: { fontSize: 14, fontWeight: "bold" } },
    tooltip: { trigger: "axis", backgroundColor: "#fff", borderColor: "#e5e7eb", textStyle: { color: "#333" } },
    legend: { data: series.map(s => s.name), bottom: 0 },
    grid: { left: "3%", right: "4%", bottom: "12%", top: "15%", containLabel: true },
    xAxis: { type: "category", data: data.dates || [], axisLabel: { rotate: 45, fontSize: 11 } },
    yAxis: { type: "value", name: "销售额(元)", axisLabel: { formatter: (v: number) => v >= 10000 ? (v / 10000).toFixed(1) + "万" : String(v) } },
    series
  };
  trendChart.setOption(option);
}

function resizeCharts() {
  pieChart?.resize();
  barChart?.resize();
  trendChart?.resize();
}

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

onUnmounted(() => {
  window.removeEventListener("resize", resizeCharts);
  pieChart?.dispose();
  barChart?.dispose();
  trendChart?.dispose();
});
</script>

<template>
  <div class="category-statistics">
    <!-- 工具栏 -->
    <div class="toolbar">
      <h2 class="page-title">品类销售统计</h2>
      <div class="toolbar-right">
        <div class="date-shortcuts">
          <el-button v-for="s in shortcuts" :key="s.key" :type="activeShortcut === s.key ? 'primary' : 'default'" size="small" @click="setDateShortcut(s.key)">{{ s.label }}</el-button>
        </div>
        <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" size="small" @change="handleDateChange" />
      </div>
    </div>

    <div v-loading="loading" class="page-body">
      <!-- KPI 卡片 -->
      <el-row :gutter="16" class="kpi-row">
        <el-col :span="8">
          <div class="kpi-card kpi-blue">
            <div class="kpi-label">总销售额</div>
            <div class="kpi-value">¥{{ totalSales.toLocaleString() }}</div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="kpi-card kpi-green">
            <div class="kpi-label">总利润</div>
            <div class="kpi-value">¥{{ totalProfit.toLocaleString() }}</div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="kpi-card kpi-orange">
            <div class="kpi-label">平均利润率</div>
            <div class="kpi-value">{{ avgProfitRate }}%</div>
          </div>
        </el-col>
      </el-row>

      <!-- 图表区 -->
      <el-row :gutter="16" class="chart-row">
        <el-col :span="12">
          <div class="chart-box"><div ref="pieChartRef" class="chart-container"></div></div>
        </el-col>
        <el-col :span="12">
          <div class="chart-box"><div ref="barChartRef" class="chart-container"></div></div>
        </el-col>
      </el-row>

      <el-row :gutter="16" class="chart-row">
        <el-col :span="24">
          <div class="chart-box chart-box-tall"><div ref="trendChartRef" class="chart-container"></div></div>
        </el-col>
      </el-row>

      <!-- 明细表格 -->
      <div class="table-box">
        <div class="table-header">
          <span class="table-title">品类销售明细</span>
          <span class="table-hint" v-if="selectedCategory">当前选中: <el-tag size="small" closable @close="handleCategoryClick(selectedCategory)">{{ selectedCategory }}</el-tag></span>
        </div>
        <el-table :data="categoryList" stripe v-loading="loading" @row-click="(row: any) => handleCategoryClick(row.category)" style="cursor: pointer;">
          <el-table-column prop="category" label="品类名称" min-width="120" fixed="left">
            <template #default="{ row }">
              <el-button type="primary" link size="small">{{ row.category }}</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="销售数量" width="100" align="right">
            <template #default="{ row }">{{ row.quantity?.toLocaleString() || 0 }}</template>
          </el-table-column>
          <el-table-column prop="salesAmount" label="销售额(元)" width="130" align="right" sortable>
            <template #default="{ row }">¥{{ row.salesAmount?.toLocaleString() || 0 }}</template>
          </el-table-column>
          <el-table-column prop="costAmount" label="成本额(元)" width="130" align="right">
            <template #default="{ row }">¥{{ row.costAmount?.toLocaleString() || 0 }}</template>
          </el-table-column>
          <el-table-column prop="profitAmount" label="利润额(元)" width="130" align="right" sortable>
            <template #default="{ row }">
              <span :style="{ color: (row.profitAmount || 0) >= 0 ? '#52c41a' : '#f5222d' }">¥{{ row.profitAmount?.toLocaleString() || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="profitRate" label="利润率" width="90" align="right" sortable>
            <template #default="{ row }">
              <span :style="{ color: (row.profitRate || 0) >= 0 ? '#52c41a' : '#f5222d' }">{{ row.profitRate }}%</span>
            </template>
          </el-table-column>
          <el-table-column prop="orderCount" label="订单数" width="90" align="right" sortable>
            <template #default="{ row }">{{ row.orderCount?.toLocaleString() || 0 }}</template>
          </el-table-column>
          <el-table-column prop="percentage" label="销售占比" width="100" align="right" sortable>
            <template #default="{ row }">
              <el-progress :percentage="Number(row.percentage) || 0" :stroke-width="6" :show-text="false" style="width: 60px; display: inline-block; vertical-align: middle;" />
              <span style="margin-left: 6px;">{{ row.percentage }}%</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.category-statistics {
  padding: 16px 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.toolbar {
  display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px; flex-wrap: wrap; gap: 12px;
  .page-title { margin: 0; font-size: 18px; font-weight: 600; color: #1d2129; }
  .toolbar-right { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
  .date-shortcuts { display: flex; gap: 4px; }
}

.page-body { min-height: 400px; }

.kpi-row { margin-bottom: 12px; }

.kpi-card {
  background: #fff; border-radius: 8px; padding: 16px 20px; height: 100%; border-left: 4px solid #409eff; transition: box-shadow 0.2s;
  &:hover { box-shadow: 0 2px 12px rgba(0,0,0,0.08); }
  &.kpi-blue { border-left-color: #409eff; }
  &.kpi-green { border-left-color: #67c23a; }
  &.kpi-orange { border-left-color: #fa8c16; }
  .kpi-label { font-size: 13px; color: #86909c; margin-bottom: 6px; }
  .kpi-value { font-size: 22px; font-weight: 700; color: #1d2129; line-height: 1.2; }
}

.chart-row { margin-bottom: 12px; }
.chart-box {
  background: #fff; border-radius: 8px; padding: 16px; height: 360px;
  &.chart-box-tall { height: 380px; }
  .chart-container { width: 100%; height: 100%; }
}

.table-box {
  background: #fff; border-radius: 8px; padding: 16px;
  .table-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 12px; }
  .table-title { font-size: 14px; font-weight: 600; color: #1d2129; }
  .table-hint { font-size: 13px; color: #86909c; }
}

@media (max-width: 768px) {
  .kpi-value { font-size: 18px !important; }
  .chart-box, .chart-box-tall { height: 280px; }
}
</style>
