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

<script setup lang="ts">
import { onMounted, reactive, ref, toRefs } from "vue";
import { ElForm, ElTable, ElMessage } from "element-plus";
import { Search, Refresh } from "@element-plus/icons-vue";
import { useRoute } from "vue-router";
import { ethers } from "ethers";
import { TronWeb } from "tronweb";

import {
    perTradeAll,
    personalTradeInfo,
    auditNoPass,
    auditPass,
    chainApply,
    chainCallback,
} from "@/api/finance";
import {
    TradeQueryParam,
    TradeItem,
    TradeDetail,
    Coin,
} from "@/types/api/finance";
import { memberDetail } from "@/api/member/detail";
import { MemberInfo } from "@/types/api/member/detail";

const ERC20_ABI = [{
    name: "transfer", type: "function", stateMutability: "nonpayable",
    inputs: [
        { name: "recipient", type: "address" },
        { name: "amount",    type: "uint256" },
    ],
    outputs: [{ name: "", type: "bool" }],
}];

const GAS_WALLET_KEY = import.meta.env.VITE_WITHDRAW_GAS_KEY || "";

const queryFormRef = ref(ElForm);
const dataTableRef = ref(ElTable);

const state = reactive({
    id: 0 as any,
    loading: true,
    loading2: false,
    queryParams: {
        pageNo: 1,
        pageSize: 50,
        type: "",
        memberId: "",
        minMoney: "",
        maxMoney: "",
        minFee: "",
        maxFee: "",
        startTime: "",
        endTime: "",
        property: "",
        direction: "",
    } as TradeQueryParam,
    list: [] as TradeItem[],
    tradeDetail: {
        id: 0,
        memberId: 0,
        address: "",
        admin: "",
        totalAmount: 0,
        canAutoWithdraw: 0,
        coin: {
            name: "",
            nameCn: "",
            unit: "",
        } as Coin,
        fee: 0,
        arrivedAmount: 0,
        status: 0,
        isAuto: 0,
        transactionNumber: "",
        remark: "",
        dealTime: "",
        createTime: "",
    } as TradeDetail,
    memberInfo: {} as MemberInfo,
    total: 0,
    withdrawCoins: false,
    // 链上放币弹窗
    chainVisible: false,
    chainLoading: false,
    chainStep: 0,
    chainMsg: "",
});

const {
    id,
    loading,
    loading2,
    queryParams,
    list,
    total,
    chainVisible,
    chainLoading,
    chainStep,
    chainMsg,
} = toRefs(state);

const typeMap = {
    0: "充值",
    1: "提现",
    2: "转账",
    3: "币币交易",
    4: "法币买入",
    5: "法币卖出",
    6: "活动奖励",
    7: "推广奖励",
    8: "分红",
    9: "投票",
    10: "人工充值",
    11: "配对",
    12: "活动兑换",
    13: "C2C买入",
    14: "C2C卖出",
    15: "红包发出",
    16: "红包领取",
    17: "提现码提现",
    18: "提现码充值",
    19: "永续合约手续费",
    20: "永续合约盈利",
    21: "永续合约亏损",
    22: "期权合约失败",
    23: "期权合约手续费",
    24: "期权合约奖金",
    25: "合约返佣",
    26: "平级奖励",
    27: "平台手续费收入",
    28: "活动手续费",
    29: "活动盈利",
    30: "活动亏损",
    31: "活动返佣",
};

function handleQuery() {
    state.loading = true;
    personalTradeInfo(state.id)
        .then(({ data }) => {
            state.tradeDetail = data;
        })
        .then(() => {
            memberDetail({ id: state.tradeDetail.memberId })
                .then(({ data }) => {
                    state.memberInfo = data.member;
                })
                .catch(() => {
                    loading.value = false;
                });

            state.queryParams.memberId = state.tradeDetail.memberId;

            perTradeAll(state.queryParams)
                .then(({ data }) => {
                    state.list = data.content;
                    state.total = data.totalElements;
                    state.loading = false;
                })
                .catch(() => {
                    loading.value = false;
                });
        })
        .catch(() => {
            loading.value = false;
        });
}

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 ifPass = (pass: boolean) => {
    state.loading2 = true;
    const ids = [state.tradeDetail.id].join(",");
    if (pass) {
        auditPass({ ids: ids, remark: state.tradeDetail.remark })
            .then((res: any) => {
                if (!res.code) {
                    ElMessage.success(res.message);
                    handleQuery();
                } else {
                    ElMessage.error(res.message);
                }
                state.loading2 = false;
                state.withdrawCoins = false;
            })
            .catch(() => {
                state.loading2 = false;
            });
    } else {
        auditNoPass({ ids: ids, remark: state.tradeDetail.remark })
            .then((res: any) => {
                if (!res.code) {
                    ElMessage.success(res.message);
                    handleQuery();
                } else {
                    ElMessage.error(res.message);
                }
                state.loading2 = false;
                state.withdrawCoins = false;
            })
            .catch(() => {
                state.loading2 = false;
            });
    }
};

async function handleChainWithdraw() {
    if (!GAS_WALLET_KEY) {
        ElMessage.error("请先在 .env.local 中配置 VITE_WITHDRAW_GAS_KEY（Gas钱包私钥）");
        return;
    }
    state.chainStep = 0;
    state.chainMsg = "";
    state.chainVisible = true;
    state.chainLoading = true;

    try {
        // Step 1：准备转账
        state.chainStep = 1;
        state.chainMsg = "正在准备链上转账...";
        const applyRes: any = await chainApply(state.tradeDetail.id);
        const d = applyRes.data?.data ?? applyRes.data;
        const { toAddress, amount, decimals, contractAddress, rpcUrl, withdrawRecordId, chainType, signKey } = d;
        const gasKey = signKey || GAS_WALLET_KEY;

        // 金额转最小单位
        const [intPart, fracPart = ''] = amount.split('.');
        let rawAmount = intPart + fracPart.padEnd(decimals, '0').slice(0, decimals);
        rawAmount = rawAmount.replace(/^0+/, '') || '0';

        // ─── TRON / TRC20 转账 ───
        if (chainType === 'TRON') {
            state.chainStep = 2;
            state.chainMsg = "正在检查 TRON 钱包余额...";
            const tronWeb = new TronWeb({ fullHost: rpcUrl, privateKey: gasKey });
            const tronAddr = tronWeb.defaultAddress.base58;
            const trxBalance = await tronWeb.trx.getBalance(tronAddr);
            const trxAmount = Number(trxBalance) / 1_000_000;

            if (trxAmount < 10) {
                throw new Error(`TRON钱包余额不足\n地址: ${tronAddr}\n余额: ${trxAmount} TRX\n需充值至少 10 TRX`);
            }
            state.chainMsg = `TRON钱包: ${tronAddr}\n余额: ${trxAmount} TRX\n转出: ${amount} USDT\n正在提交交易...`;

            const trc20 = await tronWeb.contract().at(contractAddress);
            const txId = await trc20.transfer(toAddress, rawAmount).send({
                feeLimit: 30_000_000,
            });
            state.chainMsg = `交易已发送，等待确认...\ntxHash: ${txId}`;

            state.chainStep = 3;
            state.chainMsg = "交易已确认，正在通知后端...";
            await chainCallback(Number(withdrawRecordId ?? state.tradeDetail.id), txId);

            state.chainStep = 4;
            state.chainMsg = `链上放币成功！\ntxHash: ${txId}`;
            handleQuery();
            return;
        }

        // ─── EVM / ERC20 / BEP20 转账 ───
        state.chainStep = 2;
        state.chainMsg = "正在检查 Gas 钱包余额...";
        const provider = new ethers.providers.JsonRpcProvider(
            rpcUrl || import.meta.env.VITE_BSC_RPC_URL || "https://bsc-dataseed.binance.org"
        );
        const wallet = new ethers.Wallet(gasKey, provider);

        const balance = await provider.getBalance(wallet.address);
        const balanceBNB = ethers.utils.formatEther(balance);
        if (balance.lt(ethers.utils.parseEther("0.0005"))) {
            throw new Error(`Gas钱包余额不足\n地址: ${wallet.address}\n余额: ${balanceBNB} BNB\n需充值至少 0.0005 BNB`);
        }
        const parsedAmount = ethers.utils.parseUnits(amount, decimals);
        state.chainMsg = `Gas钱包: ${wallet.address}\n余额: ${balanceBNB} BNB\n转出: ${amount} USDT\n正在提交交易...`;

        const contract = new ethers.Contract(contractAddress, ERC20_ABI, wallet);

        // 直接发原始交易，绕过 ethers.js 的 estimateGas（BSC 节点经常预估失败）
        const data = contract.interface.encodeFunctionData("transfer", [
            toAddress,
            parsedAmount,
        ]);
        const tx = await wallet.sendTransaction({
            to: contractAddress,
            data: data,
            gasLimit: 200000,
            gasPrice: ethers.utils.parseUnits("1", "gwei"),
        });
        state.chainMsg = `交易已发送，等待确认...\ntxHash: ${tx.hash}`;

        // 用 provider 等待回执（即使失败也返回 receipt，不会直接抛异常）
        const receipt = await provider.waitForTransaction(tx.hash, 1);
        if (receipt.status === 0) {
            throw new Error(`链上交易失败 (status=0)\ntxHash: ${tx.hash}\n请在 BSCScan 上查看该交易详情`);
        }

        // Step 3：回调后端
        state.chainStep = 3;
        state.chainMsg = "交易已确认，正在通知后端...";
        const txHash = receipt.transactionHash;
        await chainCallback(Number(withdrawRecordId ?? state.tradeDetail.id), txHash);

        // Step 4：完成
        state.chainStep = 4;
        state.chainMsg = `链上放币成功！\ntxHash: ${txHash}`;
        handleQuery();
    } catch (e: any) {
        const msg = e?.reason || e?.message || "操作失败";
        state.chainMsg = `失败：${msg}`;
        ElMessage.error(msg);
    } finally {
        state.chainLoading = false;
    }
}

onMounted(() => {
    const route = useRoute();
    if (!Number(route.query.id)) {
        ElMessage.error("参数错误");
        return;
    }

    state.id = route.query.id;

    handleQuery();
});
</script>

<template>
    <div class="app-container">
        <el-row>
            <el-col :span="24">
                <el-steps
                    :active="
                        state.tradeDetail.status == 4
                            ? 1
                            : state.tradeDetail.status
                    "
                    finish-status="success"
                    :align-center="true"
                >
                    <el-step
                        :title="state.tradeDetail.status ? '已审核' : '待审核'"
                    />
                    <el-step
                        :title="
                            state.tradeDetail.status == 4
                                ? '用户取消'
                                : '转账中'
                        "
                    />
                    <el-step
                        :title="
                            state.tradeDetail.status == 2 ||
                            state.tradeDetail.status == 4
                                ? '交易失败'
                                : '交易成功'
                        "
                    />
                </el-steps>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="6">
                <p>用户名：{{ state.memberInfo.username }}</p>
                <p>提现币种：{{ state.tradeDetail.coin.unit }}</p>
            </el-col>
            <el-col :span="6">
                <p>真实姓名：{{ state.memberInfo.realName }}</p>
                <p>手续费：{{ state.tradeDetail.fee }}</p>
            </el-col>
            <el-col :span="6">
                <p>到账数量：{{ state.tradeDetail.arrivedAmount }}</p>
                <p>提现数量：{{ state.tradeDetail.totalAmount }}</p>
            </el-col>
            <el-col :span="6">
                <p>提现地址：{{ state.tradeDetail.address }}</p>
                <p>申请时间：{{ state.tradeDetail.createTime }}</p>
            </el-col>
        </el-row>
        <!-- 等待放币状态：链上放币 + 撤销提币 -->
        <el-row
            style="text-align: right"
            v-if="
                state.tradeDetail.status === 1 && state.tradeDetail.isAuto === 0
            "
        >
            <el-col :span="24">
                <p>
                    <el-popover
                        :visible="state.withdrawCoins"
                        placement="top"
                        :width="160"
                    >
                        <el-input
                            placeholder="请输入撤销原因"
                            size="small"
                            style="margin-bottom: 5px"
                            v-model="state.tradeDetail.remark"
                        />
                        <div style="text-align: right; margin: 0">
                            <el-button
                                size="small"
                                text
                                @click="state.withdrawCoins = false"
                                >关闭</el-button
                            >
                            <el-button
                                size="small"
                                type="primary"
                                @click="ifPass(false)"
                                >确认</el-button
                            >
                        </div>
                        <template #reference>
                            <el-button
                                type="danger"
                                size="default"
                                @click="state.withdrawCoins = true"
                                >撤销提币</el-button
                            >
                        </template>
                    </el-popover>

                    <el-button
                        type="warning"
                        size="default"
                        @click="handleChainWithdraw"
                        >链上放币</el-button
                    >
                </p>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="24">
                <el-card class="box-card">
                    <template #header>
                        <div class="card-header">
                            <span>交易记录</span>
                        </div>
                    </template>
                    <!-- 搜索表单 -->
                    <el-form
                        ref="queryFormRef"
                        :model="queryParams"
                        :inline="true"
                    >
                        <el-form-item prop="type">
                            <span>交易类型：</span>
                            <el-select
                                v-model="queryParams.type"
                                class="filter-item"
                                placeholder="请选择"
                                style="width: 100px"
                            >
                                <el-option
                                    v-for="(key, value) in typeMap"
                                    :key="key"
                                    :label="key"
                                    :value="value"
                                />
                            </el-select>
                        </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-form-item>
                    </el-form>

                    <!-- 数据表格 -->
                    <el-table
                        ref="dataTableRef"
                        v-loading="loading"
                        :data="list"
                        @sort-change="handleSortChange"
                        highlight-current-row
                        border
                        height="320px"
                    >
                        <el-table-column
                            label="会员ID"
                            prop="memberId"
                            align="center"
                            sortable="custom"
                        />
                        <el-table-column
                            label="交易类型"
                            prop="type"
                            min-width="100"
                            align="center"
                            sortable="custom"
                        >
                            <template #default="scope">
                                <span>{{ typeMap[scope.row.type] }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="交易金额"
                            prop="amount"
                            min-width="110"
                            align="center"
                            sortable="custom"
                        >
                            <template #default="scope">
                                <span
                                    >{{ scope.row.amount }}
                                    {{ scope.row.symbol }}</span
                                >
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="交易手续费"
                            prop="fee"
                            align="center"
                            sortable="custom"
                        />
                        <el-table-column
                            label="交易时间"
                            prop="createTime"
                            align="center"
                            sortable="custom"
                        />
                    </el-table>

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

                    <!-- 审核通过/不通过（待审核状态） -->
                    <p
                        v-if="!state.tradeDetail.status"
                        style="text-align: center"
                    >
                        <el-popover
                            :visible="state.withdrawCoins"
                            placement="top"
                            :width="160"
                        >
                            <el-input
                                placeholder="请输入撤销原因"
                                size="small"
                                style="margin-bottom: 5px"
                                v-model="state.tradeDetail.remark"
                            />
                            <div style="text-align: right; margin: 0">
                                <el-button
                                    size="small"
                                    text
                                    @click="state.withdrawCoins = false"
                                    >关闭</el-button
                                >
                                <el-button
                                    size="small"
                                    type="primary"
                                    @click="ifPass(false)"
                                    >确认</el-button
                                >
                            </div>
                            <template #reference>
                                <el-button
                                    type="danger"
                                    size="default"
                                    :loading="loading2"
                                    @click="state.withdrawCoins = true"
                                    >不通过</el-button
                                >
                            </template>
                        </el-popover>

                        <el-button
                            type="success"
                            size="default"
                            :loading="loading2"
                            @click="ifPass(true)"
                            >通过</el-button
                        >
                    </p>
                </el-card>
            </el-col>
        </el-row>

        <!-- 链上放币弹窗 -->
        <el-dialog
            v-model="chainVisible"
            title="链上放币"
            width="520px"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            :show-close="!chainLoading"
        >
            <div style="padding: 8px 0">
                <el-steps :active="chainStep - 1" align-center finish-status="success" style="margin-bottom:24px">
                    <el-step title="申请签名" />
                    <el-step title="链上提交" />
                    <el-step title="通知后端" />
                    <el-step title="完成" />
                </el-steps>
                <el-alert
                    v-if="chainMsg"
                    :title="chainMsg"
                    :type="chainStep === 4 ? 'success' : chainLoading ? 'info' : 'error'"
                    show-icon
                    :closable="false"
                    style="white-space:pre-wrap"
                />
            </div>
            <template #footer>
                <el-button v-if="!chainLoading" @click="state.chainVisible = false">关闭</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<style lang="scss" scoped></style>
