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

<script setup lang="ts">
import { onMounted, reactive, ref, toRefs, nextTick } from "vue";
import { ElForm, ElMessage } from "element-plus";
import { Search, Refresh, ArrowUp, ArrowDown, ArrowRight, Warning } from "@element-plus/icons-vue";
import { memberAsset, getBalanceByMember, verifyAdminPassword, transferToSpot } from "@/api/member/asset";
import { AssetQueryParam, AssetItem } from "@/types/api/member/asset";

const queryFormRef = ref(ElForm);

const state = reactive({
    loading: true,
    searchBox: {
        title: "展开搜索",
        expand: false,
    },
    queryParams: {
        pageNo: 1,
        pageSize: 15,
        account: "",
        walletAddress: "",
        unit: "USDT",
        minBalance: "",
        maxBalance: "",
        minFrozenBalance: "",
        maxFrozenBalance: "",
        minAllBalance: "",
        maxAllBalance: "",
    } as AssetQueryParam,
    assetList: [] as AssetItem[],
    total: 0,
    // 资产划转
    transferModalVisible: false,
    passwordModalVisible: false,
    transferLoading: false,
    passwordLoading: false,
    transferRow: null as AssetItem | null,
    followBalance: "0",
    spotBalance: "0",
    hasPosition: false,
    transferAmount: "",
    password: "",
});

const { loading, searchBox, queryParams, assetList, total, transferModalVisible, passwordModalVisible, transferLoading, passwordLoading, transferRow, followBalance, spotBalance, hasPosition, transferAmount, password } = toRefs(state);

function handleQuery() {
    state.loading = true;
    memberAsset(state.queryParams).then(({ data }) => {
        state.assetList = data.content;
        state.total = data.totalElements;
        state.loading = false;
    });
}

/** 格式化余额显示 */
function formatBalance(value: number | undefined | null): string {
    if (value === undefined || value === null || isNaN(value)) {
        return '0';
    }
    return String(value);
}

/** 格式化余额显示（用于弹窗，处理长数字） */
function formatBalanceDisplay(value: string | number | undefined | null): string {
    if (value === undefined || value === null || value === '') {
        return '0';
    }
    const numValue = typeof value === 'string' ? parseFloat(value) : value;
    if (isNaN(numValue)) {
        return '0';
    }
    // 如果数字很大或小数位很多，使用科学计数法或限制小数位
    const strValue = String(numValue);
    // 如果小数位超过8位，保留8位小数
    if (strValue.includes('.')) {
        const parts = strValue.split('.');
        if (parts[1] && parts[1].length > 8) {
            return numValue.toFixed(8).replace(/\.?0+$/, '');
        }
    }
    return strValue;
}

/**
 * 排序
 */
function handleSortChange(column: any) {
    var sortingType = column.order;
    state.queryParams.property = column.prop;
    if (sortingType === "ascending") {
        state.queryParams.direction = "1";
    } else if (sortingType === "descending") {
        state.queryParams.direction = "0";
    } else {
        state.queryParams.property = "id";
        state.queryParams.direction = "1";
    }
    handleQuery();
}

/**
 * 查询重置
 */
function resetQuery() {
    queryFormRef.value.resetFields();
    handleQuery();
}

/**
 * 展开/收起搜索
 */
const closeSearch = () => {
    state.searchBox.expand = !state.searchBox.expand;
    state.searchBox.title = !state.searchBox.expand ? "展开搜索" : "收起搜索";
};

/** 点击资产划转 */
function openTransferModal(row: AssetItem) {
    state.transferRow = row;
    state.transferAmount = "";
    state.transferModalVisible = true;
    state.transferLoading = true;
    getBalanceByMember(row.memberId)
        .then((res: any) => {
            const d = res.data || res;
            state.followBalance = String(d.followBalance ?? 0);
            state.spotBalance = String(d.spotBalance ?? 0);
            state.hasPosition = d.hasPosition ?? false;
            // 如果API返回了username，更新transferRow的username（确保响应式更新）
            if (d.username && state.transferRow) {
                // 使用对象展开确保响应式更新
                state.transferRow = {
                    ...state.transferRow,
                    username: d.username
                };
            }
        })
        .catch(() => {
            ElMessage.error("获取账户余额失败");
            state.transferModalVisible = false;
        })
        .finally(() => {
            state.transferLoading = false;
        });
}

/** 全部划转 */
function setMaxAmount() {
    state.transferAmount = state.followBalance;
}

/** 划转：关闭转账弹窗，打开密码验证弹窗 */
function confirmTransferAmount() {
    const amount = parseFloat(state.transferAmount);
    if (!state.transferAmount || isNaN(amount) || amount <= 0) {
        ElMessage.warning("请输入有效划转数量");
        return;
    }
    const maxAmount = parseFloat(state.followBalance);
    if (amount > maxAmount) {
        ElMessage.warning("划转数量不能超过跟单账户可用余额");
        return;
    }
    if (state.hasPosition) {
        ElMessage.warning("用户跟单账户有持仓时不支持划转");
        return;
    }
    // 确保transferRow存在
    if (!state.transferRow) {
        ElMessage.error("划转信息丢失，请重新操作");
        return;
    }
    // 先打开密码弹窗，再关闭转账弹窗，避免@close事件清空transferRow
    state.password = "";
    state.passwordModalVisible = true;
    // 使用nextTick确保密码弹窗先打开，避免close事件触发时清空transferRow
    nextTick(() => {
        state.transferModalVisible = false;
    });
}

/** 确认划转：先校验密码，再调用划转接口 */
function confirmTransferWithPassword() {
    if (!state.password) {
        ElMessage.warning("请输入操作密码");
        return;
    }
    if (!state.transferRow) {
        ElMessage.error("划转信息丢失，请重新操作");
        return;
    }
    state.passwordLoading = true;
    verifyAdminPassword(state.password)
        .then(() => {
            return transferToSpot({
                memberId: state.transferRow!.memberId,
                amount: state.transferAmount,
            });
        })
        .then(() => {
            ElMessage.success("划转成功");
            state.passwordModalVisible = false;
            state.password = "";
            state.transferRow = null;
            handleQuery();
        })
        .catch((err: any) => {
            // 响应拦截器已经显示了错误消息，这里不再重复显示
            // 只在控制台记录错误，方便调试
            console.error("划转失败:", err);
        })
        .finally(() => {
            state.passwordLoading = false;
        });
}

/** 关闭划转弹窗 */
function closeTransferModal() {
    state.transferModalVisible = false;
    // 如果即将打开密码弹窗，不要清空transferRow
    // 只有在真正关闭时才清空
    if (!state.passwordModalVisible) {
        state.transferRow = null;
    }
}

/** 关闭密码弹窗 */
function closePasswordModal() {
    state.passwordModalVisible = false;
    state.transferRow = null;
}

onMounted(() => {
    handleQuery();
});
</script>

<template>
    <div class="app-container">
        <!-- 搜索表单 -->
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item prop="account">
                <el-tooltip
                    content="请输入用户名、邮箱或姓名搜索"
                    placement="bottom"
                    effect="light"
                >
                    <el-input
                        v-model="queryParams.account"
                        placeholder="请输入用户名、邮箱或姓名搜索"
                        style="width: 300px"
                        clearable
                        @keyup.enter="handleQuery"
                    />
                </el-tooltip>
            </el-form-item>
            <el-form-item prop="walletAddress" v-show="searchBox.expand">
                <el-tooltip
                    content="请输入钱包地址搜索"
                    placement="bottom"
                    effect="light"
                >
                    <el-input
                        v-model="queryParams.walletAddress"
                        placeholder="请输入钱包地址搜索"
                        style="width: 300px"
                        clearable
                        @keyup.enter="handleQuery"
                    />
                </el-tooltip>
            </el-form-item>
            <el-form-item prop="unit" v-show="searchBox.expand">
                <el-tooltip
                    content="请输入币种搜索"
                    placement="bottom"
                    effect="light"
                >
                    <el-input
                        v-model="queryParams.unit"
                        placeholder="请输入币种搜索"
                        style="width: 300px"
                        clearable
                        @keyup.enter="handleQuery"
                    />
                </el-tooltip>
            </el-form-item>

            <el-form-item prop="minBalance" v-show="searchBox.expand">
                <el-col :span="11">
                    <el-tooltip
                        content="请输入可用币最低数搜索"
                        placement="bottom"
                        effect="light"
                    >
                        <el-input
                            v-model="queryParams.minBalance"
                            placeholder="可用币最低数搜索"
                            clearable
                            @keyup.enter="handleQuery"
                        />
                    </el-tooltip>
                </el-col>
                <el-col :span="2" align="center">~</el-col>
                <el-col :span="11">
                    <el-tooltip
                        content="请输入可用币最高数搜索"
                        placement="bottom"
                        effect="light"
                    >
                        <el-input
                            v-model="queryParams.maxBalance"
                            placeholder="可用币最高数搜索"
                            clearable
                            @keyup.enter="handleQuery"
                        />
                    </el-tooltip>
                </el-col>
            </el-form-item>
            <el-form-item prop="maxBalance" v-show="false"> </el-form-item>

            <el-form-item prop="minFrozenBalance" v-show="searchBox.expand">
                <el-col :span="11">
                    <el-tooltip
                        content="请输入冻结币最低数搜索"
                        placement="bottom"
                        effect="light"
                    >
                        <el-input
                            v-model="queryParams.minFrozenBalance"
                            placeholder="冻结币最低数搜索"
                            clearable
                            @keyup.enter="handleQuery"
                        />
                    </el-tooltip>
                </el-col>
                <el-col :span="2" align="center">~</el-col>
                <el-col :span="11">
                    <el-tooltip
                        content="请输入冻结币最高数搜索"
                        placement="bottom"
                        effect="light"
                    >
                        <el-input
                            v-model="queryParams.maxFrozenBalance"
                            placeholder="冻结币最高数搜索"
                            clearable
                            @keyup.enter="handleQuery"
                        />
                    </el-tooltip>
                </el-col>
            </el-form-item>
            <el-form-item prop="maxFrozenBalance" v-show="false">
            </el-form-item>

            <el-form-item prop="minAllBalance" v-show="searchBox.expand">
                <el-col :span="11">
                    <el-tooltip
                        content="请输入总币最低数搜索"
                        placement="bottom"
                        effect="light"
                    >
                        <el-input
                            v-model="queryParams.minAllBalance"
                            placeholder="总币最低数搜索"
                            clearable
                            @keyup.enter="handleQuery"
                        />
                    </el-tooltip>
                </el-col>
                <el-col :span="2" align="center">~</el-col>
                <el-col :span="11">
                    <el-tooltip
                        content="请输入总币最高数搜索"
                        placement="bottom"
                        effect="light"
                    >
                        <el-input
                            v-model="queryParams.maxAllBalance"
                            placeholder="总币最高数搜索"
                            clearable
                            @keyup.enter="handleQuery"
                        />
                    </el-tooltip>
                </el-col>
            </el-form-item>
            <el-form-item prop="maxAllBalance" v-show="false"> </el-form-item>

            <el-form-item>
                <el-button type="primary" :icon="Search" @click="handleQuery"
                    >搜索</el-button
                >
                <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
                <el-button
                    link
                    @click="closeSearch"
                    style="border: 0"
                    size="small"
                >
                    {{ searchBox.title }}
                    <template v-if="searchBox.expand"
                        ><el-icon class="el-icon--right"><ArrowUp /></el-icon
                    ></template>
                    <template v-else
                        ><el-icon class="el-icon--right"><ArrowDown /></el-icon
                    ></template>
                </el-button>
            </el-form-item>
        </el-form>

        <!-- 数据表格 -->
        <el-table
            ref="dataTableRef"
            v-loading="loading"
            :data="assetList"
            @sort-change="handleSortChange"
            highlight-current-row
            border
        >
            <el-table-column
                label="会员ID"
                prop="memberId"
                align="center"
                sortable="custom"
            />
            <el-table-column
                label="用户名"
                prop="username"
                min-width="160"
                align="center"
            />
            <!-- <el-table-column
                label="邮箱"
                prop="email"
                min-width="160"
                align="center"
            /> -->
            <!-- <el-table-column label="手机号" prop="mobilePhone" align="center" /> -->
            <el-table-column label="真实姓名" prop="realName" align="center" />
            <el-table-column
                label="币种名称"
                prop="unit"
                align="center"
                sortable="custom"
            />
            <!-- <el-table-column
                label="钱包地址"
                prop="address"
                align="center"
                sortable="custom"
            /> -->
            <!-- 资产账户可用、冻结、总币数 -->
            <el-table-column label="资产账户可用、冻结、总币数" align="center" min-width="200">
                <template #default="{ row }">
                    <span>{{ formatBalance(row.spotBalance || row.balance) }}、{{ formatBalance(row.spotFrozenBalance || row.frozenBalance) }}、{{ formatBalance(row.spotTotalBalance || row.allBalance) }}</span>
                </template>
            </el-table-column>
            <!-- 合约账户可用、冻结、总币数 -->
            <el-table-column label="合约账户可用、冻结、总币数" align="center" min-width="200">
                <template #default="{ row }">
                    <span>{{ formatBalance(row.contractBalance) }}、{{ formatBalance(row.contractFrozenBalance) }}、{{ formatBalance(row.contractTotalBalance) }}</span>
                </template>
            </el-table-column>
            <!-- 跟单账户可用、冻结、总币数 -->
            <el-table-column label="跟单账户可用、冻结、总币数" align="center" min-width="200">
                <template #default="{ row }">
                    <span>{{ formatBalance(row.followBalance) }}、{{ formatBalance(row.followFrozenBalance) }}、{{ formatBalance(row.followTotalBalance) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="120" fixed="right">
                <template #default="{ row }">
                    <!-- 资产划转为跟单账户→资产账户(USDT)，仅USDT币种显示 -->
                    <el-button
                        v-if="row.unit === 'USDT'"
                        type="primary"
                        size="small"
                        @click="openTransferModal(row)"
                    >
                        资产划转
                    </el-button>
                    <span v-else>-</span>
                </template>
            </el-table-column>
        </el-table>

        <!-- 资产划转弹窗（图1） -->
        <el-dialog
            v-model="transferModalVisible"
            title="资产划转"
            width="600px"
            :close-on-click-modal="false"
            @close="closeTransferModal"
        >
            <div v-loading="transferLoading" class="transfer-content">
                <div class="transfer-accounts">
                    <div class="account-item">
                        <div class="account-label">跟单账户</div>
                        <div class="account-balance">
                            <span class="balance-label">可用余额:</span>
                            <span class="balance-value">{{ formatBalanceDisplay(followBalance) }}</span>
                            <span class="balance-unit">USDT</span>
                        </div>
                    </div>
                    <div class="transfer-arrow">
                        <el-icon :size="24"><ArrowRight /></el-icon>
                    </div>
                    <div class="account-item">
                        <div class="account-label">资产账户</div>
                        <div class="account-balance">
                            <span class="balance-label">可用余额:</span>
                            <span class="balance-value">{{ formatBalanceDisplay(spotBalance) }}</span>
                            <span class="balance-unit">USDT</span>
                        </div>
                    </div>
                </div>
                <div class="transfer-input-section">
                    <div class="transfer-input-row">
                        <el-input
                            v-model="transferAmount"
                            placeholder="请输入划转数量"
                            type="number"
                            min="0"
                            class="transfer-input"
                        />
                        <span class="unit-tag">USDT</span>
                        <el-button type="primary" size="small" @click="setMaxAmount">全部</el-button>
                    </div>
                </div>
                <div class="transfer-tip">
                    <el-icon><Warning /></el-icon>
                    <span>用户跟单账户有持仓时不支持划转。</span>
                </div>
            </div>
            <template #footer>
                <el-button @click="closeTransferModal">取消</el-button>
                <el-button type="primary" @click="confirmTransferAmount">划转</el-button>
            </template>
        </el-dialog>

        <!-- 密码验证弹窗（图2） -->
        <el-dialog
            v-model="passwordModalVisible"
            title="密码验证"
            width="500px"
            :close-on-click-modal="false"
            @close="closePasswordModal"
        >
            <div class="password-content">
                <div class="password-tip">
                    将 <span class="username-highlight">{{ transferRow?.username || '' }}</span> 跟单账户 <span class="amount-highlight">{{ transferAmount }}</span> USDT 划转到资产账户。
                </div>
                <div class="password-input-section">
                    <el-input
                        v-model="password"
                        type="password"
                        placeholder="请输入操作密码"
                        show-password
                        clearable
                        size="large"
                    />
                </div>
            </div>
            <template #footer>
                <el-button @click="closePasswordModal">取消</el-button>
                <el-button type="primary" :loading="passwordLoading" @click="confirmTransferWithPassword">
                    确认划转
                </el-button>
            </template>
        </el-dialog>

        <!-- 分页工具条 -->
        <pagination
            v-if="total > 0"
            :total="total"
            v-model:page="queryParams.pageNo"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
        />
    </div>
</template>

<style lang="scss" scoped>
.dropdown-text {
    margin-left: 12px;
    height: 24px;
    line-height: 24px;
    font-size: 12px;
}

.transfer-content {
    min-height: 180px;
    padding: 8px 0;
}

.transfer-accounts {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 24px;
    padding: 20px 24px;
    background: #f5f7fa;
    border-radius: 8px;
    gap: 16px;
}

.account-item {
    flex: 1;
    text-align: center;
    min-width: 0; // 允许内容收缩
    max-width: 45%; // 限制最大宽度，避免过度拉伸

    .account-label {
        font-size: 14px;
        color: #606266;
        margin-bottom: 12px;
        font-weight: 500;
    }

    .account-balance {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 4px;
        
        .balance-label {
            font-size: 12px;
            color: #909399;
        }
        
        .balance-value {
            font-size: 18px;
            font-weight: 600;
            color: #303133;
            word-break: break-all;
            line-height: 1.4;
            max-width: 100%;
            overflow-wrap: break-word;
        }
        
        .balance-unit {
            font-size: 14px;
            color: #606266;
        }
    }
}

.transfer-arrow {
    flex-shrink: 0;
    color: #409eff;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 8px;
}

.transfer-input-section {
    margin-bottom: 16px;
}

.transfer-input-row {
    display: flex;
    align-items: center;
    gap: 12px;
    width: 100%;

    .transfer-input {
        flex: 1;
        min-width: 0; // 允许收缩
    }

    .unit-tag {
        font-size: 14px;
        color: #606266;
        font-weight: 500;
        white-space: nowrap;
        flex-shrink: 0;
    }
}

.transfer-tip {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 12px;
    color: #e6a23c;
    padding: 8px 12px;
    background: #fdf6ec;
    border-radius: 4px;
    
    .el-icon {
        font-size: 14px;
    }
}

.password-content {
    padding: 8px 0;
    
    .password-tip {
        margin-bottom: 24px;
        padding: 16px;
        background: #f5f7fa;
        border-radius: 8px;
        font-size: 14px;
        color: #606266;
        line-height: 1.6;
        text-align: center;

        .username-highlight {
            color: #409eff;
            font-weight: 600;
        }

        .amount-highlight {
            color: #409eff;
            font-weight: 600;
        }
    }
    
    .password-input-section {
        width: 100%;
    }
}
</style>
