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

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

interface Row {
    id:            number;
    member_id:     number;
    symbol:        string;
    direction:     number;
    leverage:      number;
    qty:           number;
    coin_qty:      number;
    open_price:    number;
    unrealized_pnl: number;
    profit_rate:   number;
}

const route     = useRoute();
const router    = useRouter();
const userStore = useUserStore();

const traderMemberId = Number(route.query.traderMemberId);
const symbol         = String(route.query.symbol ?? "");

// derive coin name from symbol, e.g. "ETH/USDT" → "ETH"
const coinName = computed(() => symbol.split("/")[0] || "");

const state = reactive({
    loading:  false,
    rows:     [] as Row[],
    total:    0,
    pageNo:   1,
    pageSize: 20,
    keyword:  "",
    forceClose: {
        visible:    false,
        submitting: false,
        positionId: 0 as number,
        memberId:   0 as number,
        password:   "",
    },
});

async function load() {
    state.loading = true;
    try {
        const params: any = {
            traderMemberId,
            symbol,
            pageNo:   state.pageNo,
            pageSize: state.pageSize,
        };
        if (state.keyword) params.memberKeyword = state.keyword;
        const res: any = await copyTradePositionDetail(params);
        const data = res?.data ?? {};
        state.rows  = data.content ?? [];
        state.total = data.totalElements ?? 0;
    } catch (e) {
        ElMessage.error("数据加载失败");
    } finally {
        state.loading = false;
    }
}

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

function openForceClose(row: Row) {
    state.forceClose.positionId = row.id;
    state.forceClose.memberId   = row.member_id;
    state.forceClose.password   = "";
    state.forceClose.visible    = true;
}

async function submitForceClose() {
    if (!state.forceClose.password) {
        ElMessage.warning("请输入管理员密码");
        return;
    }
    state.forceClose.submitting = true;
    try {
        const res: any = await copyTradePositionForceCloseOne({
            positionId: state.forceClose.positionId,
            username:   userStore.username,
            password:   state.forceClose.password,
        });
        if (res?.code === 0) {
            ElMessage.success("平仓指令已发送");
            state.forceClose.visible = false;
            load();
        } else {
            ElMessage.error(res?.message ?? "操作失败");
        }
    } catch {
        // 拦截器已弹出错误信息（code=500），此处不重复提示
    } finally {
        state.forceClose.submitting = false;
    }
}

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

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

onMounted(load);
</script>

<template>
    <div class="app-container">
        <!-- 面包屑返回 -->
        <div class="page-header">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>跟单管理</el-breadcrumb-item>
                <el-breadcrumb-item
                    class="breadcrumb-link"
                    @click="router.back()"
                >跟单持仓统计</el-breadcrumb-item>
                <el-breadcrumb-item>跟单明细</el-breadcrumb-item>
            </el-breadcrumb>
            <div class="page-title">
                交易员 <b>{{ traderMemberId }}</b> · {{ symbol }} 跟单明细
            </div>
        </div>

        <!-- 搜索栏 -->
        <div class="filter-bar">
            <el-input
                v-model="state.keyword"
                placeholder="跟单用户UID、邮箱搜索"
                clearable
                style="width: 260px"
                @keyup.enter="handleQuery"
            />
            <el-button type="primary" style="margin-left: 8px" @click="handleQuery">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
        </div>

        <!-- 数据表格 -->
        <el-table
            v-loading="state.loading"
            :data="state.rows"
            border
            style="width: 100%; margin-top: 12px"
            size="small"
        >
            <el-table-column label="序号" type="index" width="60" align="center" />
            <el-table-column label="跟单用户UID" prop="member_id" min-width="120" />
            <el-table-column label="交易对" min-width="170">
                <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 }}X</span>
                    </div>
                </template>
            </el-table-column>
<el-table-column :label="`持仓量（${coinName}）`" min-width="130">
                <template #default="{ row }">{{ fmtNum(row.coin_qty, 4) }}</template>
            </el-table-column>
            <el-table-column label="开仓价格（USDT）" min-width="140">
                <template #default="{ row }">{{ fmtNum(row.open_price, 2) }}</template>
            </el-table-column>
            <el-table-column label="未现盈亏（USDT）" min-width="140">
                <template #default="{ row }">
                    <span :class="pnlClass(row.unrealized_pnl)">{{ fmtNum(row.unrealized_pnl) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="收益率" min-width="100">
                <template #default="{ row }">
                    <span :class="pnlClass(row.profit_rate)">{{ fmtNum(row.profit_rate) }}%</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="100" fixed="right">
                <template #default="{ row }">
                    <el-button type="danger" size="small" @click="openForceClose(row)">市价平仓</el-button>
                </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="市价平仓确认"
            width="420px"
            :close-on-click-modal="false"
        >
            <p class="confirm-text">
                确认对跟单用户 <b>{{ state.forceClose.memberId }}</b> 的仓位执行市价平仓？此操作不可撤销。
            </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>
.page-header {
    margin-bottom: 16px;
}

.breadcrumb-link {
    cursor: pointer;
    color: #409eff;
}

.breadcrumb-link:hover {
    text-decoration: underline;
}

.page-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin-top: 8px;
}

.filter-bar {
    display: flex;
    align-items: center;
    background: #fff;
    padding: 12px 20px;
    border-radius: 4px;
}

.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>
