<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { useRoute } from "vue-router";
import { getInviteStatistics } from "@/api/invite";
import type { InviteStatisticsData } from "./utils/types";

defineOptions({
  name: "InviteStatistics"
});

const route = useRoute();
const loading = ref(false);
const statisticsData = ref<InviteStatisticsData | null>(null);

// 时间范围选择
const timeRange = ref("week");
const customDateRange = ref<[string, string] | null>(null);

// 图表相关
const chartRef = ref<HTMLDivElement | null>(null);
let chartInstance: any = null;

// 从路由参数获取活动ID
const activityId = computed(() => {
  return Number(route.query.id) || 0;
});

// 核心指标数据
const metrics = computed(() => {
  if (!statisticsData.value) {
    return [
      { title: "总邀请次数", value: 0, icon: "ep:user", color: "#409EFF" },
      { title: "有效邀请数", value: 0, icon: "ep:check", color: "#67C23A" },
      { title: "奖励发放总数", value: 0, icon: "ep:present", color: "#E6A23C" },
      { title: "今日新增邀请数", value: 0, icon: "ep:trend-charts", color: "#F56C6C" },
      { title: "转化率", value: "0%", icon: "ep:data-analysis", color: "#909399" },
      { title: "奖励发放成功率", value: "0%", icon: "ep:circle-check", color: "#409EFF" }
    ];
  }

  const data = statisticsData.value;
  return [
    { title: "总邀请次数", value: data.totalInvites || 0, icon: "ep:user", color: "#409EFF" },
    { title: "有效邀请数", value: data.validInvites || 0, icon: "ep:check", color: "#67C23A" },
    { title: "奖励发放总数", value: data.totalRewardsIssued || 0, icon: "ep:present", color: "#E6A23C" },
    { title: "今日新增邀请数", value: data.todayNewInvites || 0, icon: "ep:trend-charts", color: "#F56C6C" },
    {
      title: "转化率",
      value: data.conversionRate !== undefined ? `${(data.conversionRate * 100).toFixed(2)}%` : "0%",
      icon: "ep:data-analysis",
      color: "#909399"
    },
    {
      title: "奖励发放成功率",
      value: data.rewardSuccessRate !== undefined ? `${(data.rewardSuccessRate * 100).toFixed(2)}%` : "0%",
      icon: "ep:circle-check",
      color: "#409EFF"
    }
  ];
});

// 排行榜数据
const rankingList = computed(() => {
  if (!statisticsData.value?.rankingList) return [];
  return statisticsData.value.rankingList;
});

// 双向奖励统计 - 被邀请人优惠券
const inviteeCouponMetrics = computed(() => {
  if (!statisticsData.value?.inviteeCoupon) {
    return {
      totalDistributed: 0,
      totalUsed: 0,
      usageRate: "0%"
    };
  }

  const data = statisticsData.value.inviteeCoupon;
  return {
    totalDistributed: data.totalDistributed || 0,
    totalUsed: data.totalUsed || 0,
    usageRate: data.usageRate !== undefined ? `${data.usageRate.toFixed(2)}%` : "0%"
  };
});

// 双向奖励统计 - 邀请人优惠券
const inviterCouponMetrics = computed(() => {
  if (!statisticsData.value?.inviterCoupon) {
    return {
      totalDistributed: 0,
      totalUsed: 0,
      usageRate: "0%"
    };
  }

  const data = statisticsData.value.inviterCoupon;
  return {
    totalDistributed: data.totalDistributed || 0,
    totalUsed: data.totalUsed || 0,
    usageRate: data.usageRate !== undefined ? `${data.usageRate.toFixed(2)}%` : "0%"
  };
});

// 成本分析数据
const costAnalysisMetrics = computed(() => {
  if (!statisticsData.value?.costAnalysis) {
    return {
      totalDiscountAmount: 0,
      gmv: 0,
      roi: "0",
      avgAcquisitionCost: 0
    };
  }

  const data = statisticsData.value.costAnalysis;
  return {
    totalDiscountAmount: data.totalDiscountAmount || 0,
    gmv: data.gmv || 0,
    roi: data.roi !== undefined ? data.roi.toFixed(2) : "0",
    avgAcquisitionCost: data.avgAcquisitionCost || 0
  };
});

// 格式化金额
function formatMoney(value: number): string {
  return `¥${value.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
}

// 加载统计数据
async function loadStatistics() {
  if (!activityId.value) {
    // 如果没有活动ID，可以显示默认数据或提示用户选择活动
    return;
  }

  loading.value = true;
  try {
    const params: any = {};
    if (timeRange.value !== "custom") {
      params.period = timeRange.value; // day, week, month
    }
    if (customDateRange.value && customDateRange.value.length === 2) {
      params.startDate = customDateRange.value[0];
      params.endDate = customDateRange.value[1];
    }

    const { data } = await getInviteStatistics(activityId.value, params);
    if (data) {
      statisticsData.value = data as InviteStatisticsData;
      renderChart();
    }
  } finally {
    loading.value = false;
  }
}

// 渲染趋势图
function renderChart() {
  if (!chartRef.value) return;

  // 动态导入 ECharts
  import("echarts").then(echarts => {
    if (chartInstance) {
      chartInstance.dispose();
    }

    chartInstance = echarts.init(chartRef.value!);

    const trendData = statisticsData.value?.trendData || [];
    const dates = trendData.map(item => item.date);
    const invites = trendData.map(item => item.invites);
    const activations = trendData.map(item => item.activations);
    const rewards = trendData.map(item => item.rewards);

    const option = {
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "cross"
        }
      },
      legend: {
        data: ["邀请数量", "激活数量", "奖励发放"],
        bottom: 0
      },
      grid: {
        left: "3%",
        right: "4%",
        bottom: "15%",
        top: "10%",
        containLabel: true
      },
      xAxis: {
        type: "category",
        boundaryGap: false,
        data: dates.length > 0 ? dates : [],
        axisLabel: {
          rotate: dates.length > 7 ? 45 : 0
        }
      },
      yAxis: {
        type: "value"
      },
      series: [
        {
          name: "邀请数量",
          type: "line",
          smooth: true,
          data: invites.length > 0 ? invites : [],
          itemStyle: { color: "#409EFF" },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: "rgba(64, 158, 255, 0.3)" },
              { offset: 1, color: "rgba(64, 158, 255, 0.05)" }
            ])
          }
        },
        {
          name: "激活数量",
          type: "line",
          smooth: true,
          data: activations.length > 0 ? activations : [],
          itemStyle: { color: "#67C23A" },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: "rgba(103, 194, 58, 0.3)" },
              { offset: 1, color: "rgba(103, 194, 58, 0.05)" }
            ])
          }
        },
        {
          name: "奖励发放",
          type: "line",
          smooth: true,
          data: rewards.length > 0 ? rewards : [],
          itemStyle: { color: "#E6A23C" },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: "rgba(230, 162, 60, 0.3)" },
              { offset: 1, color: "rgba(230, 162, 60, 0.05)" }
            ])
          }
        }
      ]
    };

    chartInstance.setOption(option);
  });
}

function handleTimeRangeChange(value: string) {
  timeRange.value = value;
  loadStatistics();
}

onMounted(() => {
  loadStatistics();

  // 监听窗口大小变化
  window.addEventListener("resize", () => {
    chartInstance?.resize();
  });
});
</script>

<template>
  <div class="invite-statistics">
    <!-- 活动选择提示 -->
    <el-alert
      v-if="!activityId"
      title="请先从活动列表页面进入统计页面"
      type="warning"
      show-icon
      class="mb-4"
    />

    <!-- 时间范围选择器 -->
    <div class="mb-4 flex items-center justify-between">
      <div>
        <span class="mr-2 text-sm text-gray-600">时间范围：</span>
        <el-radio-group v-model="timeRange" @change="handleTimeRangeChange">
          <el-radio-button value="day">按日</el-radio-button>
          <el-radio-button value="week">按周</el-radio-button>
          <el-radio-button value="month">按月</el-radio-button>
        </el-radio-group>
      </div>
      <el-button type="primary" :loading="loading" @click="loadStatistics">
        刷新数据
      </el-button>
    </div>

    <!-- 核心指标卡片 -->
    <el-row :gutter="20" class="mb-5">
      <el-col
        v-for="(metric, index) in metrics"
        :key="index"
        :xs="24"
        :sm="12"
        :md="8"
        :lg="4"
      >
        <el-card shadow="hover" class="metric-card">
          <div class="flex items-center justify-between">
            <div>
              <div class="text-gray-500 text-sm mb-1">{{ metric.title }}</div>
              <div class="text-2xl font-bold" :style="{ color: metric.color }">
                {{ typeof metric.value === 'number' ? metric.value.toLocaleString() : metric.value }}
              </div>
            </div>
            <div
              class="w-12 h-12 rounded-full flex items-center justify-center"
              :style="{ backgroundColor: metric.color + '20' }"
            >
              <el-icon :size="24" :color="metric.color">
                <component :is="metric.icon" />
              </el-icon>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 趋势图表 -->
    <el-card class="mb-5">
      <template #header>
        <div class="flex items-center justify-between">
          <span class="font-semibold">邀请数量趋势图</span>
        </div>
      </template>
      <div ref="chartRef" style="width: 100%; height: 400px"></div>
    </el-card>

    <!-- 双向奖励统计 - 被邀请人优惠券（蓝色系） -->
    <el-card class="mb-5">
      <template #header>
        <div class="flex items-center">
          <el-icon class="mr-2" color="#409EFF" :size="20"><ep:ticket /></el-icon>
          <span class="font-semibold">被邀请人优惠券统计</span>
          <el-tag type="primary" size="small" class="ml-2">被邀请人</el-tag>
        </div>
      </template>
      <el-row :gutter="20">
        <el-col :xs="24" :sm="8">
          <div class="stat-item">
            <div class="text-gray-500 text-sm mb-2">优惠券发放总数</div>
            <div class="text-3xl font-bold text-blue-600">{{ inviteeCouponMetrics.totalDistributed.toLocaleString() }}</div>
            <div class="text-xs text-gray-400 mt-1">张</div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="8">
          <div class="stat-item">
            <div class="text-gray-500 text-sm mb-2">优惠券使用数量</div>
            <div class="text-3xl font-bold text-blue-500">{{ inviteeCouponMetrics.totalUsed.toLocaleString() }}</div>
            <div class="text-xs text-gray-400 mt-1">张</div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="8">
          <div class="stat-item">
            <div class="text-gray-500 text-sm mb-2">优惠券核销率</div>
            <div class="text-3xl font-bold" style="color: #409EFF">{{ inviteeCouponMetrics.usageRate }}</div>
            <div class="text-xs text-gray-400 mt-1">使用率</div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 双向奖励统计 - 邀请人优惠券（绿色系） -->
    <el-card class="mb-5">
      <template #header>
        <div class="flex items-center">
          <el-icon class="mr-2" color="#67C23A" :size="20"><ep:present /></el-icon>
          <span class="font-semibold">邀请人优惠券统计</span>
          <el-tag type="success" size="small" class="ml-2">邀请人</el-tag>
        </div>
      </template>
      <el-row :gutter="20">
        <el-col :xs="24" :sm="8">
          <div class="stat-item">
            <div class="text-gray-500 text-sm mb-2">优惠券发放总数</div>
            <div class="text-3xl font-bold text-green-600">{{ inviterCouponMetrics.totalDistributed.toLocaleString() }}</div>
            <div class="text-xs text-gray-400 mt-1">张</div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="8">
          <div class="stat-item">
            <div class="text-gray-500 text-sm mb-2">优惠券使用数量</div>
            <div class="text-3xl font-bold text-green-500">{{ inviterCouponMetrics.totalUsed.toLocaleString() }}</div>
            <div class="text-xs text-gray-400 mt-1">张</div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="8">
          <div class="stat-item">
            <div class="text-gray-500 text-sm mb-2">优惠券核销率</div>
            <div class="text-3xl font-bold" style="color: #67C23A">{{ inviterCouponMetrics.usageRate }}</div>
            <div class="text-xs text-gray-400 mt-1">使用率</div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 综合成本分析模块（橙色系） -->
    <el-card class="mb-5 cost-analysis-card">
      <template #header>
        <div class="flex items-center">
          <el-icon class="mr-2" color="#E6A23C" :size="20"><ep:data-analysis /></el-icon>
          <span class="font-semibold">综合成本分析</span>
          <el-tag type="warning" size="small" class="ml-2">ROI</el-tag>
        </div>
      </template>
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="6">
          <div class="cost-item">
            <div class="flex items-center mb-2">
              <div class="w-3 h-3 rounded-full mr-2" style="background-color: #E6A23C"></div>
              <span class="text-gray-600 text-sm font-medium">总优惠金额</span>
            </div>
            <div class="text-2xl font-bold" style="color: #E6A23C">{{ formatMoney(costAnalysisMetrics.totalDiscountAmount) }}</div>
            <div class="text-xs text-gray-400 mt-1">双方合计优惠成本</div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <div class="cost-item">
            <div class="flex items-center mb-2">
              <div class="w-3 h-3 rounded-full mr-2" style="background-color: #F56C6C"></div>
              <span class="text-gray-600 text-sm font-medium">GMV（总交易额）</span>
            </div>
            <div class="text-2xl font-bold" style="color: #F56C6C">{{ formatMoney(costAnalysisMetrics.gmv) }}</div>
            <div class="text-xs text-gray-400 mt-1">活动期间总交易金额</div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <div class="cost-item">
            <div class="flex items-center mb-2">
              <div class="w-3 h-3 rounded-full mr-2" style="background-color: #67C23A"></div>
              <span class="text-gray-600 text-sm font-medium">ROI（投资回报率）</span>
            </div>
            <div class="text-2xl font-bold" style="color: #67C23A">{{ costAnalysisMetrics.roi }}</div>
            <div class="text-xs text-gray-400 mt-1">GMV / 总优惠成本</div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <div class="cost-item">
            <div class="flex items-center mb-2">
              <div class="w-3 h-3 rounded-full mr-2" style="background-color: #909399"></div>
              <span class="text-gray-600 text-sm font-medium">平均获客成本</span>
            </div>
            <div class="text-2xl font-bold" style="color: #909399">{{ formatMoney(costAnalysisMetrics.avgAcquisitionCost) }}</div>
            <div class="text-xs text-gray-400 mt-1">总优惠成本 / 有效新用户数</div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 邀请达人排行榜 -->
    <el-card>
      <template #header>
        <div class="flex items-center justify-between">
          <span class="font-semibold">邀请达人排行榜</span>
        </div>
      </template>
      <el-table :data="rankingList" stripe border style="width: 100%">
        <el-table-column label="排名" width="80" align="center">
          <template #default="{ $index }">
            <el-tag
              v-if="$index === 0"
              type="danger"
              size="small"
              round
            >
              {{ $index + 1 }}
            </el-tag>
            <el-tag
              v-else-if="$index === 1"
              type="warning"
              size="small"
              round
            >
              {{ $index + 1 }}
            </el-tag>
            <el-tag
              v-else-if="$index === 2"
              size="small"
              round
            >
              {{ $index + 1 }}
            </el-tag>
            <span v-else>{{ $index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="userId" label="用户ID" width="120" align="center" />
        <el-table-column prop="userPhone" label="手机号（脱敏）" min-width="150" align="center">
          <template #default="{ row }">
            {{ row.userPhone ? row.userPhone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="inviteCount" label="邀请数量" width="120" align="center">
          <template #default="{ row }">
            <span class="font-semibold text-blue-600">{{ row.inviteCount || 0 }}</span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 空状态 -->
      <el-empty v-if="!loading && rankingList.length === 0" description="暂无排行榜数据" />
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.invite-statistics {
  padding: 16px;
}

.metric-card {
  margin-bottom: 12px;

  &:hover {
    transform: translateY(-2px);
    transition: all 0.3s ease;
  }
}

// 双向奖励统计项样式
.stat-item {
  text-align: center;
  padding: 20px 10px;
  border-radius: 8px;
  background-color: #fafafa;
  transition: all 0.3s ease;

  &:hover {
    background-color: #f5f5f5;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  }
}

// 成本分析卡片特殊样式
.cost-analysis-card {
  background: linear-gradient(135deg, #fff9f0 0%, #ffffff 100%);
  border: 1px solid #faecd8;

  :deep(.el-card__header) {
    background-color: #fdf6ec;
    border-bottom: 1px solid #faecd8;
  }
}

// 成本分析项样式
.cost-item {
  padding: 20px 15px;
  border-radius: 8px;
  background-color: rgba(255, 255, 255, 0.8);
  transition: all 0.3s ease;

  &:hover {
    background-color: #ffffff;
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(230, 162, 60, 0.15);
  }
}
</style>
