import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, DataSource, FindOptionsWhere } from 'typeorm';
import { UserAccount } from '@/entities/user-account.entity';
import { MerchantAccount } from '@/entities/merchant-account.entity';
import { PlatformAccount } from '@/entities/platform-account.entity';
import { SystemAccount } from '@/entities/system-account.entity';
import { UserTransaction } from '@/entities/user-transaction.entity';
import { MerchantTransaction } from '@/entities/merchant-transaction.entity';
import { PlatformTransaction } from '@/entities/platform-transaction.entity';
import { SystemTransaction } from '@/entities/system-transaction.entity';
import { QueryUserAccountsDto, QueryMerchantAccountsDto } from './dto/account.dto';
import { ACCOUNT_NAMES } from '@/constants/account.constant';

@Injectable()
export class AccountService {
  constructor(
    @InjectRepository(UserAccount)
    private userAccountRepo: Repository<UserAccount>,
    @InjectRepository(MerchantAccount)
    private merchantAccountRepo: Repository<MerchantAccount>,
    @InjectRepository(PlatformAccount)
    private platformAccountRepo: Repository<PlatformAccount>,
    @InjectRepository(SystemAccount)
    private systemAccountRepo: Repository<SystemAccount>,
    @InjectRepository(UserTransaction)
    private userTransactionRepo: Repository<UserTransaction>,
    @InjectRepository(MerchantTransaction)
    private merchantTransactionRepo: Repository<MerchantTransaction>,
    @InjectRepository(PlatformTransaction)
    private platformTransactionRepo: Repository<PlatformTransaction>,
    @InjectRepository(SystemTransaction)
    private systemTransactionRepo: Repository<SystemTransaction>,
    private dataSource: DataSource,
  ) {}

  /**
   * 获取用户账户
   */
  async getUserAccount(userId: number): Promise<UserAccount> {
    let account = await this.userAccountRepo.findOne({ where: { user_id: userId } });

    if (!account) {
      account = this.userAccountRepo.create({
        user_id: userId,
        balance: 0,
        frozen_balance: 0,
        total_income: 0,
        total_expense: 0,
        status: 'active',
      });
      await this.userAccountRepo.save(account);
    }

    return account;
  }

  /**
   * 获取商家账户
   */
  async getMerchantAccount(merchantId: number): Promise<MerchantAccount> {
    let account = await this.merchantAccountRepo.findOne({ where: { merchant_id: merchantId } });

    if (!account) {
      account = this.merchantAccountRepo.create({
        merchant_id: merchantId,
        balance: 0,
        frozen_balance: 0,
        debt_amount: 0,
        total_income: 0,
        total_expense: 0,
        total_settlement: 0,
        total_withdraw: 0,
        pending_settlement: 0,
        status: 'active',
      });
      await this.merchantAccountRepo.save(account);
    }

    return account;
  }

  /**
   * 获取平台账户
   */
  async getPlatformAccount(accountName: string = ACCOUNT_NAMES.PLATFORM_MAIN): Promise<PlatformAccount> {
    const account = await this.platformAccountRepo.findOne({ where: { account_name: accountName } });

    if (!account) {
      throw new NotFoundException(
        `平台账户"${accountName}"不存在，请先执行数据库初始化脚本创建平台账户`
      );
    }

    return account;
  }

  /**
   * 用户账户增加余额（邀请返现）
   */
  async addUserBalance(
    userId: number,
    amount: number,
    transactionNo: string,
    businessType: string,
    businessId: number,
    businessNo: string,
    remark: string,
  ): Promise<void> {
    const queryRunner = this.dataSource.createQueryRunner();
    await queryRunner.connect();
    await queryRunner.startTransaction();

    try {
      const account = await queryRunner.manager.findOne(UserAccount, {
        where: { user_id: userId },
        lock: { mode: 'pessimistic_write' },
      });

      if (!account) {
        throw new NotFoundException('用户账户不存在');
      }

      if (account.status !== 'active') {
        throw new BadRequestException('账户状态异常');
      }

      const balanceBefore = Number(account.balance);
      const balanceAfter = balanceBefore + amount;

      account.balance = balanceAfter;
      account.total_income = Number(account.total_income) + amount;
      account.version += 1;

      await queryRunner.manager.save(account);

      const transaction = this.userTransactionRepo.create({
        transaction_no: transactionNo,
        user_id: userId,
        account_id: account.id,
        direction: 'income',
        amount,
        balance_before: balanceBefore,
        balance_after: balanceAfter,
        transaction_type: '邀请返现',
        business_type: businessType,
        business_id: businessId,
        business_no: businessNo,
        related_account_type: 'platform',
        remark,
      });

      await queryRunner.manager.save(transaction);
      await queryRunner.commitTransaction();
    } catch (error) {
      await queryRunner.rollbackTransaction();
      throw error;
    } finally {
      await queryRunner.release();
    }
  }

  /**
   * 用户账户扣减余额（提现）
   */
  async deductUserBalance(
    userId: number,
    amount: number,
    transactionNo: string,
    businessType: string,
    businessId: number,
    businessNo: string,
    remark: string,
  ): Promise<void> {
    const queryRunner = this.dataSource.createQueryRunner();
    await queryRunner.connect();
    await queryRunner.startTransaction();

    try {
      const account = await queryRunner.manager.findOne(UserAccount, {
        where: { user_id: userId },
        lock: { mode: 'pessimistic_write' },
      });

      if (!account) {
        throw new NotFoundException('用户账户不存在');
      }

      if (account.status !== 'active') {
        throw new BadRequestException('账户状态异常');
      }

      const balanceBefore = Number(account.balance);
      if (balanceBefore < amount) {
        throw new BadRequestException('账户余额不足');
      }

      const balanceAfter = balanceBefore - amount;

      account.balance = balanceAfter;
      account.total_expense = Number(account.total_expense) + amount;
      account.version += 1;

      await queryRunner.manager.save(account);

      const transaction = this.userTransactionRepo.create({
        transaction_no: transactionNo,
        user_id: userId,
        account_id: account.id,
        direction: 'expense',
        amount,
        balance_before: balanceBefore,
        balance_after: balanceAfter,
        transaction_type: '提现',
        business_type: businessType,
        business_id: businessId,
        business_no: businessNo,
        remark,
      });

      await queryRunner.manager.save(transaction);
      await queryRunner.commitTransaction();
    } catch (error) {
      await queryRunner.rollbackTransaction();
      throw error;
    } finally {
      await queryRunner.release();
    }
  }

  /**
   * 冻结用户余额（提现申请）
   */
  async freezeUserBalance(userId: number, amount: number): Promise<void> {
    const queryRunner = this.dataSource.createQueryRunner();
    await queryRunner.connect();
    await queryRunner.startTransaction();

    try {
      const account = await queryRunner.manager.findOne(UserAccount, {
        where: { user_id: userId },
        lock: { mode: 'pessimistic_write' },
      });

      if (!account) {
        throw new NotFoundException('用户账户不存在');
      }

      const balance = Number(account.balance);
      const frozenBalance = Number(account.frozen_balance);
      const availableBalance = balance - frozenBalance;

      if (availableBalance < amount) {
        throw new BadRequestException('可用余额不足');
      }

      // 只增加冻结金额，不减少余额
      account.frozen_balance = frozenBalance + amount;
      account.version += 1;

      await queryRunner.manager.save(account);
      await queryRunner.commitTransaction();
    } catch (error) {
      await queryRunner.rollbackTransaction();
      throw error;
    } finally {
      await queryRunner.release();
    }
  }

  /**
   * 解冻用户余额（提现失败/拒绝）
   */
  async unfreezeUserBalance(userId: number, amount: number): Promise<void> {
    const queryRunner = this.dataSource.createQueryRunner();
    await queryRunner.connect();
    await queryRunner.startTransaction();

    try {
      const account = await queryRunner.manager.findOne(UserAccount, {
        where: { user_id: userId },
        lock: { mode: 'pessimistic_write' },
      });

      if (!account) {
        throw new NotFoundException('用户账户不存在');
      }

      const frozenBalance = Number(account.frozen_balance);
      if (frozenBalance < amount) {
        throw new BadRequestException('冻结余额不足');
      }

      // 只减少冻结金额，不增加余额（因为余额本来就没减少）
      account.frozen_balance = frozenBalance - amount;
      account.version += 1;

      await queryRunner.manager.save(account);
      await queryRunner.commitTransaction();
    } catch (error) {
      await queryRunner.rollbackTransaction();
      throw error;
    } finally {
      await queryRunner.release();
    }
  }

  /**
   * 商家账户增加余额（结算）
   * 同时减少待结算金额
   */
  async addMerchantBalance(
    merchantId: number,
    amount: number,
    transactionNo: string,
    businessType: string,
    businessId: number,
    businessNo: string,
    remark: string,
  ): Promise<void> {
    // 先确保商家账户存在（如果不存在会自动创建）
    await this.getMerchantAccount(merchantId);

    const queryRunner = this.dataSource.createQueryRunner();
    await queryRunner.connect();
    await queryRunner.startTransaction();

    try {
      const account = await queryRunner.manager.findOne(MerchantAccount, {
        where: { merchant_id: merchantId },
        lock: { mode: 'pessimistic_write' },
      });

      if (!account) {
        throw new NotFoundException('商家账户不存在');
      }

      if (account.status !== 'active') {
        throw new BadRequestException('账户状态异常');
      }

      const balanceBefore = Number(account.balance);
      const balanceAfter = balanceBefore + amount;

      account.balance = balanceAfter;
      account.total_income = Number(account.total_income) + amount;
      // 结算时减少待结算金额
      account.pending_settlement = Math.max(0, Number(account.pending_settlement) - amount);
      account.version += 1;

      await queryRunner.manager.save(account);

      const transaction = this.merchantTransactionRepo.create({
        transaction_no: transactionNo,
        merchant_id: merchantId,
        account_id: account.id,
        direction: 'income',
        amount,
        balance_before: balanceBefore,
        balance_after: balanceAfter,
        transaction_type: '订单结算',
        business_type: businessType,
        business_id: businessId,
        business_no: businessNo,
        related_account_type: 'platform',
        remark,
      });

      await queryRunner.manager.save(transaction);
      await queryRunner.commitTransaction();
    } catch (error) {
      await queryRunner.rollbackTransaction();
      throw error;
    } finally {
      await queryRunner.release();
    }
  }

  /**
   * 商家账户增加待结算金额（订单完成时）
   */
  async addMerchantPendingSettlement(
    merchantId: number,
    amount: number,
  ): Promise<void> {
    const queryRunner = this.dataSource.createQueryRunner();
    await queryRunner.connect();
    await queryRunner.startTransaction();

    try {
      const account = await queryRunner.manager.findOne(MerchantAccount, {
        where: { merchant_id: merchantId },
        lock: { mode: 'pessimistic_write' },
      });

      if (!account) {
        throw new NotFoundException('商家账户不存在');
      }

      account.pending_settlement = Number(account.pending_settlement) + amount;
      account.version += 1;

      await queryRunner.manager.save(account);
      await queryRunner.commitTransaction();
    } catch (error) {
      await queryRunner.rollbackTransaction();
      throw error;
    } finally {
      await queryRunner.release();
    }
  }

  /**
   * 商家账户扣减余额（提现）
   */
  async deductMerchantBalance(
    merchantId: number,
    amount: number,
    transactionNo: string,
    businessType: string,
    businessId: number,
    businessNo: string,
    remark: string,
  ): Promise<void> {
    const queryRunner = this.dataSource.createQueryRunner();
    await queryRunner.connect();
    await queryRunner.startTransaction();

    try {
      const account = await queryRunner.manager.findOne(MerchantAccount, {
        where: { merchant_id: merchantId },
        lock: { mode: 'pessimistic_write' },
      });

      if (!account) {
        throw new NotFoundException('商家账户不存在');
      }

      if (account.status !== 'active') {
        throw new BadRequestException('账户状态异常');
      }

      const balanceBefore = Number(account.balance);
      if (balanceBefore < amount) {
        throw new BadRequestException('账户余额不足');
      }

      const balanceAfter = balanceBefore - amount;

      account.balance = balanceAfter;
      account.total_expense = Number(account.total_expense) + amount;
      account.version += 1;

      await queryRunner.manager.save(account);

      const transaction = this.merchantTransactionRepo.create({
        transaction_no: transactionNo,
        merchant_id: merchantId,
        account_id: account.id,
        direction: 'expense',
        amount,
        balance_before: balanceBefore,
        balance_after: balanceAfter,
        transaction_type: '提现',
        business_type: businessType,
        business_id: businessId,
        business_no: businessNo,
        remark,
      });

      await queryRunner.manager.save(transaction);
      await queryRunner.commitTransaction();
    } catch (error) {
      await queryRunner.rollbackTransaction();
      throw error;
    } finally {
      await queryRunner.release();
    }
  }

  /**
   * 平台账户增加服务费收入
   */
  async addPlatformServiceFee(
    serviceFee: number,
    transactionNo: string,
    businessType: string,
    businessId: number,
    businessNo: string,
    remark: string,
  ): Promise<void> {
    const queryRunner = this.dataSource.createQueryRunner();
    await queryRunner.connect();
    await queryRunner.startTransaction();

    try {
      const account = await queryRunner.manager.findOne(PlatformAccount, {
        where: { account_name: ACCOUNT_NAMES.PLATFORM_MAIN },
        lock: { mode: 'pessimistic_write' },
      });

      if (!account) {
        throw new NotFoundException('平台账户不存在');
      }

      const serviceFeeNum = Number(serviceFee);
      const balanceBefore = Number(account.balance);
      const balanceAfter = parseFloat((balanceBefore + serviceFeeNum).toFixed(2));

      account.balance = balanceAfter;
      account.total_income = parseFloat((Number(account.total_income) + serviceFeeNum).toFixed(2));
      account.version += 1;

      await queryRunner.manager.save(account);

      const transaction = this.platformTransactionRepo.create({
        transaction_no: transactionNo,
        account_id: account.id,
        direction: 'income',
        amount: serviceFeeNum,
        balance_before: balanceBefore,
        balance_after: balanceAfter,
        transaction_type: '服务费收入',
        business_type: businessType,
        business_id: businessId,
        business_no: businessNo,
        remark,
      });

      await queryRunner.manager.save(transaction);
      await queryRunner.commitTransaction();
    } catch (error) {
      await queryRunner.rollbackTransaction();
      throw error;
    } finally {
      await queryRunner.release();
    }
  }

  /**
   * 平台账户扣减邀请返现支出
   */
  async deductPlatformCashback(
    cashbackAmount: number,
    transactionNo: string,
    businessType: string,
    businessId: number,
    businessNo: string,
    remark: string,
  ): Promise<void> {
    const queryRunner = this.dataSource.createQueryRunner();
    await queryRunner.connect();
    await queryRunner.startTransaction();

    try {
      const account = await queryRunner.manager.findOne(PlatformAccount, {
        where: { account_name: ACCOUNT_NAMES.PLATFORM_MAIN },
        lock: { mode: 'pessimistic_write' },
      });

      if (!account) {
        throw new NotFoundException('平台账户不存在');
      }

      const cashbackNum = Number(cashbackAmount);
      const balanceBefore = Number(account.balance);
      const balanceAfter = parseFloat((balanceBefore - cashbackNum).toFixed(2));

      account.balance = balanceAfter;
      account.total_expense = parseFloat((Number(account.total_expense) + cashbackNum).toFixed(2));
      account.version += 1;

      await queryRunner.manager.save(account);

      const transaction = this.platformTransactionRepo.create({
        transaction_no: transactionNo,
        account_id: account.id,
        direction: 'expense',
        amount: cashbackNum,
        balance_before: balanceBefore,
        balance_after: balanceAfter,
        transaction_type: '邀请返现',
        business_type: businessType,
        business_id: businessId,
        business_no: businessNo,
        remark,
      });

      await queryRunner.manager.save(transaction);
      await queryRunner.commitTransaction();
    } catch (error) {
      await queryRunner.rollbackTransaction();
      throw error;
    } finally {
      await queryRunner.release();
    }
  }

  /**
   * 平台账户扣减提现
   */
  async deductPlatformWithdrawal(
    amount: number,
    transactionNo: string,
    businessType: string,
    businessId: number,
    businessNo: string,
    remark: string,
  ): Promise<void> {
    const queryRunner = this.dataSource.createQueryRunner();
    await queryRunner.connect();
    await queryRunner.startTransaction();

    try {
      const account = await queryRunner.manager.findOne(PlatformAccount, {
        where: { account_name: ACCOUNT_NAMES.PLATFORM_MAIN },
        lock: { mode: 'pessimistic_write' },
      });

      if (!account) {
        throw new NotFoundException('平台账户不存在');
      }

      const amountNum = Number(amount);
      const balanceBefore = Number(account.balance);
      const frozenBefore = Number(account.frozen_balance);

      if (balanceBefore < amountNum) {
        throw new BadRequestException('平台账户余额不足');
      }

      if (frozenBefore < amountNum) {
        throw new BadRequestException('冻结金额不足');
      }

      const balanceAfter = parseFloat((balanceBefore - amountNum).toFixed(2));
      const frozenAfter = parseFloat((frozenBefore - amountNum).toFixed(2));

      // 确认打款时：扣减余额和冻结金额
      account.balance = balanceAfter;
      account.frozen_balance = frozenAfter;
      account.version += 1;

      await queryRunner.manager.save(account);

      const transaction = this.platformTransactionRepo.create({
        transaction_no: transactionNo,
        account_id: account.id,
        direction: 'expense',
        amount: amountNum,
        balance_before: balanceBefore,
        balance_after: balanceAfter,
        transaction_type: '提现',
        business_type: businessType,
        business_id: businessId,
        business_no: businessNo,
        remark,
      });

      await queryRunner.manager.save(transaction);
      await queryRunner.commitTransaction();
    } catch (error) {
      await queryRunner.rollbackTransaction();
      throw error;
    } finally {
      await queryRunner.release();
    }
  }

  // ==================== 管理员查询接口 ====================

  /**
   * 查询平台账户列表
   */
  async getPlatformAccounts() {
    const accounts = await this.platformAccountRepo.find({
      order: { created_at: 'DESC' },
    });
    return accounts;
  }

  /**
   * 查询平台账户详情
   */
  async getPlatformAccountDetail(id: number) {
    const account = await this.platformAccountRepo.findOne({ where: { id } });
    if (!account) {
      throw new NotFoundException('平台账户不存在');
    }
    return account;
  }

  /**
   * 查询平台账户余额
   */
  async getPlatformAccountBalance(id: number) {
    const account = await this.platformAccountRepo.findOne({
      where: { id },
      select: ['id', 'account_name', 'balance', 'frozen_balance'],
    });
    if (!account) {
      throw new NotFoundException('平台账户不存在');
    }
    return account;
  }

  /**
   * 查询用户账户列表
   */
  async getUserAccounts(dto: QueryUserAccountsDto) {
    const where: FindOptionsWhere<UserAccount> = {};
    if (dto.status) where.status = dto.status as any;
    if (dto.userId) where.user_id = dto.userId;

    const [list, total] = await this.userAccountRepo.findAndCount({
      where,
      relations: ['user'],
      order: { created_at: 'DESC' },
      skip: ((dto.page ?? 1) - 1) * (dto.pageSize ?? 10),
      take: dto.pageSize ?? 10,
    });

    // 映射数据，添加用户名
    const mappedList = list.map(account => ({
      ...account,
      userName: account.user?.nickname || account.user?.phone || '-',
    }));

    return { list: mappedList, total, page: dto.page ?? 1, pageSize: dto.pageSize ?? 10 };
  }

  /**
   * 查询用户账户详情
   */
  async getUserAccountDetail(userId: number) {
    const account = await this.userAccountRepo.findOne({
      where: { user_id: userId },
    });
    if (!account) {
      throw new NotFoundException('用户账户不存在');
    }
    return account;
  }

  /**
   * 用户账户汇总统计
   */
  async getUserAccountsSummary() {
    const result = await this.userAccountRepo
      .createQueryBuilder('ua')
      .select('COUNT(*)', 'totalAccounts')
      .addSelect('COALESCE(SUM(ua.balance), 0)', 'totalBalance')
      .addSelect('COALESCE(SUM(ua.frozen_balance), 0)', 'totalFrozenBalance')
      .addSelect('COALESCE(SUM(ua.total_income), 0)', 'totalIncome')
      .addSelect('COALESCE(SUM(ua.total_expense), 0)', 'totalExpense')
      .getRawOne();

    return {
      totalAccounts: Number(result?.totalAccounts || 0),
      totalBalance: Number(result?.totalBalance || 0),
      totalFrozenBalance: Number(result?.totalFrozenBalance || 0),
      totalIncome: Number(result?.totalIncome || 0),
      totalExpense: Number(result?.totalExpense || 0),
    };
  }

  /**
   * 查询商家账户列表
   */
  async getMerchantAccounts(dto: QueryMerchantAccountsDto) {
    const where: FindOptionsWhere<MerchantAccount> = {};
    if (dto.status) where.status = dto.status as any;
    if (dto.merchantId) where.merchant_id = dto.merchantId;

    const [list, total] = await this.merchantAccountRepo.findAndCount({
      where,
      relations: ['merchant'],
      order: { created_at: 'DESC' },
      skip: ((dto.page ?? 1) - 1) * (dto.pageSize ?? 10),
      take: dto.pageSize ?? 10,
    });

    // 映射数据，添加商家名称
    const mappedList = list.map(account => ({
      ...account,
      merchantName: account.merchant?.shopName || '-',
    }));

    return { list: mappedList, total, page: dto.page ?? 1, pageSize: dto.pageSize ?? 10 };
  }

  /**
   * 查询商家账户详情
   */
  async getMerchantAccountDetail(merchantId: number) {
    const account = await this.merchantAccountRepo.findOne({
      where: { merchant_id: merchantId },
    });
    if (!account) {
      throw new NotFoundException('商家账户不存在');
    }
    return account;
  }

  /**
   * 商家账户汇总统计
   */
  async getMerchantAccountsSummary() {
    const result = await this.merchantAccountRepo
      .createQueryBuilder('ma')
      .select('COUNT(*)', 'totalAccounts')
      .addSelect('COALESCE(SUM(ma.balance), 0)', 'totalBalance')
      .addSelect('COALESCE(SUM(ma.frozen_balance), 0)', 'totalFrozenBalance')
      .addSelect('COALESCE(SUM(ma.debt_amount), 0)', 'totalDebtAmount')
      .addSelect('COALESCE(SUM(ma.total_income), 0)', 'totalIncome')
      .addSelect('COALESCE(SUM(ma.total_expense), 0)', 'totalExpense')
      .addSelect('COALESCE(SUM(ma.pending_settlement), 0)', 'totalPendingSettlement')
      .getRawOne();

    return {
      totalAccounts: Number(result?.totalAccounts || 0),
      totalBalance: Number(result?.totalBalance || 0),
      totalFrozenBalance: Number(result?.totalFrozenBalance || 0),
      totalDebtAmount: Number(result?.totalDebtAmount || 0),
      totalIncome: Number(result?.totalIncome || 0),
      totalExpense: Number(result?.totalExpense || 0),
      totalPendingSettlement: Number(result?.totalPendingSettlement || 0),
    };
  }

  // ============================================================
  // 系统总账户操作方法
  // ============================================================

  /**
   * 获取系统总账户
   */
  async getSystemAccount(accountName: string = ACCOUNT_NAMES.SYSTEM_MAIN): Promise<SystemAccount> {
    const account = await this.systemAccountRepo.findOne({ where: { account_name: accountName } });

    if (!account) {
      throw new NotFoundException(
        `系统总账户"${accountName}"不存在，请先执行数据库初始化脚本创建系统总账户`
      );
    }

    return account;
  }

  /**
   * 系统总账户增加收入（用户支付订单）
   */
  async addSystemIncome(
    amount: number,
    transactionNo: string,
    businessType: string,
    businessId: number,
    businessNo: string,
    remark: string,
  ): Promise<void> {
    const queryRunner = this.dataSource.createQueryRunner();
    await queryRunner.connect();
    await queryRunner.startTransaction();

    try {
      const account = await queryRunner.manager.findOne(SystemAccount, {
        where: { account_name: ACCOUNT_NAMES.SYSTEM_MAIN },
        lock: { mode: 'pessimistic_write' },
      });

      if (!account) {
        throw new NotFoundException('系统总账户不存在');
      }

      const amountNum = Number(amount);
      const balanceBefore = Number(account.balance);
      const balanceAfter = parseFloat((balanceBefore + amountNum).toFixed(2));

      account.balance = balanceAfter;
      account.total_income = parseFloat((Number(account.total_income) + amountNum).toFixed(2));
      account.version += 1;

      await queryRunner.manager.save(account);

      const transaction = this.systemTransactionRepo.create({
        transactionNo: transactionNo,
        accountId: account.id,
        direction: 'income',
        amount: amountNum,
        balanceBefore: balanceBefore,
        balanceAfter: balanceAfter,
        transactionType: '用户支付',
        businessType: businessType,
        businessId: businessId,
        businessNo: businessNo,
        remark,
      });

      await queryRunner.manager.save(transaction);
      await queryRunner.commitTransaction();
    } catch (error) {
      await queryRunner.rollbackTransaction();
      throw error;
    } finally {
      await queryRunner.release();
    }
  }

  /**
   * 系统总账户增加退款支出
   */
  async addSystemRefund(
    amount: number,
    transactionNo: string,
    businessType: string,
    businessId: number,
    businessNo: string,
    remark: string,
  ): Promise<void> {
    const queryRunner = this.dataSource.createQueryRunner();
    await queryRunner.connect();
    await queryRunner.startTransaction();

    try {
      const account = await queryRunner.manager.findOne(SystemAccount, {
        where: { account_name: ACCOUNT_NAMES.SYSTEM_MAIN },
        lock: { mode: 'pessimistic_write' },
      });

      if (!account) {
        throw new NotFoundException('系统总账户不存在');
      }

      const amountNum = Number(amount);
      const balanceBefore = Number(account.balance);
      const balanceAfter = parseFloat((balanceBefore - amountNum).toFixed(2));

      account.balance = balanceAfter;
      account.total_refund = parseFloat((Number(account.total_refund) + amountNum).toFixed(2));
      account.version += 1;

      await queryRunner.manager.save(account);

      const transaction = this.systemTransactionRepo.create({
        transactionNo: transactionNo,
        accountId: account.id,
        direction: 'expense',
        amount: amountNum,
        balanceBefore: balanceBefore,
        balanceAfter: balanceAfter,
        transactionType: '退款',
        businessType: businessType,
        businessId: businessId,
        businessNo: businessNo,
        remark,
      });

      await queryRunner.manager.save(transaction);
      await queryRunner.commitTransaction();
    } catch (error) {
      await queryRunner.rollbackTransaction();
      throw error;
    } finally {
      await queryRunner.release();
    }
  }

  /**
   * 系统总账户增加提现支出
   */
  async addSystemWithdrawal(
    amount: number,
    transactionNo: string,
    businessType: string,
    businessId: number,
    businessNo: string,
    remark: string,
  ): Promise<void> {
    const queryRunner = this.dataSource.createQueryRunner();
    await queryRunner.connect();
    await queryRunner.startTransaction();

    try {
      const account = await queryRunner.manager.findOne(SystemAccount, {
        where: { account_name: ACCOUNT_NAMES.SYSTEM_MAIN },
        lock: { mode: 'pessimistic_write' },
      });

      if (!account) {
        throw new NotFoundException('系统总账户不存在');
      }

      const amountNum = Number(amount);
      const balanceBefore = Number(account.balance);
      const balanceAfter = parseFloat((balanceBefore - amountNum).toFixed(2));

      account.balance = balanceAfter;
      account.total_withdrawn = parseFloat((Number(account.total_withdrawn) + amountNum).toFixed(2));
      account.version += 1;

      await queryRunner.manager.save(account);

      const transaction = this.systemTransactionRepo.create({
        transactionNo: transactionNo,
        accountId: account.id,
        direction: 'expense',
        amount: amountNum,
        balanceBefore: balanceBefore,
        balanceAfter: balanceAfter,
        transactionType: '提现',
        businessType: businessType,
        businessId: businessId,
        businessNo: businessNo,
        remark,
      });

      await queryRunner.manager.save(transaction);
      await queryRunner.commitTransaction();
    } catch (error) {
      await queryRunner.rollbackTransaction();
      throw error;
    } finally {
      await queryRunner.release();
    }
  }
}
