package com.it.rattan.monisuo.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.it.rattan.monisuo.entity.AccountFund;
import com.it.rattan.monisuo.entity.ColdWallet;
import com.it.rattan.monisuo.entity.OrderFund;
import com.it.rattan.monisuo.entity.User;
import com.it.rattan.monisuo.mapper.AccountFundMapper;
import com.it.rattan.monisuo.mapper.OrderFundMapper;
import com.it.rattan.monisuo.mapper.UserMapper;
import com.it.rattan.monisuo.util.OrderNoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 充提服务
 *
 * 状态定义:
 * 充值: 1=待付款, 2=待确认, 3=已完成, 4=已驳回, 5=已取消
 * 提现: 1=待审批, 2=已完成, 3=已驳回, 4=已取消
 *
 * 审批参数说明:
 * status=2 表示审批通过（充值订单最终状态为3，提现订单最终状态为2）
 * status=3 表示审批驳回（充值订单最终状态为4，提现订单最终状态为3）
 */
@Service
public class FundService {

    @Autowired
    private OrderFundMapper orderFundMapper;

    @Autowired
    private AccountFundMapper accountFundMapper;

    @Autowired
    private AssetService assetService;

    @Autowired
    private ColdWalletService coldWalletService;

    @Autowired
    private UserMapper userMapper;

    /**
     * 申请充值 - 关联默认冷钱包
     */
    @Transactional
    public Map<String, Object> deposit(Long userId, BigDecimal amount, String remark) {
        if (amount.compareTo(BigDecimal.ZERO) <= 0) {
            throw new RuntimeException("充值金额必须大于0");
        }

        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 获取默认冷钱包
        ColdWallet wallet = coldWalletService.getDefaultWallet();
        if (wallet == null) {
            throw new RuntimeException("系统暂未配置充值地址");
        }

        OrderFund order = new OrderFund();
        order.setOrderNo(OrderNoUtil.fundOrderNo());
        order.setUserId(userId);
        order.setUsername(user.getUsername());
        order.setType(1); // 充值
        order.setAmount(amount);
        order.setStatus(1); // 待付款
        order.setWalletId(wallet.getId());
        order.setWalletAddress(wallet.getAddress());
        order.setRemark(remark);
        order.setCreateTime(LocalDateTime.now());
        orderFundMapper.insert(order);

        Map<String, Object> result = new HashMap<>();
        result.put("orderNo", order.getOrderNo());
        result.put("amount", amount);
        result.put("status", order.getStatus());
        result.put("walletAddress", wallet.getAddress());
        result.put("walletNetwork", wallet.getNetwork());
        return result;
    }

    /**
     * 用户确认已打款
     */
    @Transactional
    public void confirmPay(Long userId, String orderNo) {
        LambdaQueryWrapper<OrderFund> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderFund::getUserId, userId)
               .eq(OrderFund::getOrderNo, orderNo)
               .eq(OrderFund::getType, 1) // 仅充值订单
               .eq(OrderFund::getStatus, 1); // 仅待付款可确认

        OrderFund order = orderFundMapper.selectOne(wrapper);
        if (order == null) {
            throw new RuntimeException("订单不存在或状态不可操作");
        }

        order.setStatus(2); // 待确认
        order.setPayTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        orderFundMapper.updateById(order);
    }

    /**
     * 申请提现 - 冻结余额
     */
    @Transactional
    public Map<String, Object> withdraw(Long userId, BigDecimal amount, String withdrawAddress,
                                         String withdrawContact, String remark) {
        if (amount.compareTo(BigDecimal.ZERO) <= 0) {
            throw new RuntimeException("提现金额必须大于0");
        }

        if (withdrawAddress == null || withdrawAddress.isEmpty()) {
            throw new RuntimeException("请填写提现地址");
        }

        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 检查并冻结余额
        AccountFund fund = assetService.getOrCreateFundAccount(userId);
        if (fund.getBalance().compareTo(amount) < 0) {
            throw new RuntimeException("资金账户余额不足");
        }

        // 冻结余额 - 使用 LambdaUpdateWrapper 显式更新
        BigDecimal newBalance = fund.getBalance().subtract(amount);
        BigDecimal newFrozen = fund.getFrozen() != null ? fund.getFrozen().add(amount) : amount;
        LocalDateTime updateTime = LocalDateTime.now();

        System.out.println("[提现申请] 冻结余额: 用户ID=" + userId +
                ", 原余额=" + fund.getBalance() + ", 新余额=" + newBalance +
                ", 原冻结=" + fund.getFrozen() + ", 新冻结=" + newFrozen);

        LambdaUpdateWrapper<AccountFund> fundUpdateWrapper = new LambdaUpdateWrapper<>();
        fundUpdateWrapper.eq(AccountFund::getId, fund.getId())
                .set(AccountFund::getBalance, newBalance)
                .set(AccountFund::getFrozen, newFrozen)
                .set(AccountFund::getUpdateTime, updateTime);
        int fundUpdateResult = accountFundMapper.update(null, fundUpdateWrapper);

        if (fundUpdateResult <= 0) {
            System.err.println("[提现申请] 资金账户冻结失败!");
            throw new RuntimeException("资金账户冻结失败");
        }
        System.out.println("[提现申请] 资金账户冻结成功，更新行数: " + fundUpdateResult);

        // 更新本地对象状态
        fund.setBalance(newBalance);
        fund.setFrozen(newFrozen);
        fund.setUpdateTime(updateTime);

        // 创建订单
        OrderFund order = new OrderFund();
        order.setOrderNo(OrderNoUtil.fundOrderNo());
        order.setUserId(userId);
        order.setUsername(user.getUsername());
        order.setType(2); // 提现
        order.setAmount(amount);
        order.setStatus(1); // 待审批
        order.setWalletAddress(withdrawAddress);
        order.setWithdrawContact(withdrawContact);
        order.setRemark(remark);
        order.setCreateTime(LocalDateTime.now());
        orderFundMapper.insert(order);

        Map<String, Object> result = new HashMap<>();
        result.put("orderNo", order.getOrderNo());
        result.put("amount", amount);
        result.put("status", order.getStatus());
        return result;
    }

    /**
     * 取消订单 - 仅充值待付款状态可取消
     */
    @Transactional
    public void cancel(Long userId, String orderNo) {
        LambdaQueryWrapper<OrderFund> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderFund::getUserId, userId)
               .eq(OrderFund::getOrderNo, orderNo);

        OrderFund order = orderFundMapper.selectOne(wrapper);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }

        // 充值订单仅待付款可取消
        if (order.getType() == 1 && order.getStatus() != 1) {
            throw new RuntimeException("当前状态不可取消");
        }

        // 提现订单仅待审批可取消，需要解冻余额
        if (order.getType() == 2) {
            if (order.getStatus() != 1) {
                throw new RuntimeException("当前状态不可取消");
            }
            // 解冻余额 - 使用 LambdaUpdateWrapper 显式更新
            AccountFund fund = assetService.getOrCreateFundAccount(userId);
            BigDecimal newBalance = fund.getBalance().add(order.getAmount());
            BigDecimal newFrozen = fund.getFrozen().subtract(order.getAmount());
            LocalDateTime updateTime = LocalDateTime.now();

            System.out.println("[取消订单] 解冻余额: 用户ID=" + userId +
                    ", 原余额=" + fund.getBalance() + ", 新余额=" + newBalance +
                    ", 原冻结=" + fund.getFrozen() + ", 新冻结=" + newFrozen);

            LambdaUpdateWrapper<AccountFund> fundUpdateWrapper = new LambdaUpdateWrapper<>();
            fundUpdateWrapper.eq(AccountFund::getId, fund.getId())
                    .set(AccountFund::getBalance, newBalance)
                    .set(AccountFund::getFrozen, newFrozen)
                    .set(AccountFund::getUpdateTime, updateTime);
            int fundUpdateResult = accountFundMapper.update(null, fundUpdateWrapper);

            if (fundUpdateResult <= 0) {
                System.err.println("[取消订单] 资金账户解冻失败!");
                throw new RuntimeException("资金账户解冻失败");
            }
            System.out.println("[取消订单] 资金账户解冻成功，更新行数: " + fundUpdateResult);
        }

        order.setStatus(5); // 已取消
        order.setUpdateTime(LocalDateTime.now());
        orderFundMapper.updateById(order);
    }

    /**
     * 获取充提记录
     */
    public IPage<OrderFund> getOrders(Long userId, Integer type, int pageNum, int pageSize) {
        LambdaQueryWrapper<OrderFund> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderFund::getUserId, userId);
        if (type != null && type > 0) {
            wrapper.eq(OrderFund::getType, type);
        }
        wrapper.orderByDesc(OrderFund::getCreateTime);

        Page<OrderFund> page = new Page<>(pageNum, pageSize);
        return orderFundMapper.selectPage(page, wrapper);
    }

    /**
     * 获取待审批订单数量
     */
    public int getPendingCount() {
        // 充值待确认 + 提现待审批
        LambdaQueryWrapper<OrderFund> wrapper = new LambdaQueryWrapper<>();
        wrapper.and(w -> w.eq(OrderFund::getType, 1).eq(OrderFund::getStatus, 2))
               .or(w -> w.eq(OrderFund::getType, 2).eq(OrderFund::getStatus, 1));
        return Math.toIntExact(orderFundMapper.selectCount(wrapper));
    }

    /**
     * 管理员审批
     * 充值: 仅待确认(status=2)可审批
     * 提现: 仅待审批(status=1)可审批
     *
     * @param status 审批结果: 2=通过, 3=驳回
     */
    @Transactional
    public void approve(Long adminId, String adminName, String orderNo, Integer status,
                        String rejectReason, String adminRemark) {
        System.out.println("\n[FundService.approve] 开始处理审批");
        System.out.println("[FundService.approve] 参数: orderNo=" + orderNo + ", status=" + status + 
                          ", adminId=" + adminId + ", adminName=" + adminName);

        // 查询订单
        System.out.println("[FundService.approve] 步骤1: 查询订单...");
        OrderFund order = orderFundMapper.selectOne(
                new LambdaQueryWrapper<OrderFund>().eq(OrderFund::getOrderNo, orderNo));

        if (order == null) {
            System.err.println("[FundService.approve] 订单不存在: " + orderNo);
            throw new RuntimeException("订单不存在");
        }

        System.out.println("[FundService.approve] 订单查询成功:");
        System.out.println("  - 订单ID: " + order.getId());
        System.out.println("  - 订单号: " + order.getOrderNo());
        System.out.println("  - 用户ID: " + order.getUserId());
        System.out.println("  - 用户名: " + order.getUsername());
        System.out.println("  - 订单类型: " + (order.getType() == 1 ? "充值" : "提现"));
        System.out.println("  - 当前状态: " + order.getStatus());
        System.out.println("  - 金额: " + order.getAmount());

        // 充值审批: 仅待确认可审批
        if (order.getType() == 1 && order.getStatus() != 2) {
            System.err.println("[FundService.approve] 充值订单状态不正确，当前状态: " + order.getStatus() + " (需要状态2)");
            throw new RuntimeException("该充值订单不可审批，等待用户确认打款");
        }

        // 提现审批: 仅待审批可审批
        if (order.getType() == 2 && order.getStatus() != 1) {
            System.err.println("[FundService.approve] 提现订单状态不正确，当前状态: " + order.getStatus() + " (需要状态1)");
            throw new RuntimeException("该提现订单已处理");
        }

        // 查询资金账户
        System.out.println("[FundService.approve] 步骤2: 查询资金账户...");
        AccountFund fund = assetService.getOrCreateFundAccount(order.getUserId());
        System.out.println("[FundService.approve] 资金账户查询成功:");
        System.out.println("  - 账户ID: " + fund.getId());
        System.out.println("  - 用户ID: " + fund.getUserId());
        System.out.println("  - 余额: " + fund.getBalance());
        System.out.println("  - 冻结: " + fund.getFrozen());

        // 根据订单类型和审批结果，确定最终的订单状态
        Integer finalStatus;
        if (order.getType() == 1) {
            // 充值订单: 2=通过->3(已完成), 3=驳回->4(已驳回)
            finalStatus = (status == 2) ? 3 : 4;
        } else {
            // 提现订单: 2=通过->2(已完成), 3=驳回->3(已驳回)
            finalStatus = status;
        }
        System.out.println("[FundService.approve] 步骤3: 确定最终状态: " + finalStatus + 
                          " (审批" + (status == 2 ? "通过" : "驳回") + ")");

        if (status == 2) {
            // 审批通过
            System.out.println("[FundService.approve] 步骤4: 处理审批通过逻辑...");

            if (order.getType() == 1) {
                // 充值通过：增加余额 - 使用 LambdaUpdateWrapper 显式更新
                System.out.println("[FundService.approve] 处理充值通过...");

                // 处理可能的 null 值
                BigDecimal currentBalance = fund.getBalance();
                BigDecimal currentTotalDeposit = fund.getTotalDeposit();
                if (currentBalance == null) {
                    currentBalance = BigDecimal.ZERO;
                    System.out.println("  - 警告: 账户余额为 null，已设置为 0");
                }
                if (currentTotalDeposit == null) {
                    currentTotalDeposit = BigDecimal.ZERO;
                    System.out.println("  - 警告: 累计充值为 null，已设置为 0");
                }

                BigDecimal balanceBefore = currentBalance;
                BigDecimal totalDepositBefore = currentTotalDeposit;
                System.out.println("  - 审批前余额: " + balanceBefore);
                System.out.println("  - 审批前累计充值: " + totalDepositBefore);
                System.out.println("  - 账户ID: " + fund.getId());
                System.out.println("  - 用户ID: " + fund.getUserId());

                BigDecimal newBalance = currentBalance.add(order.getAmount());
                BigDecimal newTotalDeposit = currentTotalDeposit.add(order.getAmount());
                LocalDateTime updateTime = LocalDateTime.now();

                System.out.println("  - 准备更新账户余额: " + newBalance);
                System.out.println("  - 准备更新累计充值: " + newTotalDeposit);

                LambdaUpdateWrapper<AccountFund> fundUpdateWrapper = new LambdaUpdateWrapper<>();
                fundUpdateWrapper.eq(AccountFund::getId, fund.getId())
                        .set(AccountFund::getBalance, newBalance)
                        .set(AccountFund::getTotalDeposit, newTotalDeposit)
                        .set(AccountFund::getUpdateTime, updateTime);

                System.out.println("  - 执行 SQL UPDATE (使用 LambdaUpdateWrapper)...");
                int updateResult = accountFundMapper.update(null, fundUpdateWrapper);
                System.out.println("  - 账户更新结果: " + updateResult + " (1=成功, 0=失败)");

                if (updateResult <= 0) {
                    System.err.println("[FundService.approve] 充值审批更新账户余额失败!");
                    throw new RuntimeException("充值审批更新账户余额失败");
                }

                // 验证更新结果 - 使用新的查询确保从数据库读取
                AccountFund verifyFund = accountFundMapper.selectById(fund.getId());
                System.out.println("  - 验证更新后余额: " + verifyFund.getBalance());
                System.out.println("  - 验证更新后累计充值: " + verifyFund.getTotalDeposit());

                if (verifyFund.getBalance() == null || !verifyFund.getBalance().equals(newBalance)) {
                    System.err.println("[FundService.approve] 严重错误: 账户余额更新验证失败!");
                    System.err.println("  - 期望余额: " + newBalance);
                    System.err.println("  - 实际余额: " + verifyFund.getBalance());
                    throw new RuntimeException("账户余额更新验证失败");
                }
                System.out.println("  - 余额验证通过 ✓");

                // 更新本地对象状态
                fund.setBalance(newBalance);
                fund.setTotalDeposit(newTotalDeposit);
                fund.setUpdateTime(updateTime);

                // 记录流水
                System.out.println("[FundService.approve] 创建资金流水记录...");
                assetService.createFlow(order.getUserId(), 1, order.getAmount(),
                        balanceBefore, newBalance, "USDT", orderNo, "充值");
                System.out.println("  - 流水记录创建成功");

                System.out.println("[充值审批成功] 订单号: " + orderNo + ", 用户ID: " + order.getUserId() +
                        ", 充值金额: " + order.getAmount() + " USDT");
            } else {
                // 提现通过：从冻结转为扣除，更新累计提现 - 使用 LambdaUpdateWrapper 显式更新
                System.out.println("[FundService.approve] 处理提现通过...");
                if (fund.getFrozen().compareTo(order.getAmount()) < 0) {
                    System.err.println("[FundService.approve] 冻结金额不足: 冻结=" + fund.getFrozen() +
                                     ", 需要=" + order.getAmount());
                    throw new RuntimeException("冻结金额不足");
                }

                BigDecimal balanceBefore = fund.getBalance();
                BigDecimal frozenBefore = fund.getFrozen();
                BigDecimal totalWithdrawBefore = fund.getTotalWithdraw();
                System.out.println("  - 审批前余额: " + balanceBefore);
                System.out.println("  - 审批前冻结: " + frozenBefore);
                System.out.println("  - 审批前累计提现: " + totalWithdrawBefore);

                BigDecimal newFrozen = fund.getFrozen().subtract(order.getAmount());
                BigDecimal newTotalWithdraw = fund.getTotalWithdraw().add(order.getAmount());
                LocalDateTime updateTime = LocalDateTime.now();

                System.out.println("  - 准备更新账户冻结: " + newFrozen);
                System.out.println("  - 准备更新累计提现: " + newTotalWithdraw);

                LambdaUpdateWrapper<AccountFund> fundUpdateWrapper = new LambdaUpdateWrapper<>();
                fundUpdateWrapper.eq(AccountFund::getId, fund.getId())
                        .set(AccountFund::getFrozen, newFrozen)
                        .set(AccountFund::getTotalWithdraw, newTotalWithdraw)
                        .set(AccountFund::getUpdateTime, updateTime);

                System.out.println("  - 执行 SQL UPDATE (使用 LambdaUpdateWrapper)...");
                int updateResult = accountFundMapper.update(null, fundUpdateWrapper);
                System.out.println("  - 账户更新结果: " + updateResult + " (1=成功, 0=失败)");

                if (updateResult <= 0) {
                    System.err.println("[FundService.approve] 提现审批更新账户冻结失败!");
                    throw new RuntimeException("提现审批更新账户冻结失败");
                }

                // 验证更新结果
                AccountFund verifyFund = accountFundMapper.selectById(fund.getId());
                System.out.println("  - 验证更新后冻结: " + verifyFund.getFrozen());
                System.out.println("  - 验证更新后累计提现: " + verifyFund.getTotalWithdraw());

                // 更新本地对象状态
                fund.setFrozen(newFrozen);
                fund.setTotalWithdraw(newTotalWithdraw);
                fund.setUpdateTime(updateTime);

                // 记录流水 (负数表示支出)
                System.out.println("[FundService.approve] 创建资金流水记录...");
                assetService.createFlow(order.getUserId(), 2, order.getAmount().negate(),
                        balanceBefore, balanceBefore, "USDT", orderNo, "提现");
                System.out.println("  - 流水记录创建成功");

                System.out.println("[提现审批成功] 订单号: " + orderNo + ", 用户ID: " + order.getUserId() +
                        ", 提现金额: " + order.getAmount() + " USDT");
            }

            order.setConfirmTime(LocalDateTime.now());

        } else if (status == 3) {
            // 审批驳回
            System.out.println("[FundService.approve] 步骤4: 处理审批驳回逻辑...");
            
            if (rejectReason == null || rejectReason.isEmpty()) {
                System.err.println("[FundService.approve] 驳回原因为空");
                throw new RuntimeException("请填写驳回原因");
            }
            order.setRejectReason(rejectReason);
            System.out.println("[FundService.approve] 驳回原因: " + rejectReason);

            if (order.getType() == 2) {
                // 提现驳回：解冻金额退还 - 使用 LambdaUpdateWrapper 显式更新
                System.out.println("[FundService.approve] 处理提现驳回，解冻金额退还...");
                BigDecimal balanceBefore = fund.getBalance();
                BigDecimal frozenBefore = fund.getFrozen();
                System.out.println("  - 驳回前余额: " + balanceBefore);
                System.out.println("  - 驳回前冻结: " + frozenBefore);

                BigDecimal newBalance = fund.getBalance().add(order.getAmount());
                BigDecimal newFrozen = fund.getFrozen().subtract(order.getAmount());
                LocalDateTime updateTime = LocalDateTime.now();

                System.out.println("  - 准备更新账户: 新余额=" + newBalance + ", 新冻结=" + newFrozen);

                LambdaUpdateWrapper<AccountFund> fundUpdateWrapper = new LambdaUpdateWrapper<>();
                fundUpdateWrapper.eq(AccountFund::getId, fund.getId())
                        .set(AccountFund::getBalance, newBalance)
                        .set(AccountFund::getFrozen, newFrozen)
                        .set(AccountFund::getUpdateTime, updateTime);

                System.out.println("  - 执行 SQL UPDATE (使用 LambdaUpdateWrapper)...");
                int updateResult = accountFundMapper.update(null, fundUpdateWrapper);
                System.out.println("  - 账户更新结果: " + updateResult + " (1=成功, 0=失败)");

                if (updateResult <= 0) {
                    System.err.println("[FundService.approve] 提现驳回更新账户失败!");
                    throw new RuntimeException("提现驳回更新账户失败");
                }

                // 验证更新结果
                AccountFund verifyFund = accountFundMapper.selectById(fund.getId());
                System.out.println("  - 验证更新后余额: " + verifyFund.getBalance());
                System.out.println("  - 验证更新后冻结: " + verifyFund.getFrozen());

                // 更新本地对象状态
                fund.setBalance(newBalance);
                fund.setFrozen(newFrozen);
                fund.setUpdateTime(updateTime);

                // 记录流水
                System.out.println("[FundService.approve] 创建资金流水记录...");
                assetService.createFlow(order.getUserId(), 2, order.getAmount(),
                        balanceBefore, newBalance, "USDT", orderNo, "提现驳回退还");
                System.out.println("  - 流水记录创建成功");

                System.out.println("[提现驳回成功] 订单号: " + orderNo + ", 用户ID: " + order.getUserId() +
                        ", 退还金额: " + order.getAmount() + " USDT");
            } else {
                System.out.println("[充值驳回成功] 订单号: " + orderNo + ", 用户ID: " + order.getUserId() +
                        ", 充值金额: " + order.getAmount() + " USDT, 驳回原因: " + rejectReason);
            }
        }

        // 更新订单状态 - 使用 LambdaUpdateWrapper 强制更新所有字段
        System.out.println("[FundService.approve] 步骤5: 更新订单状态...");
        System.out.println("  - 当前状态: " + order.getStatus());
        System.out.println("  - 目标状态: " + finalStatus);

        LocalDateTime now = LocalDateTime.now();

        // 使用 LambdaUpdateWrapper 明确指定要更新的字段
        LambdaUpdateWrapper<OrderFund> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(OrderFund::getId, order.getId())
                .set(OrderFund::getStatus, finalStatus)
                .set(OrderFund::getApproveAdminId, adminId)
                .set(OrderFund::getApproveAdminName, adminName)
                .set(OrderFund::getApproveTime, now)
                .set(OrderFund::getConfirmTime, order.getConfirmTime())
                .set(OrderFund::getRejectReason, order.getRejectReason())
                .set(OrderFund::getAdminRemark, adminRemark)
                .set(OrderFund::getUpdateTime, now);

        System.out.println("  - 准备执行数据库更新 (使用 LambdaUpdateWrapper)...");
        System.out.println("  - UPDATE SQL 将更新: status=" + finalStatus + ", approveAdminId=" + adminId);

        int orderUpdateResult = orderFundMapper.update(null, updateWrapper);
        System.out.println("  - 订单更新结果: " + orderUpdateResult + " (1=成功, 0=失败)");

        // 验证更新是否成功 - 使用新的查询确保从数据库读取
        if (orderUpdateResult > 0) {
            System.out.println("[FundService.approve] 步骤6: 验证更新结果...");

            // 清除可能的缓存，强制从数据库读取
            OrderFund verifyOrder = orderFundMapper.selectOne(
                    new LambdaQueryWrapper<OrderFund>()
                            .eq(OrderFund::getId, order.getId())
                            .select(OrderFund::getId, OrderFund::getOrderNo, OrderFund::getStatus,
                                    OrderFund::getApproveAdminId, OrderFund::getApproveTime));

            System.out.println("  - 验证查询结果: ID=" + verifyOrder.getId() +
                             ", 订单号=" + verifyOrder.getOrderNo() +
                             ", 状态=" + verifyOrder.getStatus());

            if (!verifyOrder.getStatus().equals(finalStatus)) {
                System.err.println("[FundService.approve] 严重错误: 订单状态更新后验证失败!");
                System.err.println("  - 期望状态: " + finalStatus);
                System.err.println("  - 实际状态: " + verifyOrder.getStatus());
                throw new RuntimeException("订单状态更新失败，请检查数据库配置");
            } else {
                System.out.println("  - 状态验证通过 ✓");
            }
        } else {
            System.err.println("[FundService.approve] 订单更新失败! update返回: " + orderUpdateResult);
            throw new RuntimeException("订单更新失败");
        }

        // 最终验证：确保账户余额正确更新（仅在审批通过时）
        if (status == 2) {
            System.out.println("[FundService.approve] 步骤7: 最终验证账户余额...");
            AccountFund finalVerifyFund = accountFundMapper.selectById(fund.getId());
            System.out.println("  - 最终账户余额: " + finalVerifyFund.getBalance());
            System.out.println("  - 最终累计充值: " + finalVerifyFund.getTotalDeposit());

            if (order.getType() == 1) {
                // 充值订单：验证余额是否正确增加
                BigDecimal expectedBalance = fund.getBalance();
                if (finalVerifyFund.getBalance() == null ||
                    finalVerifyFund.getBalance().compareTo(expectedBalance) != 0) {
                    System.err.println("[FundService.approve] 严重错误: 最终验证发现账户余额不一致!");
                    System.err.println("  - 期望余额: " + expectedBalance);
                    System.err.println("  - 实际余额: " + finalVerifyFund.getBalance());
                    throw new RuntimeException("账户余额最终验证失败，数据可能不一致");
                }
                System.out.println("  - 账户余额最终验证通过 ✓");
            }
        }

        System.out.println("[审批完成] 订单号: " + orderNo + ", 订单类型: " + (order.getType() == 1 ? "充值" : "提现") +
                ", 审批结果: " + (status == 2 ? "通过" : "驳回") + ", 最终状态: " + finalStatus +
                ", 审批人: " + adminName);
        System.out.println("[FundService.approve] 处理完成\n");
    }

    /**
     * 获取待审批订单列表
     * 充值待确认(status=2) + 提现待审批(status=1)
     */
    public IPage<OrderFund> getPendingOrders(Integer type, Integer status, int pageNum, int pageSize) {
        LambdaQueryWrapper<OrderFund> wrapper = new LambdaQueryWrapper<>();

        if (type != null && type > 0) {
            // 指定类型
            wrapper.eq(OrderFund::getType, type);
            if (type == 1) {
                // 充值：待确认
                wrapper.eq(OrderFund::getStatus, status != null ? status : 2);
            } else {
                // 提现：待审批
                wrapper.eq(OrderFund::getStatus, status != null ? status : 1);
            }
        } else {
            // 不指定类型：充值待确认 + 提现待审批
            wrapper.and(w -> w.eq(OrderFund::getType, 1).eq(OrderFund::getStatus, 2))
                   .or(w -> w.eq(OrderFund::getType, 2).eq(OrderFund::getStatus, 1));
        }

        wrapper.orderByAsc(OrderFund::getCreateTime);

        Page<OrderFund> page = new Page<>(pageNum, pageSize);
        return orderFundMapper.selectPage(page, wrapper);
    }

    /**
     * 获取所有充提订单(管理员)
     */
    public IPage<OrderFund> getAllOrders(Integer type, Integer status, int pageNum, int pageSize) {
        LambdaQueryWrapper<OrderFund> wrapper = new LambdaQueryWrapper<>();
        if (type != null && type > 0) {
            wrapper.eq(OrderFund::getType, type);
        }
        if (status != null && status > 0) {
            wrapper.eq(OrderFund::getStatus, status);
        }
        wrapper.orderByDesc(OrderFund::getCreateTime);

        Page<OrderFund> page = new Page<>(pageNum, pageSize);
        return orderFundMapper.selectPage(page, wrapper);
    }
}
