<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from "vue";
import * as echarts from "echarts";
import { getDashboard } from "@/api/distribution";
import type { DashboardData, MonthlyTrend } from "../utils/types";

defineOptions({
  name: "DistributionDashboard"
});

const loading = ref(false);
const dashboardData = ref<DashboardData>({
  totalDistributors: 0,
  activeDistributors: 0,
  totalReferrals: 0,
  validReferrals: 0,
  totalCommission: 0,
  monthlyCommission: 0,
  trends: []
});

const chartRef = ref<HTMLDivElement | null>(null);
let chartInstance: echarts.ECharts | null = null;

function formatMoney(value: number): string {
  return `¥${value.toLocaleString("zh-CN", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })}`;
}

async function fetchDashboardData() {
  loading.value = true;
  try {
    const { data } = await getDashboard();
    if (data) {
      dashboardData.value = data;
      initChart();
    }
  } catch (error) {
    console.error("获取分销仪表盘数据失败:", error);
  } finally {
    loading.value = false;
  }
}

function initChart() {
  setTimeout(() => {
    const chartDom = chartRef.value;
    if (!chartDom) return;

    if (chartInstance) {
      chartInstance.dispose();
    }

    chartInstance = echarts.init(chartDom);

    const trends: MonthlyTrend[] = dashboardData.value.trends || [];
    const xData = trends.map(item => item.yearMonth);
    const referralData = trends.map(item => item.referralCount);
    const validData = trends.map(item => item.validCount);
    const commissionData = trends.map(item => item.commissionAmount);

    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,
        axisPointer: {
          type: "cross"
        }
      },
      legend: {
        data: ["拉新人数", "有效用户数", "佣金金额"],
        bottom: 0
      },
      grid: {
        left: "3%",
        right: "4%",
        bottom: "15%",
        top: "12%",
        containLabel: true
      },
      xAxis: {
        type: "category",
        data: xData,
        axisPointer: {
          type: "shadow"
        }
      },
      yAxis: [
        {
          type: "value",
          name: "人数",
          position: "left"
        },
        {
          type: "value",
          name: "金额(元)",
          position: "right"
        }
      ],
      series: [
        {
          name: "拉新人数",
          type: "line",
          smooth: true,
          data: referralData,
          itemStyle: { color: "#409eff" },
          yAxisIndex: 0
        },
        {
          name: "有效用户数",
          type: "line",
          smooth: true,
          data: validData,
          itemStyle: { color: "#67c23a" },
          yAxisIndex: 0
        },
        {
          name: "佣金金额",
          type: "bar",
          data: commissionData,
          itemStyle: { color: "#e6a23c" },
          yAxisIndex: 1
        }
      ]
    };

    chartInstance.setOption(option);
  }, 100);
}

function resizeChart() {
  chartInstance?.resize();
}

onMounted(() => {
  fetchDashboardData();
  window.addEventListener("resize", resizeChart);
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", resizeChart);
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
});
</script>

<template>
  <div class="distribution-dashboard">
    <!-- 数据概览卡片 -->
    <el-row :gutter="20" class="mb-6">
      <el-col :span="8">
        <el-card shadow="hover">
          <template #header>
            <span class="card-header-text">总分销员数</span>
          </template>
          <el-statistic :value="dashboardData.totalDistributors" />
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <template #header>
            <span class="card-header-text">活跃分销员数</span>
          </template>
          <el-statistic :value="dashboardData.activeDistributors" />
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <template #header>
            <span class="card-header-text">总拉新用户数</span>
          </template>
          <el-statistic :value="dashboardData.totalReferrals" />
        </el-card>
      </el-col>
    </el-row>
    <el-row :gutter="20" class="mb-6">
      <el-col :span="8">
        <el-card shadow="hover">
          <template #header>
            <span class="card-header-text">有效用户数</span>
          </template>
          <el-statistic :value="dashboardData.validReferrals" />
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <template #header>
            <span class="card-header-text">总佣金支出</span>
          </template>
          <el-statistic
            :value="dashboardData.totalCommission"
            :formatter="(val: number) => formatMoney(val)"
          />
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <template #header>
            <span class="card-header-text">本月佣金支出</span>
          </template>
          <el-statistic
            :value="dashboardData.monthlyCommission"
            :formatter="(val: number) => formatMoney(val)"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 趋势图表 -->
    <el-card shadow="hover">
      <div ref="chartRef" style="width: 100%; height: 400px"></div>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.distribution-dashboard {
  .card-header-text {
    font-size: 14px;
    color: var(--el-text-color-secondary);
  }
}
</style>
