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

<script setup lang="ts">
import { onBeforeMount, reactive, computed, watch, ref } from "vue";
import { contractPnl, contractPnlRefresh } from "@/api/system/dashboard";
import InventoryChart from "@/views/dashboard/components/Chart/InventoryChart.vue";
import DailyPnl from "@/views/dashboard/components/DailyPnl/index.vue";

const inventoryChartRef = ref<InstanceType<typeof InventoryChart>>();

const props = defineProps<{ includeInternal?: number }>();

const state = reactive({
    loading: false,
    activeTab: "self",
    data: null as Record<string, any> | null,
});

async function fetchData() {
    try {
        const res: any = await contractPnl((props.includeInternal ?? 0) as 0 | 1);
        if (res?.data) state.data = res.data;
    } catch (e) {
        console.error("[ContractPnl] 获取合约盈亏失败", e);
    }
}

async function forceRefresh() {
    state.loading = true;
    try {
        await contractPnlRefresh((props.includeInternal ?? 0) as 0 | 1);
        await fetchData();
        inventoryChartRef.value?.reload();
    } catch (e) {
        console.error("[ContractPnl] 刷新失败", e);
    } finally {
        state.loading = false;
    }
}

async function reload() {
    try {
        const res: any = await contractPnl((props.includeInternal ?? 0) as 0 | 1);
        if (res?.data) state.data = res.data;
        inventoryChartRef.value?.reload();
    } catch (e) {
        console.error("[ContractPnl] reload失败", e);
    }
}

defineExpose({ forceRefresh, reload });

watch(() => props.includeInternal, () => { fetchData(); });

const prefix = computed(() => state.activeTab === "self" ? "self" : "copy");

function val(suffix: string): number | null {
    if (!state.data) return null;
    const v = state.data[`${prefix.value}_${suffix}`];
    return v != null ? Number(v) : null;
}

function fmt(v: number | null | undefined, decimals = 2): string {
    if (v == null) return "--";
    return Number(v).toLocaleString("en-US", {
        minimumFractionDigits: decimals,
        maximumFractionDigits: decimals,
    });
}

function diffClass(v: number | null | undefined) {
    if (v == null) return "";
    return Number(v) >= 0 ? "is-profit" : "is-loss";
}

onBeforeMount(() => { fetchData(); });
</script>

<template>
    <el-col :span="24" class="card-panel__col">
        <el-card class="contract-pnl-card" shadow="never">
            <template #header>
                <el-tabs v-model="state.activeTab" class="header-tabs">
                    <el-tab-pane label="自主合约交易" name="self" />
                    <el-tab-pane label="跟单合约交易" name="copy" />
                </el-tabs>
            </template>

            <div class="inner-container" v-loading="state.loading" element-loading-text="正在加载统计数据...">
                <!-- 左侧：盈亏统计 -->
                <div class="left-panel">
                    <div class="section-title">{{ state.activeTab === "copy" ? "跟单合约盈亏数据" : "合约盈亏数据" }}</div>
                    <el-row :gutter="10">
                        <el-col :span="8">
                            <div class="stat-card">
                                <div class="stat-value is-profit">{{ fmt(val("hold_profit")) }}</div>
                                <div class="stat-label">当前持仓盈利（USDT）</div>
                            </div>
                        </el-col>
                        <el-col :span="8">
                            <div class="stat-card">
                                <div class="stat-value is-loss">{{ fmt(val("hold_loss")) }}</div>
                                <div class="stat-label">当前持仓亏损（USDT）</div>
                            </div>
                        </el-col>
                        <el-col :span="8">
                            <div class="stat-card">
                                <div class="stat-value" :class="diffClass(val('hold_diff'))">{{ fmt(val("hold_diff")) }}</div>
                                <div class="stat-label">当前持仓差额（USDT）</div>
                            </div>
                        </el-col>
                        <el-col :span="8">
                            <div class="stat-card">
                                <div class="stat-value is-profit">{{ fmt(val("today_close_profit")) }}</div>
                                <div class="stat-label">今日平仓盈利（USDT）</div>
                            </div>
                        </el-col>
                        <el-col :span="8">
                            <div class="stat-card">
                                <div class="stat-value is-loss">{{ fmt(val("today_close_loss")) }}</div>
                                <div class="stat-label">今日平仓亏损（USDT）</div>
                            </div>
                        </el-col>
                        <el-col :span="8">
                            <div class="stat-card">
                                <div class="stat-value" :class="diffClass(val('today_close_diff'))">{{ fmt(val("today_close_diff")) }}</div>
                                <div class="stat-label">今日平仓差额（USDT）</div>
                            </div>
                        </el-col>
                        <el-col :span="8">
                            <div class="stat-card no-margin">
                                <div class="stat-value is-profit">{{ fmt(val("total_close_profit")) }}</div>
                                <div class="stat-label">平仓总盈利（USDT）</div>
                            </div>
                        </el-col>
                        <el-col :span="8">
                            <div class="stat-card no-margin">
                                <div class="stat-value is-loss">{{ fmt(val("total_close_loss")) }}</div>
                                <div class="stat-label">平仓总亏损（USDT）</div>
                            </div>
                        </el-col>
                        <el-col :span="8">
                            <div class="stat-card no-margin">
                                <div class="stat-value" :class="diffClass(val('total_close_diff'))">{{ fmt(val("total_close_diff")) }}</div>
                                <div class="stat-label">平仓总差额（USDT）</div>
                            </div>
                        </el-col>
                    </el-row>
                </div>

                <!-- 分割线 -->
                <div class="divider" />

                <!-- 右侧：持仓图表 -->
                <div class="right-panel">
                    <InventoryChart ref="inventoryChartRef" id="inventoryChart" height="356px" width="100%" :type="state.activeTab as 'self' | 'copy'" />
                </div>
            </div>

            <!-- 每日盈亏统计（跟随tab切换自主/跟单数据）-->
            <div class="daily-pnl-divider" />
            <DailyPnl
                :type="state.activeTab as 'self' | 'copy'"
                :include-internal="props.includeInternal"
            />
        </el-card>
    </el-col>
</template>

<style lang="scss" scoped>
.contract-pnl-card {
    border-radius: 4px;
    margin-top: 12px;

    :deep(.el-card__header) {
        padding: 0 20px;
        border-bottom: 1px solid #ebeef5;
    }

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

.header-tabs {
    :deep(.el-tabs__header) {
        margin-bottom: 0;
    }
    :deep(.el-tabs__nav-wrap::after) {
        display: none;
    }
}

.inner-container {
    display: flex;
    border: 1px solid #e4e7ed;
    border-radius: 6px;
    overflow: hidden;
}

.left-panel {
    flex: 0 0 55%;
    min-width: 0;
    padding: 16px 20px;

    .section-title {
        font-size: 14px;
        font-weight: 600;
        color: #303133;
        margin-bottom: 14px;
    }
}

.divider {
    width: 1px;
    background: #e4e7ed;
    flex-shrink: 0;
}

.right-panel {
    flex: 1;
    min-width: 0;
}

.daily-pnl-divider {
    height: 1px;
    background: #ebeef5;
    margin: 0 0;
}

.stat-card {
    background: #f7f8fa;
    border-radius: 4px;
    padding: 14px 16px;
    margin-bottom: 10px;

    &.no-margin {
        margin-bottom: 0;
    }

    .stat-value {
        font-size: 20px;
        font-weight: 600;
        color: #303133;
        font-variant-numeric: tabular-nums;
        margin-bottom: 6px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;

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

    .stat-label {
        font-size: 12px;
        color: #909399;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
}
</style>
