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

<script setup lang="ts">
import { nextTick, onBeforeUnmount, onMounted, reactive, ref, watch } from "vue";
import { useRouter } from "vue-router";
import { init, EChartsOption } from "echarts";
import resize from "@/utils/resize";
import { dailyRecharge, dailyRechargeBackfill } from "@/api/system/dashboard";
import { ElMessage } from "element-plus";

const router = useRouter();

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

interface DayRow {
    stat_date:      string;
    deposit_amount: number;
    withdraw_amount: number;
    net_amount:     number;
}

const state = reactive({
    loading: false,
    syncing: false,
    days:    7 as 7 | 30,
    rows:    [] as DayRow[],
});

const { mounted: resizeMounted, chart, beforeDestroy } = resize();

watch(() => props.includeInternal, () => load());

async function load(days: 7 | 30 = state.days) {
    state.loading = true;
    try {
        const res: any = await dailyRecharge(days, (props.includeInternal ?? 0) as 0 | 1);
        state.rows = (res?.data ?? []).map((r: any) => {
            const d = Number(r.deposit_amount)  || 0;
            const w = Number(r.withdraw_amount) || 0;
            return { stat_date: r.stat_date, deposit_amount: d, withdraw_amount: w, net_amount: d - w };
        });
        await nextTick();
        renderChart();
    } catch (e) {
        console.error("[DailyRecharge]", e);
    } finally {
        state.loading = false;
    }
}

function setDays(days: 7 | 30) {
    state.days = days;
    load(days);
}

async function handleSync() {
    state.syncing = true;
    try {
        await dailyRechargeBackfill(30);
        ElMessage.success("历史数据同步完成");
        await load(state.days);
    } catch (e) {
        ElMessage.error("同步失败，请稍后重试");
    } finally {
        state.syncing = false;
    }
}

function fmtDate(d: string) {
    const parts = d.split("-");
    if (parts.length < 3) return d;
    return parseInt(parts[1]) + "月" + parseInt(parts[2]) + "日";
}

function fmt(v: number, dec = 2) {
    return Number(v).toLocaleString("en-US", {
        minimumFractionDigits: dec,
        maximumFractionDigits: dec,
    });
}

function netClass(v: number) {
    if (v > 0) return "is-inflow";
    if (v < 0) return "is-outflow";
    return "";
}

function renderChart() {
    const el = document.getElementById("dailyRechargeChart");
    if (!el) return;
    if (!chart.value) chart.value = init(el);

    const dates    = state.rows.map(r => fmtDate(r.stat_date));
    const deposits = state.rows.map(r => r.deposit_amount);
    const withdraws = state.rows.map(r => r.withdraw_amount);
    const nets     = state.rows.map(r => r.net_amount);

    const opts: EChartsOption = {
        color: ["#409eff", "#e6a23c", "#67c23a"],
        tooltip: {
            trigger: "axis",
            axisPointer: { type: "shadow" },
            formatter(params: any) {
                let s = params[0].name + "<br/>";
                params.forEach((p: any) => {
                    s += p.marker + p.seriesName + ": " + fmt(p.value) + "<br/>";
                });
                return s;
            },
        },
        legend: {
            data: ["充值", "提现", "净流入"],
            top: 4,
            textStyle: { fontSize: 12 },
            selectedMode: false,
        },
        grid: {
            top: 36,
            bottom: 24,
            left: 12,
            right: 12,
            containLabel: true,
        },
        xAxis: {
            type: "category",
            data: dates,
            axisLabel: { fontSize: 11 },
            axisTick: { show: false },
            axisLine: { lineStyle: { color: "#ddd" } },
        },
        yAxis: {
            type: "value",
            axisLabel: {
                fontSize: 11,
                formatter: (v: number) =>
                    v >= 1e6 ? (v / 1e6).toFixed(1) + "M"
                    : v >= 1e3 ? (v / 1e3).toFixed(0) + "K"
                    : String(v),
            },
            splitLine: { lineStyle: { color: "#f5f5f5" } },
        },
        series: [
            {
                name: "充值",
                type: "bar",
                data: deposits,
                barMaxWidth: 20,
                itemStyle: { borderRadius: [3, 3, 0, 0] },
            },
            {
                name: "提现",
                type: "bar",
                data: withdraws,
                barMaxWidth: 20,
                itemStyle: { borderRadius: [3, 3, 0, 0] },
            },
            {
                name: "净流入",
                type: "bar",
                data: nets,
                barMaxWidth: 14,
                itemStyle: { borderRadius: [3, 3, 0, 0] },
            },
        ],
    };
    chart.value.setOption(opts, true);
}

onBeforeUnmount(() => { beforeDestroy(); });

onMounted(() => {
    resizeMounted();
    load();
});

defineExpose({ reload: load });
</script>

<template>
    <el-col :span="24" class="card-panel__col">
        <el-card class="daily-recharge-card" shadow="never">
            <template #header>
                <div class="rc-header">
                    <span class="rc-title">充值提现统计</span>
                    <div class="header-actions">
                        <el-button
                            size="small"
                            :type="state.days === 7 ? 'primary' : ''"
                            @click="setDays(7)"
                        >最近7日</el-button>
                        <el-button
                            size="small"
                            :type="state.days === 30 ? 'primary' : ''"
                            @click="setDays(30)"
                        >最近30日</el-button>
                        <el-button
                            size="small"
                            :loading="state.syncing"
                            @click="handleSync"
                        >同步历史数据</el-button>
                        <el-button
                            size="small"
                            type="default"
                            @click="router.push('/platform-pnl')"
                        >查看明细</el-button>
                    </div>
                </div>
            </template>

            <div v-loading="state.loading" element-loading-text="加载中...">
                <div id="dailyRechargeChart" style="height: 300px; width: 100%" />

                <div class="table-scroll" v-if="state.rows.length > 0">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th class="label-th"></th>
                                <th v-for="row in state.rows" :key="row.stat_date">
                                    {{ fmtDate(row.stat_date) }}
                                </th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td class="label-td">
                                    <span class="dot" style="background:#409eff" />充值
                                </td>
                                <td v-for="row in state.rows" :key="row.stat_date" class="is-inflow">
                                    {{ fmt(row.deposit_amount) }}
                                </td>
                            </tr>
                            <tr>
                                <td class="label-td">
                                    <span class="dot" style="background:#e6a23c" />提现
                                </td>
                                <td v-for="row in state.rows" :key="row.stat_date" class="is-outflow">
                                    {{ fmt(row.withdraw_amount) }}
                                </td>
                            </tr>
                            <tr>
                                <td class="label-td">
                                    <span class="dot" style="background:#67c23a" />净流入
                                </td>
                                <td
                                    v-for="row in state.rows"
                                    :key="row.stat_date"
                                    :class="netClass(row.net_amount)"
                                >
                                    {{ fmt(row.net_amount) }}
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <el-empty v-else-if="!state.loading" description="暂无数据" :image-size="60" style="padding: 20px 0" />
            </div>
        </el-card>
    </el-col>
</template>

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

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

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

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

    .header-actions {
        display: flex;
        gap: 8px;
    }
}

.table-scroll {
    margin-top: 12px;
    overflow-x: auto;
}

.data-table {
    border-collapse: collapse;
    width: 100%;
    min-width: max-content;
    font-size: 12px;

    th, td {
        padding: 6px 10px;
        text-align: center;
        border: 1px solid #ebeef5;
        white-space: nowrap;
    }

    th {
        background: #f5f7fa;
        color: #606266;
        font-weight: 600;
    }

    .label-th, .label-td {
        text-align: left;
        min-width: 64px;
        background: #fafafa;
        font-weight: 600;
        color: #303133;
    }
}

.dot {
    display: inline-block;
    width: 10px;
    height: 10px;
    border-radius: 2px;
    margin-right: 5px;
    vertical-align: middle;
}

.is-inflow  { color: #409eff; }
.is-outflow { color: #e6a23c; }
</style>
