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

<script setup lang="ts">
import { reactive, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import {
    copyTradePositionList,
    copyTradePositionRefresh,
    copyTradePositionForceClose,
    traderHierarchy,
} from "@/api/documentary/index";
import useUserStore from "@/store/modules/user";

const router = useRouter();

interface Row {
    trader_member_id:        number;
    trader_level:            string;
    symbol:                  string;
    direction:               number;
    leverage_rate:           number;
    trader_pos_usdt:         number;
    trader_unrealized_pnl:   number;
    profit_rate:             number;
    normal_follow_count:     number;
    normal_follow_pos_usdt:  number;
    normal_follow_pnl:       number;
    special_follow_count:    number;
    special_follow_pos_usdt: number;
    special_follow_pnl:      number;
}

const state = reactive({
    loading:       false,
    refreshing:    false,
    rows:          [] as Row[],
    total:         0,
    pageNo:        1,
    pageSize:      20,
    lastStatTime:  null as string | null,
    selectedRows:  [] as Row[],
    levelOptions:  [] as { id: number; name: string }[],
    query: {
        traderMemberId: "" as string | number,
        traderLevel:    "",
        symbol:         "",
        direction:      "" as "" | 0 | 1,
        profitStatus:   "" as "" | "positive" | "negative",
    },
    // 强平弹框（单行 / 批量复用同一个）
    forceClose: {
        visible:        false,
        submitting:     false,
        batchMode:      false,
        traderMemberId: 0 as number,
        symbol:         "",
        password:       "",
    },
});

const userStore = useUserStore();

const summary = computed(() => state.rows.reduce(
    (acc, r) => {
        acc.normalCount    += r.normal_follow_count    || 0;
        acc.normalPosUsdt  += r.normal_follow_pos_usdt || 0;
        acc.normalPnl      += r.normal_follow_pnl      || 0;
        acc.specialCount   += r.special_follow_count   || 0;
        acc.specialPosUsdt += r.special_follow_pos_usdt || 0;
        acc.specialPnl     += r.special_follow_pnl     || 0;
        return acc;
    },
    { normalCount: 0, normalPosUsdt: 0, normalPnl: 0,
      specialCount: 0, specialPosUsdt: 0, specialPnl: 0 }
));

async function load() {
    state.loading = true;
    try {
        const params: any = { pageNo: state.pageNo, pageSize: state.pageSize };
        if (state.query.traderMemberId !== "") params.traderMemberId = state.query.traderMemberId;
        if (state.query.traderLevel)         params.traderLevel   = state.query.traderLevel;
        if (state.query.symbol)              params.symbol        = state.query.symbol;
        if (state.query.direction !== "")    params.direction     = state.query.direction;
        if (state.query.profitStatus)        params.profitStatus  = state.query.profitStatus;

        const res: any = await copyTradePositionList(params);
        const data = res?.data ?? {};
        state.rows         = data.content ?? [];
        state.total        = data.totalElements ?? 0;
        state.lastStatTime = data.lastStatTime ?? null;
        state.selectedRows = [];
    } catch (e) {
        console.error("[CopyTradePosition]", e);
        ElMessage.error("数据加载失败");
    } finally {
        state.loading = false;
    }
}

function handleQuery() { state.pageNo = 1; load(); }

function handleReset() {
    state.query.traderMemberId = "";
    state.query.traderLevel    = "";
    state.query.symbol         = "";
    state.query.direction      = "";
    state.query.profitStatus   = "";
    handleQuery();
}

async function handleRefresh() {
    state.refreshing = true;
    try {
        await copyTradePositionRefresh();
        ElMessage.success("快照刷新成功");
        await load();
    } catch (e) {
        ElMessage.error("刷新失败，请稍后重试");
    } finally {
        state.refreshing = false;
    }
}

function handleSelectionChange(rows: Row[]) {
    state.selectedRows = rows;
}

// 单行强平
function openForceClose(row: Row) {
    state.forceClose.batchMode      = false;
    state.forceClose.traderMemberId = row.trader_member_id;
    state.forceClose.symbol         = row.symbol;
    state.forceClose.password       = "";
    state.forceClose.visible        = true;
}

// 批量强平（头部按钮）
function openBatchForceClose() {
    if (state.selectedRows.length === 0) {
        ElMessage.warning("请先勾选需要平仓的仓位");
        return;
    }
    state.forceClose.batchMode = true;
    state.forceClose.password  = "";
    state.forceClose.visible   = true;
}

async function submitForceClose() {
    if (!state.forceClose.password) {
        ElMessage.warning("请输入管理员密码");
        return;
    }
    state.forceClose.submitting = true;
    try {
        const targets = state.forceClose.batchMode
            ? state.selectedRows
            : [{ trader_member_id: state.forceClose.traderMemberId, symbol: state.forceClose.symbol } as Row];

        let failCount = 0;
        for (const row of targets) {
            const res: any = await copyTradePositionForceClose({
                traderMemberId: row.trader_member_id,
                symbol:         row.symbol,
                username:       userStore.username,
                password:       state.forceClose.password,
            });
            if (res?.code !== 0) failCount++;
        }

        if (failCount === 0) {
            ElMessage.success(state.forceClose.batchMode
                ? `已发送 ${targets.length} 条强平指令`
                : "强平指令已发送");
        } else {
            ElMessage.warning(`${targets.length - failCount} 条成功，${failCount} 条失败`);
        }
        state.forceClose.visible = false;
        // 平仓指令走 Kafka 异步处理，稍等后再刷新快照
        ElMessage.info("平仓指令已发送，3秒后自动刷新快照...");
        setTimeout(async () => {
            try {
                state.refreshing = true;
                await copyTradePositionRefresh();
                await load();
            } catch {
                // 刷新失败不影响主流程，用户可手动刷新
            } finally {
                state.refreshing = false;
            }
        }, 3000);
    } catch {
        // 拦截器已弹出错误信息（code=500），此处不重复提示
    } finally {
        state.forceClose.submitting = false;
    }
}

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

function fmtRate(v: number | null | undefined) {
    if (v == null) return "—";
    return Number(v).toFixed(2) + "%";
}

function pnlClass(v: number) {
    if (v > 0) return "is-profit";
    if (v < 0) return "is-loss";
    return "";
}

onMounted(() => {
    load();
    traderHierarchy().then((res: any) => {
        state.levelOptions = res?.data ?? [];
    }).catch(() => {});
});
</script>

<template>
    <div class="app-container">
        <!-- 筛选栏 -->
        <div class="filter-bar">
            <el-form :inline="true" class="filter-form">
                <el-form-item label="交易员ID">
                    <el-input
                        v-model="state.query.traderMemberId"
                        placeholder="交易员UID"
                        clearable
                        style="width: 120px"
                        @keyup.enter="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="交易员等级">
                    <el-select
                        v-model="state.query.traderLevel"
                        placeholder="全部"
                        clearable
                        style="width: 110px"
                    >
                        <el-option
                            v-for="lv in state.levelOptions"
                            :key="lv.id"
                            :label="lv.name"
                            :value="lv.name"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="交易对">
                    <el-select
                        v-model="state.query.symbol"
                        placeholder="请选择"
                        clearable
                        style="width: 130px"
                    >
                        <el-option label="BTC/USDT" value="BTC/USDT" />
                        <el-option label="ETH/USDT" value="ETH/USDT" />
                    </el-select>
                </el-form-item>
                <el-form-item label="仓位方向">
                    <el-select v-model="state.query.direction" style="width: 100px" clearable placeholder="全部">
                        <el-option label="做多" :value="0" />
                        <el-option label="做空" :value="1" />
                    </el-select>
                </el-form-item>
                <el-form-item label="仓位盈亏">
                    <el-select v-model="state.query.profitStatus" style="width: 100px" clearable placeholder="全部">
                        <el-option label="盈利" value="positive" />
                        <el-option label="亏损" value="negative" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleQuery">搜索</el-button>
                    <el-button @click="handleReset">重置</el-button>
                    <el-button
                        type="warning"
                        :disabled="state.selectedRows.length === 0"
                        @click="openBatchForceClose"
                    >一键平仓{{ state.selectedRows.length > 0 ? `(${state.selectedRows.length})` : '' }}</el-button>
                </el-form-item>
            </el-form>

            <!-- 右侧刷新区 -->
            <div class="refresh-area">
                <span class="refresh-time">
                    {{ state.lastStatTime ? state.lastStatTime.replace('T', ' ').substring(0, 19) : '暂无快照' }}
                </span>
                <el-button
                    type="primary"
                    :loading="state.refreshing"
                    @click="handleRefresh"
                >刷新</el-button>
            </div>
        </div>

        <!-- 汇总统计（两行：普通 / 无损） -->
        <div class="summary-panel">
            <div class="summary-row">
                <div class="summary-item">
                    <span class="summary-label">普通跟单未实现总盈亏</span>
                    <span class="summary-value" :class="pnlClass(summary.normalPnl)">{{ fmtUsdt(summary.normalPnl) }}</span>
                </div>
                <div class="summary-divider" />
                <div class="summary-item">
                    <span class="summary-label">普通跟单仓位数量</span>
                    <span class="summary-value">{{ summary.normalCount }}</span>
                </div>
                <div class="summary-divider" />
                <div class="summary-item">
                    <span class="summary-label">普通跟单仓位金额</span>
                    <span class="summary-value">{{ fmtUsdt(summary.normalPosUsdt) }}</span>
                </div>
            </div>
            <div class="summary-separator" />
            <div class="summary-row">
                <div class="summary-item">
                    <span class="summary-label">无损跟单未实现总盈亏</span>
                    <span class="summary-value" :class="pnlClass(summary.specialPnl)">{{ fmtUsdt(summary.specialPnl) }}</span>
                </div>
                <div class="summary-divider" />
                <div class="summary-item">
                    <span class="summary-label">无损跟单仓位数量</span>
                    <span class="summary-value">{{ summary.specialCount }}</span>
                </div>
                <div class="summary-divider" />
                <div class="summary-item">
                    <span class="summary-label">无损跟单仓位金额</span>
                    <span class="summary-value">{{ fmtUsdt(summary.specialPosUsdt) }}</span>
                </div>
            </div>
        </div>

        <!-- 数据表格 -->
        <el-table
            v-loading="state.loading"
            :data="state.rows"
            border
            style="width: 100%; margin-top: 12px"
            size="small"
            @selection-change="handleSelectionChange"
        >
            <el-table-column type="selection" width="45" fixed />
            <el-table-column label="交易员ID" prop="trader_member_id" width="100" fixed />
            <el-table-column label="交易员等级" width="100">
                <template #default="{ row }">{{ row.trader_level || '—' }}</template>
            </el-table-column>
            <el-table-column label="交易对" width="170" fixed>
                <template #default="{ row }">
                    <div class="symbol-cell">
                        <span>{{ row.symbol }}</span>
                        <el-tag
                            :type="row.direction === 0 ? 'success' : 'danger'"
                            size="small"
                            style="margin: 0 4px"
                        >{{ row.direction === 0 ? '做多' : '做空' }}</el-tag>
                        <span class="leverage-tag">{{ row.leverage_rate }}X</span>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="仓位盈亏" width="80">
                <template #default="{ row }">
                    <el-tag
                        :type="row.trader_unrealized_pnl > 0 ? 'success' : row.trader_unrealized_pnl < 0 ? 'danger' : 'info'"
                        size="small"
                    >{{ row.trader_unrealized_pnl > 0 ? '盈利' : row.trader_unrealized_pnl < 0 ? '亏损' : '持平' }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="持仓量（USDT）" width="130">
                <template #default="{ row }">{{ fmtUsdt(row.trader_pos_usdt) }}</template>
            </el-table-column>
            <el-table-column label="带单员未实现盈亏（USDT）" width="190">
                <template #default="{ row }">
                    <span :class="pnlClass(row.trader_unrealized_pnl)">{{ fmtUsdt(row.trader_unrealized_pnl) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="收益率" width="90">
                <template #default="{ row }">
                    <span :class="pnlClass(row.profit_rate)">{{ fmtRate(row.profit_rate) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="跟单持仓仓位数量" width="130">
                <template #default="{ row }">
                    {{ (row.normal_follow_count || 0) + (row.special_follow_count || 0) }}
                </template>
            </el-table-column>
            <el-table-column label="跟单持仓量（USDT）" width="150">
                <template #default="{ row }">
                    {{ fmtUsdt((row.normal_follow_pos_usdt || 0) + (row.special_follow_pos_usdt || 0)) }}
                </template>
            </el-table-column>
            <el-table-column label="跟单用户未实现盈亏（USDT）" width="200">
                <template #default="{ row }">
                    <span :class="pnlClass((row.normal_follow_pnl || 0) + (row.special_follow_pnl || 0))">
                        {{ fmtUsdt((row.normal_follow_pnl || 0) + (row.special_follow_pnl || 0)) }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="175" fixed="right">
                <template #default="{ row }">
                    <div style="display:flex;gap:4px;flex-wrap:nowrap">
                        <el-button
                            type="primary"
                            size="small"
                            @click="router.push({ name: 'CopyTradePositionDetail', query: { traderMemberId: row.trader_member_id, symbol: row.symbol } })"
                        >查看明细</el-button>
                        <el-button type="danger" size="small" @click="openForceClose(row)">一键平仓</el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
            v-model:current-page="state.pageNo"
            v-model:page-size="state.pageSize"
            :total="state.total"
            :page-sizes="[20, 50, 100]"
            layout="total, sizes, prev, pager, next"
            style="margin-top: 12px; justify-content: flex-end"
            @current-change="load"
            @size-change="handleQuery"
        />

        <!-- 强平弹框（单行 + 批量复用） -->
        <el-dialog
            v-model="state.forceClose.visible"
            :title="state.forceClose.batchMode ? '批量一键平仓' : '一键平仓确认'"
            width="440px"
            :close-on-click-modal="false"
        >
            <p class="confirm-text">
                <template v-if="state.forceClose.batchMode">
                    确认强平已选中的
                    <b>{{ state.selectedRows.length }}</b>
                    个仓位（含各自跟单仓位）？此操作不可撤销。
                </template>
                <template v-else>
                    确认强平交易员
                    <b>{{ state.forceClose.traderMemberId }}</b>
                    在
                    <b>{{ state.forceClose.symbol }}</b>
                    上的所有持仓（含跟单仓位）？此操作不可撤销。
                </template>
            </p>
            <el-form label-width="90px" style="margin-top: 16px">
                <el-form-item label="管理员密码">
                    <el-input
                        v-model="state.forceClose.password"
                        type="password"
                        placeholder="请输入管理员密码"
                        show-password
                        autocomplete="off"
                        @keyup.enter="submitForceClose"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="state.forceClose.visible = false">取消</el-button>
                <el-button
                    type="danger"
                    :loading="state.forceClose.submitting"
                    @click="submitForceClose"
                >确认平仓</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<style scoped>
.filter-bar {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    background: #fff;
    padding: 12px 20px 4px;
    border-radius: 4px;
    margin-bottom: 12px;
}

.filter-form {
    flex: 1;
}

.refresh-area {
    display: flex;
    align-items: center;
    gap: 8px;
    white-space: nowrap;
    padding-top: 4px;
}

.refresh-time {
    font-size: 12px;
    color: #909399;
    background: #1a1a2e;
    color: #fff;
    padding: 4px 10px;
    border-radius: 4px;
    letter-spacing: 0.5px;
}

.summary-panel {
    background: #f5f7fa;
    border-radius: 4px;
    padding: 12px 24px;
    margin-bottom: 12px;
}

.summary-row {
    display: flex;
    align-items: center;
    padding: 8px 0;
}

.summary-separator {
    height: 1px;
    background: #e4e7ed;
    margin: 0 -4px;
}

.summary-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    flex: 1;
    padding: 2px 0;
}

.summary-divider {
    width: 1px;
    height: 32px;
    background: #dcdfe6;
}

.summary-label {
    font-size: 12px;
    color: #909399;
    margin-bottom: 4px;
}

.summary-value {
    font-size: 18px;
    font-weight: 600;
    color: #303133;
}

.symbol-cell {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 2px;
}

.leverage-tag {
    font-size: 11px;
    color: #e6a23c;
    font-weight: 600;
}

.confirm-text {
    color: #606266;
    line-height: 1.6;
}

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