<template>
    <div class="app-container">

        <!-- 搜索栏 -->
        <el-form :model="queryParams" :inline="true" class="search-form">
            <el-form-item>
                <el-input
                    v-model="queryParams.memberId"
                    placeholder="用户UID"
                    clearable
                    style="width:130px"
                    @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item>
                <el-select
                    v-model="queryParams.status"
                    placeholder="状态"
                    clearable
                    style="width:110px"
                >
                    <el-option label="待审核" :value="0" />
                    <el-option label="通过" :value="1" />
                    <el-option label="不通过" :value="2" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-date-picker
                    v-model="queryParams.applyTimeRange"
                    type="daterange"
                    start-placeholder="申请开始时间"
                    end-placeholder="申请结束时间"
                    style="width:260px"
                    value-format="YYYY-MM-DD"
                />
            </el-form-item>
            <el-form-item>
                <el-date-picker
                    v-model="queryParams.reviewTimeRange"
                    type="daterange"
                    start-placeholder="审核开始时间"
                    end-placeholder="审核结束时间"
                    style="width:260px"
                    value-format="YYYY-MM-DD"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
                <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
                <el-button type="success" @click="handleBatchAudit(true)" :disabled="selectedIds.length === 0">
                    一键审核
                </el-button>
            </el-form-item>
        </el-form>

        <!-- 表格 -->
        <el-table
            :data="tableData"
            v-loading="loading"
            border
            style="width:100%"
            @selection-change="handleSelectionChange"
        >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="订单ID" prop="id" width="110" align="center" />
            <el-table-column label="用户UID" prop="memberId" width="100" align="center" />
            <el-table-column label="提现金额" prop="amount" width="120" align="center">
                <template #default="{ row }">{{ formatAmount(row.amount) }} USDT</template>
            </el-table-column>
            <el-table-column label="申请提现时间" prop="applyAt" min-width="160" align="center">
                <template #default="{ row }">{{ formatDate(row.applyAt) }}</template>
            </el-table-column>
            <el-table-column label="审核时间" prop="reviewedAt" min-width="160" align="center">
                <template #default="{ row }">{{ formatDate(row.reviewedAt) }}</template>
            </el-table-column>
            <el-table-column label="状态" prop="status" width="90" align="center">
                <template #default="{ row }">
                    <el-tag :type="statusTag(row.status)" size="small">{{ statusLabel(row.status) }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="200" align="center" fixed="right">
                <template #default="{ row }">
                    <el-button
                        v-if="row.status === 0"
                        link
                        type="primary"
                        @click="openAuditDialog(row)"
                    >审核</el-button>
                    <el-button link type="primary" @click="showMemberInfo(row.memberId)">用户体验金详情</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <pagination
            v-if="total > 0"
            :total="total"
            v-model:page="queryParams.pageNo"
            v-model:limit="queryParams.pageSize"
            @pagination="loadList"
        />

        <!-- 用户体验金详情弹窗 -->
        <el-dialog v-model="memberInfoDialog.visible" title="用户体验金详情" width="420px" destroy-on-close>
            <div v-if="memberInfoDialog.data" class="member-info-dialog">
                <div class="info-row">
                    <span class="info-key">用户UID：</span>
                    <span>{{ memberInfoDialog.data.memberId }}</span>
                </div>
                <div class="info-row">
                    <span class="info-key">累计获取邀请体验金：</span>
                    <span>{{ formatAmount(memberInfoDialog.data.inviteReceived) }} USDT</span>
                </div>
                <div class="info-row">
                    <span class="info-key">累计使用体验金：</span>
                    <span>{{ formatAmount(memberInfoDialog.data.totalReceived) }} USDT</span>
                </div>
                <div class="info-row">
                    <span class="info-key">累计体验金平仓盈利：</span>
                    <span class="profit">{{ formatAmount(memberInfoDialog.data.totalProfit) }} USDT</span>
                </div>
                <div class="info-row">
                    <span class="info-key">累计体验金平仓亏损：</span>
                    <span class="loss">{{ formatAmount(memberInfoDialog.data.totalLoss) }} USDT</span>
                </div>
            </div>
            <template #footer>
                <el-button @click="memberInfoDialog.visible = false">关闭</el-button>
            </template>
        </el-dialog>

        <!-- 审核弹窗 -->
        <el-dialog v-model="auditDialog.visible" title="体验金盈利提现审核" width="380px" destroy-on-close>
            <div class="audit-dialog">
                <p class="audit-tip">审核通过后，提现金额将转入用户资金账户。</p>
                <el-form v-if="auditDialog.showRemark" :model="auditDialog" style="margin-top:12px">
                    <el-form-item label="驳回原因">
                        <el-input
                            v-model="auditDialog.remark"
                            type="textarea"
                            :rows="3"
                            placeholder="请输入驳回原因（选填）"
                        />
                    </el-form-item>
                </el-form>
            </div>
            <template #footer>
                <el-button @click="submitAudit(false)">不通过</el-button>
                <el-button type="primary" @click="submitAudit(true)">通过</el-button>
            </template>
        </el-dialog>

    </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, Refresh } from "@element-plus/icons-vue";
import {
    experienceGiftWithdrawPageQuery,
    getExperienceGiftMemberInfo,
    auditExperienceGiftWithdraw,
    batchAuditExperienceGiftWithdraw,
} from "@/api/activity";

// -------- 状态 --------
const loading = ref(false);
const tableData = ref<any[]>([]);
const total = ref(0);
const selectedIds = ref<(number | string)[]>([]);

const queryParams = reactive({
    memberId: "",
    status: null as number | null,
    applyTimeRange: null as [string, string] | null,
    reviewTimeRange: null as [string, string] | null,
    pageNo: 1,
    pageSize: 15,
});

const memberInfoDialog = reactive({
    visible: false,
    data: null as any,
});

const auditDialog = reactive({
    visible: false,
    id: null as number | string | null,
    showRemark: false,
    remark: "",
});

// -------- 枚举 --------
function statusLabel(s: number) {
    return ["待审核", "通过", "不通过"][s] ?? String(s);
}
function statusTag(s: number) {
    if (s === 0) return "warning";
    if (s === 1) return "success";
    return "danger";
}

// -------- 工具 --------
function formatAmount(val: any) {
    if (val === null || val === undefined) return "0.00";
    return Number(val).toFixed(2);
}
function formatDate(val: any) {
    if (!val) return "-";
    return String(val).replace("T", " ").substring(0, 19);
}

// -------- 构建参数 --------
function buildParams() {
    const params: any = {
        pageNo: queryParams.pageNo,
        pageSize: queryParams.pageSize,
    };
    if (queryParams.memberId) params.memberId = queryParams.memberId;
    if (queryParams.status !== null) params.status = queryParams.status;
    if (queryParams.applyTimeRange?.[0]) params.applyStartTime = queryParams.applyTimeRange[0];
    if (queryParams.applyTimeRange?.[1]) params.applyEndTime = queryParams.applyTimeRange[1];
    if (queryParams.reviewTimeRange?.[0]) params.reviewStartTime = queryParams.reviewTimeRange[0];
    if (queryParams.reviewTimeRange?.[1]) params.reviewEndTime = queryParams.reviewTimeRange[1];
    return params;
}

// -------- 查询 --------
function handleQuery() {
    queryParams.pageNo = 1;
    loadList();
}

function resetQuery() {
    queryParams.memberId = "";
    queryParams.status = null;
    queryParams.applyTimeRange = null;
    queryParams.reviewTimeRange = null;
    queryParams.pageNo = 1;
    loadList();
}

async function loadList() {
    loading.value = true;
    try {
        const res: any = await experienceGiftWithdrawPageQuery(buildParams());
        tableData.value = res.data?.content ?? [];
        total.value = res.data?.totalElements ?? 0;
    } finally {
        loading.value = false;
    }
}

// -------- 多选 --------
function handleSelectionChange(rows: any[]) {
    selectedIds.value = rows.map((r) => r.id);
}

// -------- 用户详情 --------
async function showMemberInfo(memberId: number | string) {
    const res: any = await getExperienceGiftMemberInfo(memberId);
    memberInfoDialog.data = res.data;
    memberInfoDialog.visible = true;
}

// -------- 审核 --------
function openAuditDialog(row: any) {
    auditDialog.id = row.id;
    auditDialog.remark = "";
    auditDialog.showRemark = false;
    auditDialog.visible = true;
}

async function submitAudit(pass: boolean) {
    if (!pass && !auditDialog.showRemark) {
        auditDialog.showRemark = true;
        return;
    }
    await auditExperienceGiftWithdraw(auditDialog.id!, pass, auditDialog.remark || undefined);
    ElMessage.success(pass ? "审核通过" : "已驳回");
    auditDialog.visible = false;
    loadList();
}

function handleBatchAudit(pass: boolean) {
    if (selectedIds.value.length === 0) {
        ElMessage.warning("请先勾选要审核的记录");
        return;
    }
    ElMessageBox.confirm(
        `确认将选中的 ${selectedIds.value.length} 条记录全部${pass ? "通过" : "驳回"}？`,
        "批量审核",
        { confirmButtonText: "确认", cancelButtonText: "取消", type: "warning" }
    ).then(async () => {
        const res: any = await batchAuditExperienceGiftWithdraw(selectedIds.value, pass);
        ElMessage.success(res.message ?? "操作成功");
        loadList();
    }).catch(() => {});
}

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

<style lang="scss" scoped>
.search-form {
    margin-bottom: 12px;
}

.profit { color: #67c23a; }
.loss   { color: #f56c6c; }

.member-info-dialog {
    display: flex;
    flex-direction: column;
    gap: 14px;
    padding: 4px 0;

    .info-row {
        display: flex;
        font-size: 14px;
        align-items: center;

        .info-key {
            color: #606266;
            width: 170px;
            flex-shrink: 0;
        }
    }
}

.audit-dialog {
    .audit-tip {
        font-size: 14px;
        color: #606266;
        margin: 0 0 4px;
    }
}
</style>
