<template>
  <div class="statistics-container">
    <el-row :gutter="20" class="data-overview">
      <el-col :xs="12" :sm="12" :md="6" v-for="item in summaryData" :key="item.title">
        <el-card shadow="hover" class="data-card">
          <div class="card-content">
            <div class="icon-box" :style="{ backgroundColor: item.color }">
              <el-icon><component :is="item.icon" /></el-icon>
            </div>
            <div class="text-box">
              <div class="title">{{ item.title }}</div>
              <div class="value">{{ item.value.toLocaleString() }}</div>
              <div class="trend" :class="item.isUp ? 'up' : 'down'">
                {{ item.isUp ? '↑' : '↓' }} {{ item.percentage }}%
                <span>{{ item.trendLabel ?? '较上月' }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="charts-row charts-row--token-bar">
      <el-col :xs="24" :sm="24" :md="12">
        <el-card shadow="hover" header="Token售卖统计">
          <div ref="lineChartRef" class="chart-box"></div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="24" :md="12">
        <el-card shadow="hover" header="号池账号统计">
          <div ref="barChartRef" class="chart-box"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="charts-row">
      <el-col :span="24">
        <el-card shadow="hover" header="用户等级分布">
          <div ref="pieChartRef" class="chart-box"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, shallowRef, nextTick } from 'vue';
import * as echarts from 'echarts';
import { ElMessage } from 'element-plus';
import { User, Pointer, Connection, ShoppingCart } from '@element-plus/icons-vue';
import { getAccountPoolDailyExtract, getAccountPoolInventoryTotals } from '@/api/home';

// --- 类型定义 ---
interface SummaryItem {
  title: string;
  value: number;
  icon: any;
  color: string;
  percentage: number;
  isUp: boolean;
  /** 趋势说明，默认「较上月」 */
  trendLabel?: string;
}

// --- 响应式数据 ---
const lineChartRef = ref<HTMLElement | null>(null);
const pieChartRef = ref<HTMLElement | null>(null);
const barChartRef = ref<HTMLElement | null>(null);
const lineChartInstance = shallowRef<echarts.ECharts | null>(null);
const pieChartInstance = shallowRef<echarts.ECharts | null>(null);
const barChartInstance = shallowRef<echarts.ECharts | null>(null);

const summaryData = ref<SummaryItem[]>([
  { title: '总用户数', value: 12840, icon: User, color: '#3973FF', percentage: 12, isUp: true },
  { title: '今日新增', value: 156, icon: Pointer, color: '#67C23A', percentage: 5, isUp: true },
  { title: '活跃用户', value: 3420, icon: Connection, color: '#E6A23C', percentage: 2, isUp: false },
  {
    title: '今日售卖',
    value: 0,
    icon: ShoppingCart,
    color: '#F56C6C',
    percentage: 0,
    isUp: true,
    trendLabel: '较昨日',
  },
]);

/** 三条产品线当日销量之和，及相对昨日的涨跌比例（用于首页第四张卡片） */
function todaySalesVsYesterday(cursor: number[], kiro: number[], windsurf: number[]) {
  const n = Math.min(cursor.length, kiro.length, windsurf.length);
  if (n < 1) return { today: 0, pct: 0, isUp: true };
  const iToday = n - 1;
  const today = cursor[iToday] + kiro[iToday] + windsurf[iToday];
  if (n < 2) return { today, pct: 0, isUp: true };
  const iY = n - 2;
  const yesterday = cursor[iY] + kiro[iY] + windsurf[iY];
  if (yesterday > 0) {
    const raw = Math.round(((today - yesterday) / yesterday) * 100);
    return { today, pct: Math.abs(raw), isUp: today >= yesterday };
  }
  return { today, pct: today > 0 ? 100 : 0, isUp: true };
}

function buildSalesLineOption(
  days: string[],
  cursor: number[],
  kiro: number[],
  windsurf: number[],
) {
  const showSymbol = days.length <= 31;
  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'cross' },
    },
    legend: {
      data: ['Cursor', 'Kiro', 'Windsurf'],
      top: 4,
    },
    grid: { left: '3%', right: '4%', bottom: '3%', top: 52, containLabel: true },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: days,
    },
    yAxis: {
      type: 'value',
      minInterval: 1,
    },
    series: [
      {
        name: 'Cursor',
        type: 'line',
        smooth: true,
        showSymbol,
        data: cursor,
        areaStyle: { opacity: 0.08 },
        lineStyle: { width: 2 },
        itemStyle: { color: '#3973FF' },
      },
      {
        name: 'Kiro',
        type: 'line',
        smooth: true,
        showSymbol,
        data: kiro,
        areaStyle: { opacity: 0.08 },
        lineStyle: { width: 2 },
        itemStyle: { color: '#67C23A' },
      },
      {
        name: 'Windsurf',
        type: 'line',
        smooth: true,
        showSymbol,
        data: windsurf,
        areaStyle: { opacity: 0.08 },
        lineStyle: { width: 2 },
        itemStyle: { color: '#E6A23C' },
      },
    ],
  };
}

function buildInventoryBarOption(labels: string[], totalData: number[], soldData: number[]) {
  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
    },
    legend: {
      data: ['账号总数', '已售卖'],
      top: 8,
    },
    grid: { left: '3%', right: '4%', bottom: '3%', top: 48, containLabel: true },
    xAxis: {
      type: 'category',
      data: labels,
      axisTick: { alignWithLabel: true },
    },
    yAxis: {
      type: 'value',
      minInterval: 1,
    },
    series: [
      {
        name: '账号总数',
        type: 'bar',
        data: totalData,
        barMaxWidth: 56,
        itemStyle: { color: '#409EFF', borderRadius: [4, 4, 0, 0] },
      },
      {
        name: '已售卖',
        type: 'bar',
        data: soldData,
        barMaxWidth: 56,
        itemStyle: { color: '#67C23A', borderRadius: [4, 4, 0, 0] },
      },
    ],
  };
}

async function loadAccountPoolInventoryTotals() {
  await nextTick();
  if (!barChartRef.value) return;
  if (!barChartInstance.value) {
    barChartInstance.value = echarts.init(barChartRef.value);
  }
  try {
    const res = await getAccountPoolInventoryTotals();
    if (res?.code !== 200) {
      ElMessage.error((res as { msg?: string })?.msg || '加载号池统计失败');
      return;
    }
    const data = (res as { data?: { modules?: Array<{ label: string; total: number; sold: number }> } }).data;
    const mods = Array.isArray(data?.modules) ? data!.modules : [];
    const labels = mods.map((m) => m.label || '');
    const totalData = mods.map((m) => Number(m.total) || 0);
    const soldData = mods.map((m) => Number(m.sold) || 0);
    barChartInstance.value.setOption(
      buildInventoryBarOption(labels.length ? labels : ['Cursor', 'Kiro', 'Windsurf'], totalData, soldData),
      { notMerge: true },
    );
  } catch {
    ElMessage.error('加载号池统计失败');
  }
}

async function loadAccountPoolDailyExtract() {
  await nextTick();
  if (!lineChartRef.value) return;
  if (!lineChartInstance.value) {
    lineChartInstance.value = echarts.init(lineChartRef.value);
  }
  try {
    const res = await getAccountPoolDailyExtract({ days: 14 });
    if (res?.code !== 200) {
      ElMessage.error((res as { msg?: string })?.msg || '加载售卖数据失败');
      return;
    }
    const d = (res as { data?: Record<string, unknown> }).data || {};
    const days = Array.isArray(d.days) ? (d.days as string[]) : [];
    const cursor = Array.isArray(d.cursor) ? (d.cursor as number[]) : [];
    const kiro = Array.isArray(d.kiro) ? (d.kiro as number[]) : [];
    const windsurf = Array.isArray(d.windsurf) ? (d.windsurf as number[]) : [];
    lineChartInstance.value.setOption(buildSalesLineOption(days, cursor, kiro, windsurf), {
      notMerge: true,
    });

    const sale = todaySalesVsYesterday(cursor, kiro, windsurf);
    const row = summaryData.value[3];
    if (row) {
      summaryData.value[3] = {
        ...row,
        value: sale.today,
        percentage: sale.pct,
        isUp: sale.isUp,
      };
    }
  } catch {
    ElMessage.error('加载售卖数据失败');
  }
}

const initPieChart = () => {
  if (!pieChartRef.value) return;
  pieChartInstance.value = echarts.init(pieChartRef.value);
  pieChartInstance.value.setOption({
    tooltip: { trigger: 'item' },
    legend: {
      orient: 'vertical',
      right: '5%',
      top: 'center',
    },
    series: [
      {
        name: '等级分布',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['35%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: { borderRadius: 10, borderColor: '#fff', borderWidth: 2 },
        label: { show: false },
        data: [
          { value: 1048, name: '普通用户' },
          { value: 735, name: 'VIP会员' },
          { value: 580, name: '超级管理员' },
          { value: 484, name: '运营人员' },
        ],
      },
    ],
  });
};

const initLineChartShell = () => {
  if (!lineChartRef.value) return;
  lineChartInstance.value = echarts.init(lineChartRef.value);
  lineChartInstance.value.setOption(
    buildSalesLineOption([], [], [], []),
    { notMerge: true },
  );
};

const initBarChartShell = () => {
  if (!barChartRef.value) return;
  barChartInstance.value = echarts.init(barChartRef.value);
  barChartInstance.value.setOption(
    buildInventoryBarOption(['Cursor', 'Kiro', 'Windsurf'], [0, 0, 0], [0, 0, 0]),
    { notMerge: true },
  );
};

// --- 生命周期与自适应 ---
const handleResize = () => {
  lineChartInstance.value?.resize();
  pieChartInstance.value?.resize();
  barChartInstance.value?.resize();
};

onMounted(async () => {
  await nextTick();
  initLineChartShell();
  initBarChartShell();
  initPieChart();
  void loadAccountPoolDailyExtract();
  void loadAccountPoolInventoryTotals();
  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  lineChartInstance.value?.dispose();
  lineChartInstance.value = null;
  pieChartInstance.value?.dispose();
  pieChartInstance.value = null;
  barChartInstance.value?.dispose();
  barChartInstance.value = null;
});
</script>

<style scoped lang="less">
.statistics-container {
  padding: 20px;
  min-height: 100vh;

  .data-overview {
    margin-bottom: 20px;

    .data-card {
      margin-bottom: 16px;

      .card-content {
        display: flex;
        align-items: center;

        .icon-box {
          width: 56px;
          height: 56px;
          flex-shrink: 0;
          border-radius: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 15px;
          color: #fff;
          font-size: 24px;
        }

        .text-box {
          min-width: 0;
          .title {
            font-size: 14px;
            color: #909399;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
          .value {
            font-size: 24px;
            font-weight: bold;
            margin: 4px 0;
            color: var(--el-text-color-primary);
          }
          .trend {
            font-size: 12px;
            &.up { color: #67c23a; }
            &.down { color: #f56c6c; }
            span { color: #909399; margin-left: 4px; }
          }
        }
      }
    }
  }

  .charts-row {
    .el-col {
      margin-bottom: 16px;
    }
    .chart-box {
      height: 350px;
      width: 100%;
    }
    &--token-bar .chart-box {
      height: 340px;
    }
  }
}

@media (max-width: 768px) {
  .statistics-container {
    padding: 12px;

    .data-overview .data-card .card-content {
      .icon-box {
        width: 44px;
        height: 44px;
        font-size: 20px;
        margin-right: 10px;
      }
      .text-box .value {
        font-size: 20px;
      }
    }

    .charts-row .chart-box {
      height: 300px;
    }
  }
}

// 深度修改 Element Plus 卡片头部样式
:deep(.el-card__header) {
  font-weight: bold;
  font-size: 16px;
  border-bottom: 1px solid #ebeef5;
}
</style>