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

        <!-- 顶部统计 -->
        <div class="stats-bar">
            <div class="stat-item">
                <span class="stat-label">体验金金额</span>
                <span class="stat-value">{{ formatAmount(stats.totalAmount) }} USDT</span>
            </div>
            <div class="stat-divider" />
            <div class="stat-item">
                <span class="stat-label">平仓盈利</span>
                <span class="stat-value profit">{{ formatAmount(stats.profitAmount) }} USDT</span>
            </div>
            <div class="stat-divider" />
            <div class="stat-item">
                <span class="stat-label">平仓亏损</span>
                <span class="stat-value loss">{{ formatAmount(stats.lossAmount) }} USDT</span>
            </div>
        </div>

        <!-- 搜索栏 -->
        <el-form :model="queryParams" :inline="true" class="search-form">
            <el-form-item>
                <el-input
                    v-model="queryParams.productName"
                    placeholder="体验金产品名称"
                    clearable
                    style="width:150px"
                    @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item>
                <el-select
                    v-model="queryParams.statusGroup"
                    placeholder="状态"
                    clearable
                    style="width:110px"
                >
                    <el-option label="未使用" :value="0" />
                    <el-option label="持仓中" :value="1" />
                    <el-option label="已使用" :value="2" />
                    <el-option label="已过期" :value="3" />
                    <el-option label="已失效" :value="4" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-input
                    v-model="queryParams.id"
                    placeholder="体验金ID"
                    clearable
                    style="width:120px"
                    @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item>
                <el-input
                    v-model="queryParams.memberId"
                    placeholder="用户UID"
                    clearable
                    style="width:120px"
                    @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item>
                <el-date-picker
                    v-model="queryParams.grantTimeRange"
                    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.expireTimeRange"
                    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-form-item>
        </el-form>

        <!-- 表格 -->
        <el-table :data="tableData" v-loading="loading" border highlight-current-row>
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="体验金产品名称" prop="productName" min-width="130" align="center" />
            <el-table-column label="体验金ID" prop="id" width="90" align="center" />
            <el-table-column label="用户UID" prop="memberId" width="90" align="center" />
            <el-table-column label="体验金金额" prop="amount" width="110" align="center">
                <template #default="{ row }">{{ formatAmount(row.amount) }}</template>
            </el-table-column>
            <el-table-column label="仓位ID" prop="positionId" width="90" align="center">
                <template #default="{ row }">{{ row.positionId || '-' }}</template>
            </el-table-column>
            <el-table-column label="仓位信息" width="140" align="center">
                <template #default="{ row }">
                    <template v-if="row.coinSymbol">
                        <span>{{ row.coinSymbol }}</span>
                        <el-tag
                            v-if="row.positionDirection === 0"
                            type="success"
                            size="small"
                            style="margin-left:4px"
                        >做多</el-tag>
                        <el-tag
                            v-else-if="row.positionDirection === 1"
                            type="danger"
                            size="small"
                            style="margin-left:4px"
                        >做空</el-tag>
                    </template>
                    <span v-else>-</span>
                </template>
            </el-table-column>
            <el-table-column label="平仓盈亏" prop="pnl" width="100" align="center">
                <template #default="{ row }">
                    <span
                        v-if="row.pnl !== null && row.pnl !== undefined"
                        :class="Number(row.pnl) > 0 ? 'profit' : Number(row.pnl) < 0 ? 'loss' : ''"
                    >
                        {{ Number(row.pnl) > 0 ? '+' : '' }}{{ formatAmount(row.pnl) }}
                    </span>
                    <span v-else>-</span>
                </template>
            </el-table-column>
            <el-table-column label="有效期" prop="validityDays" width="80" align="center">
                <template #default="{ row }">
                    {{ row.validityDays ? row.validityDays + '天' : '-' }}
                </template>
            </el-table-column>
            <el-table-column label="领取时间" prop="createdAt" width="160" align="center">
                <template #default="{ row }">{{ formatDate(row.createdAt) }}</template>
            </el-table-column>
            <el-table-column label="失效时间" prop="expireAt" width="160" align="center">
                <template #default="{ row }">{{ formatDate(row.expireAt) }}</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="danger"
                        @click="handleRecycle(row)"
                    >回收体验金</el-button>
                    <el-button link type="primary" @click="showSource(row)">查看来源</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="sourceDialog.visible" title="体验金来源" width="480px" destroy-on-close>
            <div v-if="sourceDialog.record" class="source-dialog">
                <!-- 邀请触发 -->
                <template v-if="sourceDialog.record.grantType === 1">
                    <div class="source-title">邀请奖励体验金</div>
                    <div class="source-body">
                        <div class="source-row">
                            <span class="source-key">直邀用户UID：</span>
                            <span>{{ sourceDialog.record.memberId }}</span>
                        </div>
                        <div class="source-row">
                            <span class="source-key">邀请人UID：</span>
                            <span>{{ sourceDialog.record.inviterId || '-' }}</span>
                        </div>
                        <div class="source-row">
                            <span class="source-key">发放时间：</span>
                            <span>{{ formatDate(sourceDialog.record.createdAt) }}</span>
                        </div>
                        <div class="source-row" v-if="sourceDialog.record.positionId">
                            <span class="source-key">触发仓位ID：</span>
                            <span>{{ sourceDialog.record.positionId }}</span>
                        </div>
                        <div class="source-row" v-if="sourceDialog.record.usedAt">
                            <span class="source-key">开仓时间：</span>
                            <span>{{ formatDate(sourceDialog.record.usedAt) }}</span>
                        </div>
                        <div class="source-row" v-if="sourceDialog.record.closedAt">
                            <span class="source-key">平仓时间：</span>
                            <span>{{ formatDate(sourceDialog.record.closedAt) }}</span>
                        </div>
                    </div>
                </template>
                <!-- 注册触发 -->
                <template v-else-if="sourceDialog.record.grantType === 0">
                    <div class="source-title">注册体验金</div>
                    <div class="source-body">
                        <div class="source-row">
                            <span class="source-key">用户UID：</span>
                            <span>{{ sourceDialog.record.memberId }}</span>
                        </div>
                        <div class="source-row">
                            <span class="source-key">注册时间：</span>
                            <span>{{ formatDate(sourceDialog.record.createdAt) }}</span>
                        </div>
                        <div class="source-row">
                            <span class="source-key">产品名称：</span>
                            <span>{{ sourceDialog.record.productName }}</span>
                        </div>
                        <div class="source-row">
                            <span class="source-key">面额：</span>
                            <span>{{ formatAmount(sourceDialog.record.amount) }} USDT</span>
                        </div>
                    </div>
                </template>
                <!-- 手动派发 -->
                <template v-else-if="sourceDialog.record.grantType === 2">
                    <div class="source-title">管理后台赠送</div>
                    <div class="source-body">
                        <div class="source-row">
                            <span class="source-key">产品名称：</span>
                            <span>{{ sourceDialog.record.productName }}</span>
                        </div>
                        <div class="source-row">
                            <span class="source-key">派发管理员：</span>
                            <span>{{ sourceDialog.record.operatorUsername || '-' }}</span>
                        </div>
                        <div class="source-row">
                            <span class="source-key">派发时间：</span>
                            <span>{{ formatDate(sourceDialog.record.createdAt) }}</span>
                        </div>
                    </div>
                </template>
            </div>
            <template #footer>
                <el-button @click="sourceDialog.visible = false">关闭</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 {
    experienceGiftRecordPageQuery,
    experienceGiftRecordStats,
    recycleExperienceGift,
    getExperienceGiftSource,
} from "@/api/activity";

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

const queryParams = reactive({
    productName: "",
    statusGroup: null as number | null,
    id: "",
    memberId: "",
    grantTimeRange: null as [string, string] | null,
    expireTimeRange: null as [string, string] | null,
    pageNo: 1,
    pageSize: 15,
});

const stats = reactive({
    totalAmount: 0,
    profitAmount: 0,
    lossAmount: 0,
});

const sourceDialog = reactive({
    visible: false,
    record: null as any,
});

// -------- 枚举 --------
function statusLabel(s: number) {
    const map: Record<number, string> = {
        0: "未使用",
        1: "持仓中",
        2: "已使用",
        3: "已过期",
        4: "已失效",
    };
    return map[s] ?? String(s);
}

function statusTag(s: number) {
    if (s === 0) return "info";
    if (s === 1) return "warning";
    if (s === 2) return "success";
    if (s === 3) return "";
    if (s === 4) return "danger";
    return "";
}

// -------- 工具 --------
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.productName) params.productName = queryParams.productName;
    if (queryParams.statusGroup !== null) params.statusGroup = queryParams.statusGroup;
    if (queryParams.id) params.id = queryParams.id;
    if (queryParams.memberId) params.memberId = queryParams.memberId;
    if (queryParams.grantTimeRange?.[0]) params.grantStartTime = queryParams.grantTimeRange[0];
    if (queryParams.grantTimeRange?.[1]) params.grantEndTime = queryParams.grantTimeRange[1];
    if (queryParams.expireTimeRange?.[0]) params.expireStartTime = queryParams.expireTimeRange[0];
    if (queryParams.expireTimeRange?.[1]) params.expireEndTime = queryParams.expireTimeRange[1];
    return params;
}

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

function resetQuery() {
    queryParams.productName = "";
    queryParams.statusGroup = null;
    queryParams.id = "";
    queryParams.memberId = "";
    queryParams.grantTimeRange = null;
    queryParams.expireTimeRange = null;
    queryParams.pageNo = 1;
    loadList();
    loadStats();
}

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

async function loadStats() {
    const params = buildParams();
    // stats 不需要分页参数
    delete params.pageNo;
    delete params.pageSize;
    const res: any = await experienceGiftRecordStats(params);
    const d = res.data ?? {};
    stats.totalAmount = d.totalAmount ?? 0;
    stats.profitAmount = d.profitAmount ?? 0;
    stats.lossAmount = d.lossAmount ?? 0;
}

// -------- 操作 --------
async function showSource(row: any) {
    const res: any = await getExperienceGiftSource(row.id);
    sourceDialog.record = res.data ?? row;
    sourceDialog.visible = true;
}

function handleRecycle(row: any) {
    ElMessageBox.confirm(
        `确认回收用户 ${row.memberId} 的体验金（面额 ${formatAmount(row.amount)} USDT）？`,
        "提示",
        {
            confirmButtonText: "确认回收",
            cancelButtonText: "取消",
            type: "warning",
        }
    ).then(async () => {
        await recycleExperienceGift(row.id);
        ElMessage.success("回收成功");
        loadList();
        loadStats();
    }).catch(() => {});
}

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

<style lang="scss" scoped>
.stats-bar {
    display: flex;
    align-items: center;
    background: #f8f9fb;
    border: 1px solid #ebeef5;
    border-radius: 6px;
    padding: 14px 32px;
    margin-bottom: 16px;
    gap: 0;

    .stat-item {
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        flex: 1;
        gap: 6px;

        .stat-label {
            font-size: 13px;
            color: #909399;
        }
        .stat-value {
            font-size: 20px;
            font-weight: 600;
            color: #303133;
            &.profit { color: #67c23a; }
            &.loss   { color: #f56c6c; }
        }
    }

    .stat-divider {
        width: 1px;
        height: 40px;
        background: #dcdfe6;
        margin: 0 32px;
    }
}

.search-form {
    margin-bottom: 12px;
}

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

.source-dialog {
    .source-title {
        font-size: 15px;
        font-weight: 600;
        color: #303133;
        margin-bottom: 16px;
        padding-bottom: 10px;
        border-bottom: 1px solid #ebeef5;
    }
    .source-body {
        display: flex;
        flex-direction: column;
        gap: 12px;
    }
    .source-row {
        display: flex;
        font-size: 14px;
        .source-key {
            color: #909399;
            width: 120px;
            flex-shrink: 0;
        }
    }
}
</style>
