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

<script setup lang="ts">
import { onBeforeMount, reactive } from "vue";
import { todayOverview, refreshAll } from "@/api/system/dashboard";

const emit = defineEmits<{
    (e: "change-internal", v: boolean): void;
    (e: "refresh", includeInternal: number): void;
    (e: "loading-change", v: boolean): void;
}>();

// ---------- 数据状态 ----------
const state = reactive({
    loading: false,
    includeInternal: false,   // false=不含内部账户，true=含内部账户
    overview: {
        profit_loss:     null as number | null,
        deposit_amount:  null as number | null,
        withdraw_amount: null as number | null,
        trade_volume:    null as number | null,
        register_count:  null as number | null,
        login_count:     null as number | null,
        updated_time:    null as string | null,
    },
});

// ---------- 数据拉取 ----------
async function fetchData() {
    try {
        const res: any = await todayOverview(state.includeInternal ? 1 : 0);
        if (res?.data) state.overview = res.data;
    } catch (e) {
        console.error("[Dashboard] 获取今日概览失败", e);
    }
}

// ---------- 刷新（触发 datacenter 重算） ----------
async function handleRefresh() {
    state.loading = true;
    emit("loading-change", true);
    try {
        await refreshAll(state.includeInternal ? 1 : 0);
        await fetchData();
        emit("refresh", state.includeInternal ? 1 : 0);
    } catch (e) {
        console.error("[Dashboard] 刷新失败", e);
    } finally {
        state.loading = false;
        emit("loading-change", false);
    }
}

// ---------- 切换"统计内部账户" ----------
function toggleInternal() {
    state.includeInternal = !state.includeInternal;
    fetchData();
    emit("change-internal", state.includeInternal);
}

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

// ---------- 生命周期 ----------
onBeforeMount(() => {
    fetchData();
});
</script>

<template>
    <!-- 运营数据总览 卡片 -->
    <el-col :span="24" class="card-panel__col">
        <el-card class="overview-card" shadow="never">
            <template #header>
                <div class="overview-header">
                    <div class="header-left">
                        <span class="overview-title">运营数据总览</span>
                        <span class="overview-sub">实时监控平台核心数据与运营情况</span>
                    </div>
                    <div class="header-right">
                        <span v-if="state.overview.updated_time" class="time-text">
                            上次更新：{{ state.overview.updated_time }}
                        </span>
                        <el-button
                            size="small"
                            type="primary"
                            :loading="state.loading"
                            @click="handleRefresh"
                        >刷新</el-button>
                        <el-button
                            size="small"
                            :class="['toggle-btn', state.includeInternal ? 'is-active' : '']"
                            @click="toggleInternal"
                        >
                            <span class="toggle-dot" :class="state.includeInternal ? 'on' : 'off'">●</span>
                            统计内部账户
                        </el-button>
                    </div>
                </div>
            </template>

            <el-row
                :gutter="12"
            >
                <!-- 今日盈亏 -->
                <el-col :span="4">
                    <div class="stat-card">
                        <div class="stat-label">今日盈亏（USDT）</div>
                        <div class="stat-value" :class="pnlClass(state.overview.profit_loss)">
                            {{ fmt(state.overview.profit_loss) }}
                        </div>
                    </div>
                </el-col>

                <!-- 今日充值 -->
                <el-col :span="4">
                    <div class="stat-card">
                        <div class="stat-label">今日充值（USDT）</div>
                        <div class="stat-value">{{ fmt(state.overview.deposit_amount) }}</div>
                    </div>
                </el-col>

                <!-- 今日提现 -->
                <el-col :span="4">
                    <div class="stat-card">
                        <div class="stat-label">今日提现（USDT）</div>
                        <div class="stat-value">{{ fmt(state.overview.withdraw_amount) }}</div>
                    </div>
                </el-col>

                <!-- 今日交易额 -->
                <el-col :span="4">
                    <div class="stat-card">
                        <div class="stat-label">今日交易额（USDT）</div>
                        <div class="stat-value">{{ fmt(state.overview.trade_volume) }}</div>
                    </div>
                </el-col>

                <!-- 今日注册 -->
                <el-col :span="4">
                    <div class="stat-card">
                        <div class="stat-label">今日注册（人）</div>
                        <div class="stat-value">{{ fmtInt(state.overview.register_count) }}</div>
                    </div>
                </el-col>

                <!-- 今日登录 -->
                <el-col :span="4">
                    <div class="stat-card">
                        <div class="stat-label">今日登录（人）</div>
                        <div class="stat-value">{{ fmtInt(state.overview.login_count) }}</div>
                    </div>
                </el-col>
            </el-row>
        </el-card>
    </el-col>
</template>

<style lang="scss" scoped>
.overview-card {
    border-radius: 4px;

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

.overview-header {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .header-left {
        display: flex;
        flex-direction: column;
        gap: 2px;
    }

    .overview-title {
        font-size: 16px;
        font-weight: 600;
        color: #303133;
    }

    .overview-sub {
        font-size: 12px;
        color: #909399;
    }

    .header-right {
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .time-text {
        font-size: 13px;
        color: #909399;
        white-space: nowrap;
    }
}

/* 统计内部账户切换按钮 */
.toggle-btn {
    background: #f4f4f5;
    border-color: #dcdfe6;
    color: #606266;

    &.is-active {
        background: #303133;
        border-color: #303133;
        color: #ffffff;
    }

    .toggle-dot {
        font-size: 10px;
        margin-right: 4px;

        &.on  { color: #67c23a; }
        &.off { color: #c0c4cc; }
    }
}

/* 6 个统计卡片 */
.stat-card {
    background: #f7f8fa;
    border-radius: 4px;
    padding: 16px 20px;
    min-height: 80px;

    .stat-label {
        font-size: 13px;
        color: #606266;
        margin-bottom: 10px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    .stat-value {
        font-size: 22px;
        font-weight: 600;
        color: #303133;
        font-variant-numeric: tabular-nums;

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