<script lang="ts">
export default { name: "PlatformPnl" };
</script>

<script setup lang="ts">
import { onMounted, reactive, computed } from "vue";
import { platformDailyPnl, platformDailyPnlBackfill } from "@/api/system/dashboard";
import { ElMessage, ElMessageBox } from "element-plus";

interface DayRow {
    stat_date: string;
    deposit_amount:    number;
    withdraw_amount:   number;
    self_open_count:   number;
    self_open_amount:  number;
    self_close_profit: number;
    self_close_loss:   number;
    self_close_diff:   number;
    self_fee:          number;
    self_funding_fee:  number;
    copy_open_count:   number;
    copy_open_amount:  number;
    copy_close_profit: number;
    copy_close_loss:   number;
    copy_close_diff:   number;
    copy_fee:          number;
    copy_funding_fee:  number;
}

const state = reactive({
    loading:         false,
    backfillLoading: false,
    includeInternal: 0 as 0 | 1,
    dateRange:       [] as string[],
    rows:            [] as DayRow[],
    page:            1,
    pageSize:        15,
});

// ── 汇总行 ─────────────────────────────────────────────────────────────────
const numCols: (keyof Omit<DayRow, "stat_date">)[] = [
    "deposit_amount", "withdraw_amount",
    "self_open_count", "self_open_amount", "self_close_profit", "self_close_loss", "self_close_diff", "self_fee", "self_funding_fee",
    "copy_open_count", "copy_open_amount", "copy_close_profit", "copy_close_loss", "copy_close_diff", "copy_fee", "copy_funding_fee",
];

const pagedRows = computed(() => {
    const start = (state.page - 1) * state.pageSize;
    return state.rows.slice(start, start + state.pageSize);
});

const totals = computed(() => {
    const t: Record<string, number> = {};
    for (const col of numCols) {
        t[col] = state.rows.reduce((sum, r) => sum + (Number(r[col]) || 0), 0);
    }
    return t;
});

// ── 格式化 ─────────────────────────────────────────────────────────────────
function fmt(v: number | null | undefined, decimals = 2): string {
    if (v == null) return "--";
    return Number(v).toLocaleString("en-US", {
        minimumFractionDigits: decimals,
        maximumFractionDigits: decimals,
    });
}
function fmtInt(v: number | null | undefined): string {
    if (v == null) return "--";
    return Number(v).toLocaleString("en-US");
}
function diffClass(v: number | null | undefined): string {
    if (v == null) return "";
    return Number(v) >= 0 ? "is-profit" : "is-loss";
}

// ── 数据加载 ───────────────────────────────────────────────────────────────
async function load() {
    state.loading = true;
    try {
        const params: any = { includeInternal: state.includeInternal };
        if (state.dateRange?.length === 2) {
            params.startDate = state.dateRange[0];
            params.endDate   = state.dateRange[1];
        }
        const res: any = await platformDailyPnl(params);
        state.rows = (res?.data ?? []).map((r: any) => ({
            stat_date:         r.stat_date,
            deposit_amount:    Number(r.deposit_amount)    || 0,
            withdraw_amount:   Number(r.withdraw_amount)   || 0,
            self_open_count:   Number(r.self_open_count)   || 0,
            self_open_amount:  Number(r.self_open_amount)  || 0,
            self_close_profit: Number(r.self_close_profit) || 0,
            self_close_loss:   Number(r.self_close_loss)   || 0,
            self_close_diff:   Number(r.self_close_diff)   || 0,
            self_fee:          Number(r.self_fee)          || 0,
            self_funding_fee:  Number(r.self_funding_fee)  || 0,
            copy_open_count:   Number(r.copy_open_count)   || 0,
            copy_open_amount:  Number(r.copy_open_amount)  || 0,
            copy_close_profit: Number(r.copy_close_profit) || 0,
            copy_close_loss:   Number(r.copy_close_loss)   || 0,
            copy_close_diff:   Number(r.copy_close_diff)   || 0,
            copy_fee:          Number(r.copy_fee)          || 0,
            copy_funding_fee:  Number(r.copy_funding_fee)  || 0,
        }));
    } catch (e) {
        console.error("[PlatformPnl] 加载失败", e);
    } finally {
        state.loading = false;
    }
}

function handleSearch() {
    state.page = 1;
    load();
}

function handleReset() {
    state.dateRange       = [];
    state.includeInternal = 0;
    state.page            = 1;
    load();
}

async function handleBackfill() {
    await ElMessageBox.confirm(
        "将补算过去 90 天历史数据，可能耗时较长，确认继续？",
        "补算历史数据", { type: "warning" }
    );
    state.backfillLoading = true;
    try {
        await platformDailyPnlBackfill(90);
        ElMessage.success("已触发补算，请稍后刷新页面查看");
    } catch (e) {
        ElMessage.error("补算触发失败");
    } finally {
        state.backfillLoading = false;
    }
}

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

<template>
    <div class="platform-pnl-container">
        <!-- 搜索栏 -->
        <el-card shadow="never" class="filter-card">
            <el-form inline>
                <el-form-item label="日期范围">
                    <el-date-picker
                        v-model="state.dateRange"
                        type="daterange"
                        range-separator="—"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        value-format="YYYY-MM-DD"
                        style="width: 260px"
                    />
                </el-form-item>
                <el-form-item label="内部账户">
                    <el-select v-model="state.includeInternal" style="width: 110px">
                        <el-option label="排除" :value="0" />
                        <el-option label="包含" :value="1" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">搜索</el-button>
                    <el-button @click="handleReset">重置</el-button>
                    <el-button
                        :loading="state.backfillLoading"
                        @click="handleBackfill"
                    >补算历史数据</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 合计行 -->
        <el-card shadow="never" class="summary-card" v-if="state.rows.length > 0">
            <div class="summary-grid">
                <div class="summary-item">
                    <span class="s-label">累计充值</span>
                    <span class="s-value">{{ fmt(totals.deposit_amount) }}</span>
                </div>
                <div class="summary-item">
                    <span class="s-label">累计提现</span>
                    <span class="s-value">{{ fmt(totals.withdraw_amount) }}</span>
                </div>
                <div class="summary-item">
                    <span class="s-label">合约开仓次数</span>
                    <span class="s-value">{{ fmtInt(totals.self_open_count) }}</span>
                </div>
                <div class="summary-item">
                    <span class="s-label">合约开仓金额（USDT）</span>
                    <span class="s-value">{{ fmt(totals.self_open_amount) }}</span>
                </div>
                <div class="summary-item">
                    <span class="s-label">合约平仓盈利</span>
                    <span class="s-value is-profit">{{ fmt(totals.self_close_profit) }}</span>
                </div>
                <div class="summary-item">
                    <span class="s-label">合约平仓亏损</span>
                    <span class="s-value is-loss">{{ fmt(totals.self_close_loss) }}</span>
                </div>
                <div class="summary-item">
                    <span class="s-label">合约差额</span>
                    <span class="s-value" :class="diffClass(totals.self_close_diff)">{{ fmt(totals.self_close_diff) }}</span>
                </div>
                <div class="summary-item">
                    <span class="s-label">合约手续费</span>
                    <span class="s-value">{{ fmt(totals.self_fee) }}</span>
                </div>
                <div class="summary-item">
                    <span class="s-label">合约资金费</span>
                    <span class="s-value">{{ fmt(totals.self_funding_fee) }}</span>
                </div>
                <div class="summary-item">
                    <span class="s-label">跟单开仓次数</span>
                    <span class="s-value">{{ fmtInt(totals.copy_open_count) }}</span>
                </div>
                <div class="summary-item">
                    <span class="s-label">跟单开仓金额</span>
                    <span class="s-value">{{ fmt(totals.copy_open_amount) }}</span>
                </div>
                <div class="summary-item">
                    <span class="s-label">跟单平仓盈利</span>
                    <span class="s-value is-profit">{{ fmt(totals.copy_close_profit) }}</span>
                </div>
                <div class="summary-item">
                    <span class="s-label">跟单平仓亏损</span>
                    <span class="s-value is-loss">{{ fmt(totals.copy_close_loss) }}</span>
                </div>
                <div class="summary-item">
                    <span class="s-label">跟单差额</span>
                    <span class="s-value" :class="diffClass(totals.copy_close_diff)">{{ fmt(totals.copy_close_diff) }}</span>
                </div>
                <div class="summary-item">
                    <span class="s-label">跟单手续费</span>
                    <span class="s-value">{{ fmt(totals.copy_fee) }}</span>
                </div>
                <div class="summary-item">
                    <span class="s-label">跟单资金费</span>
                    <span class="s-value">{{ fmt(totals.copy_funding_fee) }}</span>
                </div>
            </div>
        </el-card>

        <!-- 数据表格 -->
        <el-card shadow="never" class="table-card">
            <el-table
                v-loading="state.loading"
                :data="pagedRows"
                border
                stripe
                size="small"
                style="width: 100%"
            >
                <el-table-column label="日期" prop="stat_date" min-width="100" fixed="left" align="center" />
                <el-table-column label="充值" min-width="120" align="right">
                    <template #default="{ row }">{{ fmt(row.deposit_amount) }}</template>
                </el-table-column>
                <el-table-column label="提现" min-width="120" align="right">
                    <template #default="{ row }">{{ fmt(row.withdraw_amount) }}</template>
                </el-table-column>

                <!-- 合约 -->
                <el-table-column label="合约开仓次数" min-width="110" align="right">
                    <template #default="{ row }">{{ fmtInt(row.self_open_count) }}</template>
                </el-table-column>
                <el-table-column label="合约开仓金额（USDT）" min-width="150" align="right">
                    <template #default="{ row }">{{ fmt(row.self_open_amount) }}</template>
                </el-table-column>
                <el-table-column label="合约平仓盈利" min-width="130" align="right">
                    <template #default="{ row }">
                        <span class="is-profit">{{ fmt(row.self_close_profit) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="合约平仓亏损" min-width="130" align="right">
                    <template #default="{ row }">
                        <span class="is-loss">{{ fmt(row.self_close_loss) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="合约差额" min-width="120" align="right">
                    <template #default="{ row }">
                        <span :class="diffClass(row.self_close_diff)">{{ fmt(row.self_close_diff) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="合约交易手续费" min-width="130" align="right">
                    <template #default="{ row }">{{ fmt(row.self_fee) }}</template>
                </el-table-column>
                <el-table-column label="合约资金费" min-width="120" align="right">
                    <template #default="{ row }">{{ fmt(row.self_funding_fee) }}</template>
                </el-table-column>

                <!-- 跟单 -->
                <el-table-column label="跟单开仓次数" min-width="110" align="right">
                    <template #default="{ row }">{{ fmtInt(row.copy_open_count) }}</template>
                </el-table-column>
                <el-table-column label="跟单开仓金额" min-width="130" align="right">
                    <template #default="{ row }">{{ fmt(row.copy_open_amount) }}</template>
                </el-table-column>
                <el-table-column label="跟单平仓盈利" min-width="130" align="right">
                    <template #default="{ row }">
                        <span class="is-profit">{{ fmt(row.copy_close_profit) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="跟单平仓亏损" min-width="130" align="right">
                    <template #default="{ row }">
                        <span class="is-loss">{{ fmt(row.copy_close_loss) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="跟单差额" min-width="120" align="right">
                    <template #default="{ row }">
                        <span :class="diffClass(row.copy_close_diff)">{{ fmt(row.copy_close_diff) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="跟单交易手续费" min-width="130" align="right">
                    <template #default="{ row }">{{ fmt(row.copy_fee) }}</template>
                </el-table-column>
                <el-table-column label="跟单资金费" min-width="120" align="right">
                    <template #default="{ row }">{{ fmt(row.copy_funding_fee) }}</template>
                </el-table-column>
            </el-table>

            <el-empty v-if="!state.loading && state.rows.length === 0" description="暂无数据" style="padding: 40px 0" />

            <div v-if="state.rows.length > 0" class="pagination-wrap">
                <el-pagination
                    v-model:current-page="state.page"
                    :page-size="state.pageSize"
                    :total="state.rows.length"
                    layout="total, prev, pager, next, jumper"
                    background
                />
            </div>
        </el-card>
    </div>
</template>

<style lang="scss" scoped>
.platform-pnl-container {
    padding: 20px;
    background-color: rgb(240, 242, 245);
    min-height: 100%;
}

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

    :deep(.el-card__body) {
        padding: 16px 20px 8px;
    }
}

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

    :deep(.el-card__body) {
        padding: 16px 20px;
    }
}

.summary-grid {
    display: flex;
    flex-wrap: wrap;
    gap: 12px 0;
}

.summary-item {
    flex: 0 0 12.5%; /* 8 per row */
    display: flex;
    flex-direction: column;
    padding: 0 12px;
    border-right: 1px solid #ebeef5;

    &:last-child { border-right: none; }

    .s-label {
        font-size: 12px;
        color: #909399;
        margin-bottom: 4px;
        white-space: nowrap;
    }

    .s-value {
        font-size: 16px;
        font-weight: 600;
        color: #303133;
        font-variant-numeric: tabular-nums;
    }
}

.table-card {
    :deep(.el-card__body) { padding: 0; }
}

.pagination-wrap {
    display: flex;
    justify-content: flex-end;
    padding: 12px 16px;
    border-top: 1px solid #ebeef5;
}

.is-profit { color: #67c23a; }
.is-loss   { color: #f56c6c; }
</style>
