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

defineOptions({
  name: "StatisticsOverview"
});

// ==================== 类型定义 ====================
interface CategoryStat {
  category: string;
  quantity: number;
  salesAmount: number;
  costAmount: number;
  profitAmount: number;
  profitRate: number;
  orderCount: number;
  percentage: number;
}

interface TrendData {
  dates: string[];
  label?: string;
  value?: number;
  series: { name: string; data: number[] }[];
}

interface OverviewData {
  totalSales: number;
  totalProfit: number;
  avgProfitRate: number;
  totalOrders: number;
  totalUsers: number;
  newUsers: number;
  totalDevices: number;
  onlineDevices: number;
  totalShops: number;
  repurchaseRate: number;
  avgOrderAmount: number;
  categoryList: CategoryStat[];
  salesTrend: TrendData[];
  profitTrend: TrendData[];
}

// ==================== 状态 ====================
const loading = ref(false);

// 日期范围: 默认近30天
const dateRange = ref<[Date, Date]>([
  new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
  new Date()
]);

const overviewData = ref<OverviewData>({
  totalSales: 0,
  totalProfit: 0,
  avgProfitRate: 0,
  totalOrders: 0,
  totalUsers: 0,
  newUsers: 0,
  totalDevices: 0,
  onlineDevices: 0,
  totalShops: 0,
  repurchaseRate: 0,
  avgOrderAmount: 0,
  categoryList: [],
  salesTrend: [{ dates: [], series: [] }],
  profitTrend: [{ dates: [], series: [] }]
});

// 图表引用
const salesTrendRef = ref<HTMLElement | null>(null);
const categoryPieRef = ref<HTMLElement | null>(null);
const profitTrendRef = ref<HTMLElement | null>(null);

let salesTrendChart: echarts.ECharts | null = null;
let categoryPieChart: echarts.ECharts | null = null;
let profitTrendChart: echarts.ECharts | null = null;

// 日期快捷选择
const shortcuts = [
  { key: "today", label: "今日" },
  { key: "week", label: "本周" },
  { key: "month", label: "本月" },
  { key: "30d", label: "近30天" }
];
const activeShortcut = ref("30d");

// ==================== 计算属性 ====================
const onlineRate = computed(() => {
  const { totalDevices, onlineDevices } = overviewData.value;
  if (!totalDevices || totalDevices === 0) return "0%";
  return ((onlineDevices / totalDevices) * 100).toFixed(1) + "%";
});

const newUserRate = computed(() => {
  const { totalUsers, newUsers } = overviewData.value;
  if (!totalUsers || totalUsers === 0) return "0%";
  return ((newUsers / totalUsers) * 100).toFixed(1) + "%";
});

// ==================== 日期工具函数 ====================
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];
  fetchOverviewData();
}

// ==================== 数据获取 ====================
async function fetchOverviewData() {
  loading.value = true;
  try {
    const params = {
      startDate: formatDate(dateRange.value[0]),
      endDate: formatDate(dateRange.value[1])
    };
    const res = await getStatisticsOverview(params);
    if (res.code === 200 && res.data) {
      overviewData.value = res.data;
    }
    initCharts();
  } catch (error) {
    console.error("获取统计概览数据失败:", error);
  } finally {
    loading.value = false;
  }
}

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

// ==================== 图表初始化 ====================
function initCharts() {
  setTimeout(() => {
    initSalesTrendChart();
    initCategoryPieChart();
    initProfitTrendChart();
  }, 100);
}

// 销售趋势折线图
function initSalesTrendChart() {
  if (!salesTrendRef.value) return;
  salesTrendChart?.dispose();
  salesTrendChart = echarts.init(salesTrendRef.value);

  const trend = overviewData.value.salesTrend?.[0];
  const dates = trend?.dates || [];
  const series = (trend?.series || []).map((s: any) => ({
    name: s.name,
    type: "line" as const,
    smooth: true,
    data: s.data,
    symbol: "circle",
    symbolSize: 4
  }));

  const option: EChartsOption = {
    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: "10%", containLabel: true },
    xAxis: { type: "category", data: dates, axisLabel: { rotate: 45, fontSize: 11 } },
    yAxis: { type: "value", name: "金额(元)", axisLabel: { formatter: (v: number) => v >= 10000 ? (v / 10000).toFixed(1) + "万" : String(v) } },
    series
  };
  salesTrendChart.setOption(option);
}

// 品类销售分布饼图
function initCategoryPieChart() {
  if (!categoryPieRef.value) return;
  categoryPieChart?.dispose();
  categoryPieChart = echarts.init(categoryPieRef.value);

  const list = overviewData.value.categoryList || [];
  const COLORS = ["#5470c6", "#91cc75", "#fac858", "#ee6666", "#73c0de", "#3ba272", "#fc8452", "#9a60b4"];

  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: list.slice(0, 8).map((item, i) => ({
        value: item.salesAmount,
        name: item.category,
        itemStyle: { color: COLORS[i % COLORS.length] }
      }))
    }]
  };
  categoryPieChart.setOption(option);
}

// 利润趋势面积图
function initProfitTrendChart() {
  if (!profitTrendRef.value) return;
  profitTrendChart?.dispose();
  profitTrendChart = echarts.init(profitTrendRef.value);

  const trend = overviewData.value.profitTrend?.[0];
  const dates = trend?.dates || [];
  const data = trend?.series?.[0]?.data || [];

  const option: EChartsOption = {
    title: { text: "利润趋势", left: "center", top: 10, textStyle: { fontSize: 14, fontWeight: "bold" } },
    tooltip: { trigger: "axis", backgroundColor: "#fff", borderColor: "#e5e7eb", textStyle: { color: "#333" } },
    grid: { left: "3%", right: "4%", bottom: "8%", top: "15%", containLabel: true },
    xAxis: { type: "category", data: dates, axisLabel: { rotate: 45, fontSize: 11 } },
    yAxis: { type: "value", name: "利润(元)", axisLabel: { formatter: (v: number) => v >= 10000 ? (v / 10000).toFixed(1) + "万" : String(v) } },
    series: [{
      name: "利润",
      type: "line",
      smooth: true,
      data,
      symbol: "circle",
      symbolSize: 4,
      lineStyle: { color: "#67c23a", width: 2 },
      areaStyle: { color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{ offset: 0, color: "rgba(103,194,58,0.25)" }, { offset: 1, color: "rgba(103,194,58,0.02)" }]) }
    }]
  };
  profitTrendChart.setOption(option);
}

// ==================== 响应式 ====================
function resizeCharts() {
  salesTrendChart?.resize();
  categoryPieChart?.resize();
  profitTrendChart?.resize();
}

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

onUnmounted(() => {
  window.removeEventListener("resize", resizeCharts);
  salesTrendChart?.dispose();
  categoryPieChart?.dispose();
  profitTrendChart?.dispose();
});
</script>

<template>
  <div class="statistics-overview">
    <!-- 顶部工具栏 -->
    <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">
      <!-- 第一行: 核心经营指标 -->
      <el-row :gutter="16" class="kpi-row">
        <el-col :xs="12" :sm="6" :lg="3">
          <div class="kpi-card kpi-blue">
            <div class="kpi-label">总销售额</div>
            <div class="kpi-value">¥{{ (overviewData.totalSales || 0).toLocaleString() }}</div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="6" :lg="3">
          <div class="kpi-card kpi-green">
            <div class="kpi-label">总利润</div>
            <div class="kpi-value">¥{{ (overviewData.totalProfit || 0).toLocaleString() }}</div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="6" :lg="3">
          <div class="kpi-card kpi-purple">
            <div class="kpi-label">总订单数</div>
            <div class="kpi-value">{{ (overviewData.totalOrders || 0).toLocaleString() }}</div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="6" :lg="3">
          <div class="kpi-card kpi-orange">
            <div class="kpi-label">利润率</div>
            <div class="kpi-value">{{ overviewData.avgProfitRate || 0 }}%</div>
          </div>
        </el-col>
      </el-row>

      <!-- 第二行: 辅助指标 -->
      <el-row :gutter="16" class="kpi-row">
        <el-col :xs="12" :sm="6" :lg="3">
          <div class="kpi-card kpi-cyan">
            <div class="kpi-label">购买用户</div>
            <div class="kpi-value">{{ (overviewData.totalUsers || 0).toLocaleString() }}</div>
            <div class="kpi-sub">新用户 {{ (overviewData.newUsers || 0).toLocaleString() }} ({{ newUserRate }})</div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="6" :lg="3">
          <div class="kpi-card kpi-teal">
            <div class="kpi-label">设备在线率</div>
            <div class="kpi-value">{{ onlineRate }}</div>
            <div class="kpi-sub">{{ overviewData.onlineDevices || 0 }}/{{ overviewData.totalDevices || 0 }} 台在线</div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="6" :lg="3">
          <div class="kpi-card kpi-indigo">
            <div class="kpi-label">门店数</div>
            <div class="kpi-value">{{ (overviewData.totalShops || 0).toLocaleString() }}</div>
            <div class="kpi-sub">门店</div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="6" :lg="3">
          <div class="kpi-card kpi-pink">
            <div class="kpi-label">客单价 / 复购率</div>
            <div class="kpi-value">¥{{ (overviewData.avgOrderAmount || 0).toLocaleString() }}</div>
            <div class="kpi-sub">复购率 {{ overviewData.repurchaseRate || 0 }}%</div>
          </div>
        </el-col>
      </el-row>

      <!-- 第三行: 图表区 -->
      <el-row :gutter="16" class="chart-row">
        <el-col :span="16">
          <div class="chart-box">
            <div ref="salesTrendRef" class="chart-container"></div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="chart-box">
            <div ref="categoryPieRef" class="chart-container"></div>
          </div>
        </el-col>
      </el-row>

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

<style lang="scss" scoped>
.statistics-overview {
  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 指标卡片
.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-purple { border-left-color: #722ed1; }
  &.kpi-orange { border-left-color: #fa8c16; }
  &.kpi-cyan { border-left-color: #13c2c2; }
  &.kpi-teal { border-left-color: #52c41a; }
  &.kpi-indigo { border-left-color: #597ef7; }
  &.kpi-pink { border-left-color: #eb2f96; }

  .kpi-label {
    font-size: 13px;
    color: #86909c;
    margin-bottom: 6px;
  }

  .kpi-value {
    font-size: 22px;
    font-weight: 700;
    color: #1d2129;
    line-height: 1.2;
  }

  .kpi-sub {
    font-size: 12px;
    color: #86909c;
    margin-top: 4px;
  }
}

// 图表区
.chart-row {
  margin-bottom: 12px;
}

.chart-box {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  height: 360px;

  .chart-container {
    width: 100%;
    height: 100%;
  }
}

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