<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import { getInviteRecords, exportInviteRecords, manualReissueReward } from "@/api/invite";
import { message } from "@/utils/message";
import type { InviteRecordsSearchParams } from "./utils/types";

defineOptions({
  name: "InviteRecords"
});

const formRef = ref();
const loading = ref(false);
const dataList = ref([]);
const timeRange = ref([]);
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 搜索表单
const form = reactive<InviteRecordsSearchParams>({
  activityId: undefined,
  inviterId: "",
  status: undefined,
  rewardType: undefined,
  startTime: "",
  endTime: ""
});

// 状态映射
type TagType = "success" | "primary" | "warning" | "info" | "danger";
const statusMap: Record<number, { text: string; type: TagType }> = {
  0: { text: "待激活", type: "info" },
  1: { text: "已激活", type: "primary" },
  2: { text: "奖励已发放", type: "success" },
  3: { text: "发放失败", type: "danger" }
};

// 奖励类型映射
const rewardTypeMap: Record<number, { text: string; type: TagType; icon: string }> = {
  0: { text: "邀请人推荐奖", type: "success", icon: "🎯" },
  1: { text: "被邀请人新人券", type: "primary", icon: "🎁" }
};

// 触发条件映射
const triggerTypeMap: Record<number, { text: string; type: TagType }> = {
  0: { text: "首单完成", type: "warning" },
  1: { text: "注册绑定", type: "info" }
};

// 手机号脱敏
function maskPhone(phone: string): string {
  if (!phone) return "-";
  return phone.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
}

// 格式化奖励类型
function formatRewardType(type: number | undefined): { text: string; type: TagType; icon: string } {
  if (type === undefined || type === null) {
    return { text: "未知", type: "info", icon: "" };
  }
  return rewardTypeMap[type] || { text: "未知", type: "info", icon: "" };
}

// 格式化触发条件
function formatTriggerType(type: number | undefined): { text: string; type: TagType } {
  if (type === undefined || type === null) {
    return { text: "未知", type: "info" };
  }
  return triggerTypeMap[type] || { text: "未知", type: "info" };
}

// 加载记录列表
async function onSearch() {
  loading.value = true;
  try {
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      ...form
    };

    const { data } = await getInviteRecords(params);
    if (data) {
      dataList.value = data.list || [];
      pagination.total = Number(data.total) || 0;
    }
  } finally {
    loading.value = false;
  }
}

// 重置表单
function resetForm(formEl) {
  if (!formEl) return;
  formEl.resetFields();
  Object.assign(form, {
    activityId: undefined,
    inviterId: "",
    status: undefined,
    rewardType: undefined,
    startTime: "",
    endTime: ""
  });
  pagination.currentPage = 1;
  onSearch();
}

// 分页大小变化
function handleSizeChange(val: number) {
  pagination.pageSize = val;
  pagination.currentPage = 1;
  onSearch();
}

// 当前页变化
function handleCurrentChange(val: number) {
  pagination.currentPage = val;
  onSearch();
}

// 导出 Excel
async function handleExport() {
  try {
    const params = { ...form };
    const res = await exportInviteRecords(params);

    // 创建下载链接
    const blob = new Blob([res.data], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = `邀请记录_${new Date().getTime()}.xlsx`;
    link.click();
    window.URL.revokeObjectURL(url);

    message("导出成功", { type: "success" });
  } catch (error) {
    message("导出失败", { type: "error" });
  }
}

// 手动补发奖励
async function handleReissue(row: any) {
  try {
    const { code } = await manualReissueReward(row.id);
    if (code === 200) {
      message("补发成功", { type: "success" });
      onSearch();
    }
  } catch (error) {
    message("补发失败", { type: "error" });
  }
}

onMounted(() => {
  onSearch();
});
</script>

<template>
  <div class="main">
    <el-form
      ref="formRef"
      :inline="true"
      :model="form"
      class="search-form bg-bg_color w-full pl-8 pt-[12px] overflow-auto"
    >
      <el-form-item label="活动ID：" prop="activityId">
        <el-input-number
          v-model="form.activityId"
          placeholder="请输入活动ID"
          :min="0"
          controls-position="right"
          class="w-[180px]!"
        />
      </el-form-item>
      <el-form-item label="邀请人ID：" prop="inviterId">
        <el-input
          v-model="form.inviterId"
          placeholder="请输入邀请人ID或手机号"
          clearable
          class="w-[200px]!"
        />
      </el-form-item>
      <el-form-item label="状态：" prop="status">
        <el-select
          v-model="form.status"
          placeholder="请选择"
          clearable
          class="w-[150px]!"
        >
          <el-option label="待激活" :value="0" />
          <el-option label="已激活" :value="1" />
          <el-option label="奖励已发放" :value="2" />
          <el-option label="发放失败" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="奖励类型：" prop="rewardType">
        <el-select
          v-model="form.rewardType"
          placeholder="奖励类型"
          clearable
          class="w-[150px]!"
        >
          <el-option label="全部" :value="undefined" />
          <el-option label="邀请人推荐奖" :value="0" />
          <el-option label="被邀请人新人券" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="时间范围：" prop="timeRange">
        <el-date-picker
          v-model="timeRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD HH:mm:ss"
          @change="(val) => {
            if (val && val.length === 2) {
              form.startTime = val[0];
              form.endTime = val[1];
            } else {
              form.startTime = '';
              form.endTime = '';
            }
          }"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          :icon="'ri/search-line'"
          :loading="loading"
          @click="onSearch"
        >
          搜索
        </el-button>
        <el-button :icon="'ep/refresh'" @click="resetForm(formRef)">
          重置
        </el-button>
        <el-button
          type="warning"
          :icon="'ep/download'"
          @click="handleExport"
        >
          导出 Excel
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <div class="table-container bg-white p-4 mt-2">
      <el-table
        v-loading="loading"
        :data="dataList"
        border
        stripe
        style="width: 100%"
        :header-cell-style="{
          background: 'var(--el-fill-color-light)',
          color: 'var(--el-text-color-primary)'
        }"
      >
        <el-table-column label="记录ID" prop="id" width="80" align="center" />
        <el-table-column label="活动名称" prop="activityName" min-width="140" align="center" show-overflow-tooltip />
        <el-table-column label="邀请人ID" prop="inviterId" width="100" align="center" />
        <el-table-column label="邀请人手机号（脱敏）" min-width="160" align="center">
          <template #default="{ row }">
            {{ maskPhone(row.inviterPhone) }}
          </template>
        </el-table-column>
        <el-table-column label="被邀请人ID" prop="inviteeId" width="100" align="center" />
        <el-table-column label="被邀请人手机号（脱敏）" min-width="160" align="center">
          <template #default="{ row }">
            {{ maskPhone(row.inviteePhone) }}
          </template>
        </el-table-column>
        <el-table-column label="邀请码" prop="inviteCode" width="120" align="center" show-overflow-tooltip />
        <el-table-column label="邀请时间" prop="inviteTime" width="170" align="center" />
        <el-table-column label="激活时间" prop="activateTime" width="170" align="center">
          <template #default="{ row }">
            {{ row.activateTime || "-" }}
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" width="110" align="center">
          <template #default="{ row }">
            <el-tag :type="statusMap[row.status]?.type || 'info'" size="small">
              {{ statusMap[row.status]?.text || "未知" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="奖励类型" prop="rewardType" width="150" align="center">
          <template #default="{ row }">
            <el-tag
              v-if="row.rewardType !== undefined && row.rewardType !== null"
              :type="formatRewardType(row.rewardType).type"
              size="small"
            >
              {{ formatRewardType(row.rewardType).icon }} {{ formatRewardType(row.rewardType).text }}
            </el-tag>
            <span v-else class="text-gray-400">—</span>
          </template>
        </el-table-column>
        <el-table-column label="触发条件" prop="triggerType" width="130" align="center">
          <template #default="{ row }">
            <el-tag
              v-if="row.triggerType !== undefined && row.triggerType !== null"
              :type="formatTriggerType(row.triggerType).type"
              size="small"
            >
              {{ formatTriggerType(row.triggerType).text }}
            </el-tag>
            <span v-else class="text-gray-400">—</span>
          </template>
        </el-table-column>
        <el-table-column label="奖励金额" prop="rewardAmount" width="100" align="center">
          <template #default="{ row }">
            <span v-if="row.rewardAmount">¥{{ row.rewardAmount }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="120" align="center">
          <template #default="{ row }">
            <el-button
              v-if="row.status === 3"
              link
              type="primary"
              size="small"
              @click="handleReissue(row)"
            >
              补发奖励
            </el-button>
            <span v-else class="text-gray-400 text-sm">-</span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="flex justify-end mt-4">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

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

<style lang="scss" scoped>
.main-content {
  margin: 24px 24px 0 !important;
}

.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}

.table-container {
  border-radius: 4px;
}
</style>
