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

defineOptions({
  name: "CategoryStatistics"
});

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

const categoryList = ref([]);
const totalSales = ref(0);
const totalProfit = ref(0);
const avgProfitRate = ref(0);

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;

async function fetchData() {
  loading.value = true;
  try {
    const params = {
      startDate: formatDate(dateRange.value[0]),
      endDate: formatDate(dateRange.value[1])
    };
    
    const { data } = await getCategoryOverview(params);
    categoryList.value = data;
    
    totalSales.value = data.reduce((sum: number, item: any) => sum + (item.salesAmount || 0), 0);
    totalProfit.value = data.reduce((sum: number, item: any) => sum + (item.profitAmount || 0), 0);
    avgProfitRate.value = totalSales.value > 0 
      ? Number((totalProfit.value / totalSales.value * 100).toFixed(2))
      : 0;
    
    initCharts();
    await fetchTrendData();
  } catch (error) {
    console.error("获取品类统计数据失败:", error);
  } finally {
    loading.value = false;
  }
}

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

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

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

function initPieChart() {
  if (!pieChartRef.value) return;
  
  if (pieChart) {
    pieChart.dispose();
  }
  
  pieChart = echarts.init(pieChartRef.value);
  
  const option: echarts.EChartsOption = {
    title: {
      text: "品类销售额占比",
      left: "center",
      textStyle: { fontSize: 14, fontWeight: "normal" }
    },
    tooltip: {
      trigger: "item",
      formatter: "{a} <br/>{b}: ¥{c} ({d}%)"
    },
    legend: {
      orient: "vertical",
      left: "left",
      top: "middle"
    },
    series: [
      {
        name: "销售额",
        type: "pie",
        radius: ["40%", "70%"],
        center: ["60%", "50%"],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: "#fff",
          borderWidth: 2
        },
        label: {
          show: false,
          position: "center"
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: "bold"
          }
        },
        labelLine: {
          show: false
        },
        data: categoryList.value.slice(0, 8).map((item: any) => ({
          value: item.salesAmount,
          name: item.category
        }))
      }
    ]
  };
  
  pieChart.setOption(option);
}

function initBarChart() {
  if (!barChartRef.value) return;
  
  if (barChart) {
    barChart.dispose();
  }
  
  barChart = echarts.init(barChartRef.value);
  
  const categories = categoryList.value.slice(0, 10);
  
  const option: echarts.EChartsOption = {
    title: {
      text: "品类利润对比",
      left: "center",
      textStyle: { fontSize: 14, fontWeight: "normal" }
    },
    tooltip: {
      trigger: "axis",
      axisPointer: { type: "shadow" }
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      data: categories.map((item: any) => item.category),
      axisLabel: {
        rotate: 30
      }
    },
    yAxis: {
      type: "value",
      name: "利润(元)"
    },
    series: [
      {
        name: "利润额",
        type: "bar",
        data: categories.map((item: any) => item.profitAmount),
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "#83bff6" },
            { offset: 0.5, color: "#188df0" },
            { offset: 1, color: "#188df0" }
          ])
        }
      }
    ]
  };
  
  barChart.setOption(option);
}

function initTrendChart(data: any) {
  if (!trendChartRef.value) return;
  
  if (trendChart) {
    trendChart.dispose();
  }
  
  trendChart = echarts.init(trendChartRef.value);
  
  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
    },
    legend: {
      data: data.series?.map((s: any) => s.name) || [],
      bottom: 0
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "15%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      data: data.dates || [],
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: "value",
      name: "销售额(元)"
    },
    series: (data.series || []).map((s: any) => ({
      name: s.name,
      type: "line",
      smooth: true,
      data: s.data
    }))
  };
  
  trendChart.setOption(option);
}

function handleDateChange() {
  fetchData();
}

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

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

<template>
  <div class="category-statistics">
    <el-card shadow="never" class="mb-4">
      <div class="flex items-center justify-between">
        <span class="text-lg font-medium">品类销售统计</span>
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          @change="handleDateChange"
        />
      </div>
    </el-card>

    <el-row :gutter="20" class="mb-6">
      <el-col :span="8">
        <el-card shadow="hover" class="stat-card-wrapper">
          <div class="stat-card">
            <div class="stat-icon bg-blue">
              <i class="ri:money-cny-circle-line"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ totalSales.toLocaleString() }}</div>
              <div class="stat-label">总销售额</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="stat-card-wrapper">
          <div class="stat-card">
            <div class="stat-icon bg-green">
              <i class="ri:profit-line"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ totalProfit.toLocaleString() }}</div>
              <div class="stat-label">总利润</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="stat-card-wrapper">
          <div class="stat-card">
            <div class="stat-icon bg-orange">
              <i class="ri:percent-line"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ avgProfitRate }}%</div>
              <div class="stat-label">平均利润率</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mb-6">
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <div ref="pieChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <div ref="barChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-card shadow="hover" class="chart-card mb-6">
      <div ref="trendChartRef" class="chart-container" style="height: 350px;"></div>
    </el-card>

    <el-card shadow="never">
      <template #header>
        <span class="font-medium">品类销售明细</span>
      </template>
      <el-table :data="categoryList" stripe v-loading="loading">
        <el-table-column prop="category" label="品类名称" min-width="120" />
        <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="120" align="right">
          <template #default="{ row }">
            ¥{{ row.salesAmount?.toLocaleString() || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="costAmount" label="成本额(元)" width="120" align="right">
          <template #default="{ row }">
            ¥{{ row.costAmount?.toLocaleString() || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="profitAmount" label="利润额(元)" width="120" align="right">
          <template #default="{ row }">
            <span :class="row.profitAmount >= 0 ? 'text-green-500' : 'text-red-500'">
              ¥{{ row.profitAmount?.toLocaleString() || 0 }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="profitRate" label="利润率" width="100" align="right">
          <template #default="{ row }">
            <span :class="row.profitRate >= 0 ? 'text-green-500' : 'text-red-500'">
              {{ row.profitRate }}%
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="orderCount" label="订单数" width="100" align="right">
          <template #default="{ row }">
            {{ row.orderCount?.toLocaleString() || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="percentage" label="销售占比" width="100" align="right">
          <template #default="{ row }">
            {{ row.percentage }}%
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

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

.stat-card-wrapper {
  :deep(.el-card__body) {
    padding: 20px;
  }
}

.stat-card {
  display: flex;
  align-items: center;
  
  .stat-icon {
    width: 56px;
    height: 56px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 16px;
    
    i {
      font-size: 28px;
      color: white;
    }
    
    &.bg-blue { background: linear-gradient(135deg, #409eff, #337ecc); }
    &.bg-green { background: linear-gradient(135deg, #67c23a, #529b2e); }
    &.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;
  
  :deep(.el-card__body) {
    padding: 20px;
    height: 100%;
  }
  
  .chart-container {
    width: 100%;
    height: 100%;
    min-height: 280px;
  }
}
</style>
