import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PrismaService } from '../../infrastructure/persistence/prisma/prisma.service';
import { RedisService } from '../../infrastructure/redis/redis.service';
import { OrderRepository } from '../../infrastructure/persistence/repositories/order.repository';
import { TradingAccountRepository } from '../../infrastructure/persistence/repositories/trading-account.repository';
import { OrderService } from './order.service';
import { PriceService } from './price.service';
import { OrderType, OrderSource } from '../../domain/aggregates/order.aggregate';
import { TradingAccountAggregate } from '../../domain/aggregates/trading-account.aggregate';
import { Money } from '../../domain/value-objects/money.vo';
import Decimal from 'decimal.js';

export interface DepthLevel {
  price: string;
  quantity: string;
  total: string; // 累计数量
}

export interface DepthData {
  bids: DepthLevel[]; // 买单深度（从高到低）
  asks: DepthLevel[]; // 卖单深度（从低到高）
  timestamp: number;
}

export interface MarketMakerConfig {
  id: string;
  name: string;
  accountSequence: string;
  cashBalance: Decimal;
  shareBalance: Decimal;
  frozenCash: Decimal;
  frozenShares: Decimal;
  maxBuyRatio: Decimal;
  minIntervalMs: number;
  maxIntervalMs: number;
  priceStrategy: string;
  discountRate: Decimal;
  isActive: boolean;
  kavaWalletAddress: string | null;
  eusdtWalletAddress: string | null;
}

export enum LedgerType {
  DEPOSIT = 'DEPOSIT',
  WITHDRAW = 'WITHDRAW',
  BUY = 'BUY',
  SELL = 'SELL',
  FREEZE = 'FREEZE',
  UNFREEZE = 'UNFREEZE',
}

export enum AssetType {
  CASH = 'CASH',
  SHARE = 'SHARE',
}

export type MarketMakerMode = 'idle' | 'taker' | 'maker';

@Injectable()
export class MarketMakerService {
  private readonly logger = new Logger(MarketMakerService.name);
  private isRunning = false;
  private timeoutId: NodeJS.Timeout | null = null;
  private makerTimeoutId: NodeJS.Timeout | null = null;
  private isMakerRunning = false;

  constructor(
    private readonly prisma: PrismaService,
    private readonly redis: RedisService,
    private readonly orderRepository: OrderRepository,
    private readonly accountRepository: TradingAccountRepository,
    private readonly orderService: OrderService,
    private readonly priceService: PriceService,
    private readonly configService: ConfigService,
  ) {}

  /**
   * 获取做市商配置
   * 注意：余额从 TradingAccount 获取，保证一致性
   */
  async getConfig(name: string = 'MAIN_MARKET_MAKER'): Promise<MarketMakerConfig | null> {
    const config = await this.prisma.marketMakerConfig.findUnique({
      where: { name },
    });
    if (!config) return null;

    // 自动从环境变量填充空的钱包地址
    const updateData: Record<string, string> = {};
    if (!config.kavaWalletAddress) {
      const addr = this.configService.get<string>('FUSDT_MARKET_MAKER_ADDRESS');
      if (addr) updateData.kavaWalletAddress = addr;
    }
    if (!config.eusdtWalletAddress) {
      const addr = this.configService.get<string>('EUSDT_MARKET_MAKER_ADDRESS');
      if (addr) updateData.eusdtWalletAddress = addr;
    }
    if (Object.keys(updateData).length > 0) {
      await this.prisma.marketMakerConfig.update({
        where: { name },
        data: updateData,
      });
      Object.assign(config, updateData);
      this.logger.log(`Auto-filled wallet addresses from env for ${name}: ${JSON.stringify(updateData)}`);
    }

    // 从交易账户获取实际余额（保证一致性）
    const tradingAccount = await this.accountRepository.findByAccountSequence(config.accountSequence);
    const cashBalance = tradingAccount ? new Decimal(tradingAccount.cashBalance.value.toString()) : new Decimal(0);
    const shareBalance = tradingAccount ? new Decimal(tradingAccount.shareBalance.value.toString()) : new Decimal(0);
    const frozenCash = tradingAccount ? new Decimal(tradingAccount.frozenCash.value.toString()) : new Decimal(0);
    const frozenShares = tradingAccount ? new Decimal(tradingAccount.frozenShares.value.toString()) : new Decimal(0);

    return {
      id: config.id,
      name: config.name,
      accountSequence: config.accountSequence,
      cashBalance,
      shareBalance,
      frozenCash,
      frozenShares,
      maxBuyRatio: new Decimal(config.maxBuyRatio.toString()),
      minIntervalMs: config.minIntervalMs,
      maxIntervalMs: config.maxIntervalMs,
      priceStrategy: config.priceStrategy,
      discountRate: new Decimal(config.discountRate.toString()),
      isActive: config.isActive,
      kavaWalletAddress: config.kavaWalletAddress,
      eusdtWalletAddress: config.eusdtWalletAddress,
    };
  }

  /**
   * 获取当前运行模式
   * idle: 空闲（两个模式都未运行）
   * taker: 吃单模式运行中
   * maker: 挂单模式运行中
   */
  getCurrentMode(): MarketMakerMode {
    if (this.isMakerRunning) return 'maker';
    if (this.isRunning) return 'taker';
    return 'idle';
  }

  /**
   * 获取运行状态详情
   */
  getRunningStatus(): {
    mode: MarketMakerMode;
    takerRunning: boolean;
    makerRunning: boolean;
  } {
    return {
      mode: this.getCurrentMode(),
      takerRunning: this.isRunning,
      makerRunning: this.isMakerRunning,
    };
  }

  /**
   * 初始化做市商配置（如果不存在）
   */
  async initializeConfig(params: {
    name?: string;
    accountSequence: string;
    initialCash?: string;
    maxBuyRatio?: number;
    minIntervalMs?: number;
    maxIntervalMs?: number;
  }): Promise<MarketMakerConfig> {
    const name = params.name || 'MAIN_MARKET_MAKER';

    // 检查是否已存在
    const existing = await this.getConfig(name);
    if (existing) {
      // 如果存在但钱包地址为空，尝试从环境变量更新
      const updateData: any = {};
      if (!existing.kavaWalletAddress) {
        const kavaWalletAddress = this.configService.get<string>('FUSDT_MARKET_MAKER_ADDRESS');
        if (kavaWalletAddress) updateData.kavaWalletAddress = kavaWalletAddress;
      }
      if (!existing.eusdtWalletAddress) {
        const eusdtWalletAddress = this.configService.get<string>('EUSDT_MARKET_MAKER_ADDRESS');
        if (eusdtWalletAddress) updateData.eusdtWalletAddress = eusdtWalletAddress;
      }
      if (Object.keys(updateData).length > 0) {
        await this.prisma.marketMakerConfig.update({
          where: { name },
          data: updateData,
        });
        this.logger.log(`Market maker ${name} wallet addresses updated from env: ${JSON.stringify(updateData)}`);
        return this.getConfig(name) as Promise<MarketMakerConfig>;
      }
      return existing;
    }

    // 确保交易账户存在
    let tradingAccount = await this.accountRepository.findByAccountSequence(params.accountSequence);
    if (!tradingAccount) {
      tradingAccount = TradingAccountAggregate.create(params.accountSequence);
      await this.accountRepository.save(tradingAccount);
    }

    // 从环境变量读取做市商钱包地址
    const kavaWalletAddress = this.configService.get<string>('FUSDT_MARKET_MAKER_ADDRESS') || null;
    const eusdtWalletAddress = this.configService.get<string>('EUSDT_MARKET_MAKER_ADDRESS') || null;

    // 创建做市商配置
    const config = await this.prisma.marketMakerConfig.create({
      data: {
        name,
        accountSequence: params.accountSequence,
        cashBalance: params.initialCash || '0',
        maxBuyRatio: params.maxBuyRatio || 0.05,
        minIntervalMs: params.minIntervalMs || 1000,
        maxIntervalMs: params.maxIntervalMs || 1000,
        kavaWalletAddress,
        eusdtWalletAddress,
      },
    });

    this.logger.log(`Market maker initialized: ${name}, account: ${params.accountSequence}, fUSDT wallet: ${kavaWalletAddress || 'not configured'}, eUSDT wallet: ${eusdtWalletAddress || 'not configured'}`);

    return this.getConfig(name) as Promise<MarketMakerConfig>;
  }

  /**
   * 充值资金到做市商账户
   * 注意：只更新 TradingAccount，不维护双重余额
   */
  async deposit(name: string, amount: string, memo?: string): Promise<void> {
    const configRecord = await this.prisma.marketMakerConfig.findUnique({
      where: { name },
    });
    if (!configRecord) {
      throw new Error(`Market maker ${name} not found`);
    }

    const depositAmount = new Decimal(amount);
    if (depositAmount.lte(0)) {
      throw new Error('Deposit amount must be positive');
    }

    // 获取交易账户当前余额
    let tradingAccount = await this.accountRepository.findByAccountSequence(configRecord.accountSequence);
    if (!tradingAccount) {
      tradingAccount = TradingAccountAggregate.create(configRecord.accountSequence);
    }

    const balanceBefore = new Decimal(tradingAccount.cashBalance.value.toString());
    const balanceAfter = balanceBefore.plus(depositAmount);

    // 更新交易账户余额
    tradingAccount.deposit(new Money(depositAmount), 'MARKET_MAKER_DEPOSIT');
    await this.accountRepository.save(tradingAccount);

    // 记录做市商分类账
    await this.prisma.marketMakerLedger.create({
      data: {
        marketMakerId: configRecord.id,
        type: LedgerType.DEPOSIT,
        assetType: AssetType.CASH,
        amount: depositAmount,
        balanceBefore,
        balanceAfter,
        memo: memo || '管理员充值',
      },
    });

    this.logger.log(`Market maker ${name} deposited: ${amount}, new balance: ${balanceAfter.toString()}`);
  }

  /**
   * 提现资金
   * 注意：只操作 TradingAccount，不维护双重余额
   */
  async withdraw(name: string, amount: string, memo?: string): Promise<void> {
    const configRecord = await this.prisma.marketMakerConfig.findUnique({
      where: { name },
    });
    if (!configRecord) {
      throw new Error(`Market maker ${name} not found`);
    }

    const withdrawAmount = new Decimal(amount);

    // 获取交易账户当前余额
    const tradingAccount = await this.accountRepository.findByAccountSequence(configRecord.accountSequence);
    if (!tradingAccount) {
      throw new Error('Trading account not found');
    }

    const availableBalance = new Decimal(tradingAccount.availableCash.value.toString());
    if (withdrawAmount.gt(availableBalance)) {
      throw new Error(`Insufficient balance. Available: ${availableBalance.toString()}`);
    }

    const balanceBefore = new Decimal(tradingAccount.cashBalance.value.toString());
    const balanceAfter = balanceBefore.minus(withdrawAmount);

    // 更新交易账户余额
    tradingAccount.withdraw(new Money(withdrawAmount), 'MARKET_MAKER_WITHDRAW');
    await this.accountRepository.save(tradingAccount);

    // 记录做市商分类账
    await this.prisma.marketMakerLedger.create({
      data: {
        marketMakerId: configRecord.id,
        type: LedgerType.WITHDRAW,
        assetType: AssetType.CASH,
        amount: withdrawAmount.negated(),
        balanceBefore,
        balanceAfter,
        memo: memo || '管理员提现',
      },
    });

    this.logger.log(`Market maker ${name} withdrew: ${amount}`);
  }

  /**
   * 充值积分股到做市商账户
   */
  async depositShares(name: string, amount: string, memo?: string): Promise<void> {
    const configRecord = await this.prisma.marketMakerConfig.findUnique({
      where: { name },
    });
    if (!configRecord) {
      throw new Error(`Market maker ${name} not found`);
    }

    const depositAmount = new Decimal(amount);
    if (depositAmount.lte(0)) {
      throw new Error('Deposit amount must be positive');
    }

    // 获取交易账户当前余额
    let tradingAccount = await this.accountRepository.findByAccountSequence(configRecord.accountSequence);
    if (!tradingAccount) {
      tradingAccount = TradingAccountAggregate.create(configRecord.accountSequence);
    }

    const balanceBefore = new Decimal(tradingAccount.shareBalance.value.toString());
    const balanceAfter = balanceBefore.plus(depositAmount);

    // 更新交易账户积分股余额
    tradingAccount.depositShares(new Money(depositAmount), 'MARKET_MAKER_SHARE_DEPOSIT');
    await this.accountRepository.save(tradingAccount);

    // 记录做市商分类账
    await this.prisma.marketMakerLedger.create({
      data: {
        marketMakerId: configRecord.id,
        type: LedgerType.DEPOSIT,
        assetType: AssetType.SHARE,
        amount: depositAmount,
        balanceBefore,
        balanceAfter,
        memo: memo || '管理员充值积分股',
      },
    });

    this.logger.log(`Market maker ${name} deposited shares: ${amount}, new balance: ${balanceAfter.toString()}`);
  }

  /**
   * 提现积分股
   */
  async withdrawShares(name: string, amount: string, memo?: string): Promise<void> {
    const configRecord = await this.prisma.marketMakerConfig.findUnique({
      where: { name },
    });
    if (!configRecord) {
      throw new Error(`Market maker ${name} not found`);
    }

    const withdrawAmount = new Decimal(amount);

    // 获取交易账户当前余额
    const tradingAccount = await this.accountRepository.findByAccountSequence(configRecord.accountSequence);
    if (!tradingAccount) {
      throw new Error('Trading account not found');
    }

    const availableBalance = new Decimal(tradingAccount.availableShares.value.toString());
    if (withdrawAmount.gt(availableBalance)) {
      throw new Error(`Insufficient share balance. Available: ${availableBalance.toString()}`);
    }

    const balanceBefore = new Decimal(tradingAccount.shareBalance.value.toString());
    const balanceAfter = balanceBefore.minus(withdrawAmount);

    // 更新交易账户积分股余额
    tradingAccount.withdrawShares(new Money(withdrawAmount), 'MARKET_MAKER_SHARE_WITHDRAW');
    await this.accountRepository.save(tradingAccount);

    // 记录做市商分类账
    await this.prisma.marketMakerLedger.create({
      data: {
        marketMakerId: configRecord.id,
        type: LedgerType.WITHDRAW,
        assetType: AssetType.SHARE,
        amount: withdrawAmount.negated(),
        balanceBefore,
        balanceAfter,
        memo: memo || '管理员提现积分股',
      },
    });

    this.logger.log(`Market maker ${name} withdrew shares: ${amount}`);
  }

  /**
   * 启动做市商（吃单模式）
   * 注意：与挂单模式互斥，启动吃单模式会自动停止挂单模式
   */
  async start(name: string = 'MAIN_MARKET_MAKER'): Promise<void> {
    const config = await this.getConfig(name);
    if (!config) {
      throw new Error(`Market maker ${name} not found`);
    }

    if (this.isRunning) {
      this.logger.warn('Market maker taker mode is already running');
      return;
    }

    // 互斥：如果挂单模式正在运行，先停止它
    if (this.isMakerRunning) {
      this.logger.log('Stopping maker mode before starting taker mode (mutual exclusion)');
      await this.stopMaker(name);
    }

    await this.prisma.marketMakerConfig.update({
      where: { id: config.id },
      data: { isActive: true, makerEnabled: false },
    });

    this.isRunning = true;
    this.logger.log(`Market maker ${name} taker mode started`);

    // 开始吃单循环
    this.scheduleNextRun(config);
  }

  /**
   * 停止做市商
   */
  async stop(name: string = 'MAIN_MARKET_MAKER'): Promise<void> {
    const config = await this.getConfig(name);
    if (!config) {
      throw new Error(`Market maker ${name} not found`);
    }

    if (this.timeoutId) {
      clearTimeout(this.timeoutId);
      this.timeoutId = null;
    }

    this.isRunning = false;

    await this.prisma.marketMakerConfig.update({
      where: { id: config.id },
      data: { isActive: false },
    });

    this.logger.log(`Market maker ${name} stopped`);
  }

  /**
   * 执行一次吃单
   */
  async executeTakeOrder(name: string = 'MAIN_MARKET_MAKER'): Promise<{
    success: boolean;
    message: string;
    tradeInfo?: {
      orderNo: string;
      sellOrderNo: string;
      price: string;
      quantity: string;
      amount: string;
    };
  }> {
    const lockValue = await this.redis.acquireLock(`market-maker:take:${name}`, 30);
    if (!lockValue) {
      return { success: false, message: 'Another take order is in progress' };
    }

    try {
      // 获取最新配置
      const config = await this.getConfig(name);
      if (!config) {
        return { success: false, message: `Market maker ${name} not found` };
      }

      // 查找最老的待成交卖单
      const oldestSellOrder = await this.orderRepository.findOldestPendingSellOrder();
      if (!oldestSellOrder) {
        return { success: false, message: 'No pending sell orders found' };
      }

      // 计算可用资金
      const availableCash = config.cashBalance.minus(config.frozenCash);
      if (availableCash.lte(0)) {
        return { success: false, message: 'Insufficient cash balance' };
      }

      // 计算本次最大买入金额（资金池的 maxBuyRatio）
      const maxBuyAmount = availableCash.times(config.maxBuyRatio);

      // 根据价格策略确定买入价格
      let buyPrice: Decimal;
      switch (config.priceStrategy) {
        case 'DISCOUNT':
          buyPrice = new Decimal(oldestSellOrder.price.value).times(config.discountRate);
          break;
        case 'MARKET':
          // TODO: 从价格服务获取当前市场价
          buyPrice = new Decimal(oldestSellOrder.price.value);
          break;
        case 'TAKER':
        default:
          // 以卖单价格买入
          buyPrice = new Decimal(oldestSellOrder.price.value);
          break;
      }

      // 计算买入数量
      const maxQuantityByAmount = maxBuyAmount.dividedBy(buyPrice);
      const sellOrderRemaining = new Decimal(oldestSellOrder.remainingQuantity.value);
      const buyQuantity = Decimal.min(maxQuantityByAmount, sellOrderRemaining);

      if (buyQuantity.lte(0)) {
        return { success: false, message: 'Calculated buy quantity is zero or negative' };
      }

      // 创建买单（OrderService 会自动撮合）
      const result = await this.orderService.createOrder(
        config.accountSequence,
        OrderType.BUY,
        buyPrice.toString(),
        buyQuantity.toString(),
        OrderSource.MARKET_MAKER,
        '做市商吃单',
      );

      // 获取实际成交量（可能部分成交或全部成交）
      const filledQuantity = new Decimal(result.filledQuantity);

      if (filledQuantity.lte(0)) {
        // 订单未成交（可能价格不匹配或其他原因）
        this.logger.warn(`Market maker order not filled: ${result.orderNo}`);
        return {
          success: true,
          message: 'Order created but not filled yet',
          tradeInfo: {
            orderNo: result.orderNo,
            sellOrderNo: oldestSellOrder.orderNo,
            price: buyPrice.toString(),
            quantity: '0',
            amount: '0',
          },
        };
      }

      // 基于实际成交量记录分类账
      const actualAmount = filledQuantity.times(buyPrice);
      await this.recordTradeLedger(config.id, {
        type: LedgerType.BUY,
        cashAmount: actualAmount,
        shareAmount: filledQuantity,
        price: buyPrice,
        orderNo: result.orderNo,
        counterpartySeq: oldestSellOrder.accountSequence,
        memo: `吃单买入, 卖单号: ${oldestSellOrder.orderNo}, 成交量: ${filledQuantity.toString()}`,
      });

      // 更新做市商统计（基于实际成交量）
      await this.prisma.marketMakerConfig.update({
        where: { id: config.id },
        data: {
          lastRunAt: new Date(),
          totalBuyCount: { increment: 1 },
          totalBuyQuantity: { increment: filledQuantity },
          totalBuyAmount: { increment: actualAmount },
        },
      });

      this.logger.log(
        `Market maker took order: ${result.orderNo}, price: ${buyPrice.toString()}, filled: ${filledQuantity.toString()}`,
      );

      return {
        success: true,
        message: 'Order taken successfully',
        tradeInfo: {
          orderNo: result.orderNo,
          sellOrderNo: oldestSellOrder.orderNo,
          price: buyPrice.toString(),
          quantity: filledQuantity.toString(),
          amount: actualAmount.toString(),
        },
      };
    } catch (error) {
      this.logger.error(`Market maker take order failed: ${error}`);
      return { success: false, message: `Take order failed: ${error}` };
    } finally {
      await this.redis.releaseLock(`market-maker:take:${name}`, lockValue);
    }
  }

  /**
   * 记录交易分类账
   * 注意：余额已由 OrderService 在 TradingAccount 中更新，这里只记录分类账
   */
  private async recordTradeLedger(
    marketMakerId: string,
    params: {
      type: LedgerType;
      cashAmount: Decimal;
      shareAmount: Decimal;
      price: Decimal;
      orderNo: string;
      tradeNo?: string;
      counterpartySeq?: string;
      memo?: string;
    },
  ): Promise<void> {
    const config = await this.prisma.marketMakerConfig.findUnique({
      where: { id: marketMakerId },
    });
    if (!config) return;

    // 从 TradingAccount 获取实际余额
    const tradingAccount = await this.accountRepository.findByAccountSequence(config.accountSequence);
    if (!tradingAccount) return;

    // 注意：此时 OrderService.createOrder 已经完成撮合并更新了 TradingAccount
    // 所以 TradingAccount 中的余额是成交后的余额（balanceAfter）
    const cashAfter = new Decimal(tradingAccount.cashBalance.value.toString());
    const shareAfter = new Decimal(tradingAccount.shareBalance.value.toString());

    // 买入：现金减少，积分股增加
    // 卖出：现金增加，积分股减少
    const isBuy = params.type === LedgerType.BUY;
    const cashBefore = isBuy ? cashAfter.plus(params.cashAmount) : cashAfter.minus(params.cashAmount);
    const shareBefore = isBuy ? shareAfter.minus(params.shareAmount) : shareAfter.plus(params.shareAmount);

    // 只记录分类账，不再更新 MarketMakerConfig 的余额字段
    await this.prisma.$transaction(async (tx) => {
      // 记录现金流水
      await tx.marketMakerLedger.create({
        data: {
          marketMakerId,
          type: params.type,
          assetType: AssetType.CASH,
          amount: isBuy ? params.cashAmount.negated() : params.cashAmount,
          balanceBefore: cashBefore,
          balanceAfter: cashAfter,
          orderNo: params.orderNo,
          tradeNo: params.tradeNo,
          counterpartySeq: params.counterpartySeq,
          price: params.price,
          quantity: params.shareAmount,
          memo: params.memo,
        },
      });

      // 记录积分股流水
      await tx.marketMakerLedger.create({
        data: {
          marketMakerId,
          type: params.type,
          assetType: AssetType.SHARE,
          amount: isBuy ? params.shareAmount : params.shareAmount.negated(),
          balanceBefore: shareBefore,
          balanceAfter: shareAfter,
          orderNo: params.orderNo,
          tradeNo: params.tradeNo,
          counterpartySeq: params.counterpartySeq,
          price: params.price,
          quantity: params.shareAmount,
          memo: params.memo,
        },
      });
    });
  }

  /**
   * 调度下一次运行
   */
  private scheduleNextRun(config: MarketMakerConfig): void {
    if (!this.isRunning) return;

    // 随机间隔 (minIntervalMs ~ maxIntervalMs)
    const interval =
      config.minIntervalMs + Math.random() * (config.maxIntervalMs - config.minIntervalMs);

    this.timeoutId = setTimeout(async () => {
      await this.executeTakeOrder(config.name);

      // 重新获取配置（可能已被更新）
      const latestConfig = await this.getConfig(config.name);
      if (latestConfig && latestConfig.isActive) {
        this.scheduleNextRun(latestConfig);
      } else {
        this.isRunning = false;
      }
    }, interval);
  }

  /**
   * 获取做市商统计
   */
  async getStats(name: string = 'MAIN_MARKET_MAKER'): Promise<{
    config: MarketMakerConfig | null;
    recentTrades: any[];
    dailyStats: any[];
  }> {
    const config = await this.getConfig(name);
    if (!config) {
      return { config: null, recentTrades: [], dailyStats: [] };
    }

    const [recentTrades, dailyStats] = await Promise.all([
      this.prisma.marketMakerLedger.findMany({
        where: {
          marketMakerId: config.id,
          type: { in: [LedgerType.BUY, LedgerType.SELL] },
        },
        orderBy: { createdAt: 'desc' },
        take: 20,
      }),
      this.prisma.marketMakerDailyStats.findMany({
        where: { marketMakerId: config.id },
        orderBy: { date: 'desc' },
        take: 7,
      }),
    ]);

    return { config, recentTrades, dailyStats };
  }

  /**
   * 获取分类账列表
   */
  async getLedgers(
    name: string,
    options?: {
      type?: LedgerType;
      assetType?: AssetType;
      page?: number;
      pageSize?: number;
    },
  ): Promise<{ data: any[]; total: number }> {
    const config = await this.getConfig(name);
    if (!config) {
      return { data: [], total: 0 };
    }

    const where: any = { marketMakerId: config.id };
    if (options?.type) where.type = options.type;
    if (options?.assetType) where.assetType = options.assetType;

    const page = options?.page ?? 1;
    const pageSize = options?.pageSize ?? 50;

    const [data, total] = await Promise.all([
      this.prisma.marketMakerLedger.findMany({
        where,
        orderBy: { createdAt: 'desc' },
        skip: (page - 1) * pageSize,
        take: pageSize,
      }),
      this.prisma.marketMakerLedger.count({ where }),
    ]);

    return { data, total };
  }

  /**
   * 更新配置
   */
  async updateConfig(
    name: string,
    updates: {
      maxBuyRatio?: number;
      minIntervalMs?: number;
      maxIntervalMs?: number;
      priceStrategy?: string;
      discountRate?: number;
      kavaWalletAddress?: string;
      eusdtWalletAddress?: string;
    },
  ): Promise<MarketMakerConfig | null> {
    const config = await this.getConfig(name);
    if (!config) {
      throw new Error(`Market maker ${name} not found`);
    }

    await this.prisma.marketMakerConfig.update({
      where: { id: config.id },
      data: updates,
    });

    return this.getConfig(name);
  }

  // ============ 双边挂单（深度做市）相关方法 ============

  /**
   * 启动挂单模式（双边深度）
   * 注意：与吃单模式互斥，启动挂单模式会自动停止吃单模式
   */
  async startMaker(name: string = 'MAIN_MARKET_MAKER'): Promise<void> {
    const configRecord = await this.prisma.marketMakerConfig.findUnique({
      where: { name },
    });
    if (!configRecord) {
      throw new Error(`Market maker ${name} not found`);
    }

    if (this.isMakerRunning) {
      this.logger.warn('Maker mode is already running');
      return;
    }

    // 互斥：如果吃单模式正在运行，先停止它
    if (this.isRunning) {
      this.logger.log('Stopping taker mode before starting maker mode (mutual exclusion)');
      await this.stop(name);
    }

    await this.prisma.marketMakerConfig.update({
      where: { id: configRecord.id },
      data: { makerEnabled: true, isActive: false },
    });

    this.isMakerRunning = true;
    this.logger.log(`Market maker ${name} maker mode started`);

    // 立即刷新一次挂单
    await this.refreshMakerOrders(name);

    // 开始定时刷新循环
    this.scheduleMakerRefresh(name, configRecord.refreshIntervalMs);
  }

  /**
   * 停止挂单模式
   */
  async stopMaker(name: string = 'MAIN_MARKET_MAKER'): Promise<void> {
    const configRecord = await this.prisma.marketMakerConfig.findUnique({
      where: { name },
    });
    if (!configRecord) {
      throw new Error(`Market maker ${name} not found`);
    }

    if (this.makerTimeoutId) {
      clearTimeout(this.makerTimeoutId);
      this.makerTimeoutId = null;
    }

    this.isMakerRunning = false;

    // 取消所有做市商挂单
    await this.cancelAllMakerOrders(name);

    await this.prisma.marketMakerConfig.update({
      where: { id: configRecord.id },
      data: { makerEnabled: false },
    });

    this.logger.log(`Market maker ${name} maker mode stopped`);
  }

  /**
   * 刷新双边挂单
   */
  async refreshMakerOrders(name: string = 'MAIN_MARKET_MAKER'): Promise<{
    success: boolean;
    message: string;
    bidOrders?: number;
    askOrders?: number;
  }> {
    const lockValue = await this.redis.acquireLock(`market-maker:maker:${name}`, 60);
    if (!lockValue) {
      return { success: false, message: 'Another refresh is in progress' };
    }

    try {
      const configRecord = await this.prisma.marketMakerConfig.findUnique({
        where: { name },
      });
      if (!configRecord) {
        return { success: false, message: `Market maker ${name} not found` };
      }

      // 获取当前价格
      const priceInfo = await this.priceService.getCurrentPrice();
      const currentPrice = new Decimal(priceInfo.price);

      if (currentPrice.lte(0)) {
        return { success: false, message: 'Invalid current price' };
      }

      // 获取交易账户余额
      const tradingAccount = await this.accountRepository.findByAccountSequence(configRecord.accountSequence);
      if (!tradingAccount) {
        return { success: false, message: 'Trading account not found' };
      }

      const availableCash = new Decimal(tradingAccount.availableCash.value.toString());
      const availableShares = new Decimal(tradingAccount.availableShares.value.toString());

      // 先取消所有现有的做市商挂单
      await this.cancelAllMakerOrders(name);

      let bidOrdersCreated = 0;
      let askOrdersCreated = 0;

      // 创建买单（Bid）
      if (configRecord.bidEnabled && availableCash.gt(0)) {
        const bidSpread = new Decimal(configRecord.bidSpread.toString());
        const bidLevelSpacing = new Decimal(configRecord.bidLevelSpacing.toString());
        const bidQuantityPerLevel = new Decimal(configRecord.bidQuantityPerLevel.toString());

        for (let level = 1; level <= configRecord.bidLevels; level++) {
          // 价格 = 当前价 * (1 - spread - (level-1) * spacing)
          const priceDiscount = bidSpread.plus(bidLevelSpacing.times(level - 1));
          const bidPrice = currentPrice.times(new Decimal(1).minus(priceDiscount));

          // 计算该档位需要的资金
          const requiredCash = bidPrice.times(bidQuantityPerLevel);

          // 检查资金是否足够
          const remainingCash = availableCash.minus(
            bidPrice.times(bidQuantityPerLevel).times(bidOrdersCreated),
          );
          if (remainingCash.lt(requiredCash)) {
            this.logger.warn(`Insufficient cash for bid level ${level}`);
            break;
          }

          try {
            // 创建买单
            const result = await this.orderService.createOrder(
              configRecord.accountSequence,
              OrderType.BUY,
              bidPrice.toFixed(18),
              bidQuantityPerLevel.toFixed(8),
              OrderSource.MARKET_MAKER,
              `做市商买单 L${level}`,
            );

            // 记录做市商挂单
            await this.prisma.marketMakerOrder.create({
              data: {
                marketMakerId: configRecord.id,
                orderId: result.orderId,
                orderNo: result.orderNo,
                side: 'BID',
                level,
                price: bidPrice,
                quantity: bidQuantityPerLevel,
                remainingQty: bidQuantityPerLevel,
                status: 'ACTIVE',
              },
            });

            bidOrdersCreated++;
          } catch (error) {
            this.logger.error(`Failed to create bid order at level ${level}: ${error}`);
          }
        }
      }

      // 创建卖单（Ask）
      if (configRecord.askEnabled && availableShares.gt(0)) {
        const askSpread = new Decimal(configRecord.askSpread.toString());
        const askLevelSpacing = new Decimal(configRecord.askLevelSpacing.toString());
        const askQuantityPerLevel = new Decimal(configRecord.askQuantityPerLevel.toString());

        for (let level = 1; level <= configRecord.askLevels; level++) {
          // 价格 = 当前价 * (1 + spread + (level-1) * spacing)
          const pricePremium = askSpread.plus(askLevelSpacing.times(level - 1));
          const askPrice = currentPrice.times(new Decimal(1).plus(pricePremium));

          // 检查积分股是否足够
          const usedShares = askQuantityPerLevel.times(askOrdersCreated);
          const remainingShares = availableShares.minus(usedShares);
          if (remainingShares.lt(askQuantityPerLevel)) {
            this.logger.warn(`Insufficient shares for ask level ${level}`);
            break;
          }

          try {
            // 创建卖单
            const result = await this.orderService.createOrder(
              configRecord.accountSequence,
              OrderType.SELL,
              askPrice.toFixed(18),
              askQuantityPerLevel.toFixed(8),
              OrderSource.MARKET_MAKER,
              `做市商卖单 L${level}`,
            );

            // 记录做市商挂单
            await this.prisma.marketMakerOrder.create({
              data: {
                marketMakerId: configRecord.id,
                orderId: result.orderId,
                orderNo: result.orderNo,
                side: 'ASK',
                level,
                price: askPrice,
                quantity: askQuantityPerLevel,
                remainingQty: askQuantityPerLevel,
                status: 'ACTIVE',
              },
            });

            askOrdersCreated++;
          } catch (error) {
            this.logger.error(`Failed to create ask order at level ${level}: ${error}`);
          }
        }
      }

      // 更新最后刷新时间
      await this.prisma.marketMakerConfig.update({
        where: { id: configRecord.id },
        data: { lastRefreshAt: new Date() },
      });

      this.logger.log(
        `Market maker orders refreshed: ${bidOrdersCreated} bids, ${askOrdersCreated} asks`,
      );

      return {
        success: true,
        message: 'Orders refreshed',
        bidOrders: bidOrdersCreated,
        askOrders: askOrdersCreated,
      };
    } catch (error) {
      this.logger.error(`Failed to refresh maker orders: ${error}`);
      return { success: false, message: `Refresh failed: ${error}` };
    } finally {
      await this.redis.releaseLock(`market-maker:maker:${name}`, lockValue);
    }
  }

  /**
   * 取消所有做市商挂单
   */
  async cancelAllMakerOrders(name: string = 'MAIN_MARKET_MAKER'): Promise<number> {
    const configRecord = await this.prisma.marketMakerConfig.findUnique({
      where: { name },
    });
    if (!configRecord) {
      return 0;
    }

    // 查找所有活跃的做市商挂单
    const activeOrders = await this.prisma.marketMakerOrder.findMany({
      where: {
        marketMakerId: configRecord.id,
        status: 'ACTIVE',
      },
    });

    let cancelledCount = 0;

    for (const makerOrder of activeOrders) {
      try {
        // 取消订单
        await this.orderService.cancelOrder(makerOrder.orderNo, configRecord.accountSequence);

        // 更新做市商挂单状态
        await this.prisma.marketMakerOrder.update({
          where: { id: makerOrder.id },
          data: { status: 'CANCELLED' },
        });

        cancelledCount++;
      } catch (error) {
        this.logger.error(`Failed to cancel maker order ${makerOrder.orderNo}: ${error}`);
      }
    }

    this.logger.log(`Cancelled ${cancelledCount} maker orders`);
    return cancelledCount;
  }

  /**
   * 获取深度数据
   */
  async getDepth(levels: number = 10): Promise<DepthData> {
    // 获取所有活跃的买单（按价格从高到低）
    const buyOrders = await this.prisma.order.findMany({
      where: {
        type: 'BUY',
        status: { in: ['PENDING', 'PARTIAL'] },
      },
      orderBy: { price: 'desc' },
    });

    // 获取所有活跃的卖单（按价格从低到高）
    const sellOrders = await this.prisma.order.findMany({
      where: {
        type: 'SELL',
        status: { in: ['PENDING', 'PARTIAL'] },
      },
      orderBy: { price: 'asc' },
    });

    // 聚合买单深度
    const bidMap = new Map<string, Decimal>();
    for (const order of buyOrders) {
      const priceKey = new Decimal(order.price.toString()).toFixed(8);
      const existing = bidMap.get(priceKey) || new Decimal(0);
      bidMap.set(priceKey, existing.plus(new Decimal(order.remainingQuantity.toString())));
    }

    // 聚合卖单深度
    const askMap = new Map<string, Decimal>();
    for (const order of sellOrders) {
      const priceKey = new Decimal(order.price.toString()).toFixed(8);
      const existing = askMap.get(priceKey) || new Decimal(0);
      askMap.set(priceKey, existing.plus(new Decimal(order.remainingQuantity.toString())));
    }

    // 转换为深度格式
    const bids: DepthLevel[] = [];
    let bidTotal = new Decimal(0);
    const bidPrices = Array.from(bidMap.keys()).sort((a, b) => new Decimal(b).minus(new Decimal(a)).toNumber());
    for (const price of bidPrices.slice(0, levels)) {
      const quantity = bidMap.get(price)!;
      bidTotal = bidTotal.plus(quantity);
      bids.push({
        price,
        quantity: quantity.toFixed(8),
        total: bidTotal.toFixed(8),
      });
    }

    const asks: DepthLevel[] = [];
    let askTotal = new Decimal(0);
    const askPrices = Array.from(askMap.keys()).sort((a, b) => new Decimal(a).minus(new Decimal(b)).toNumber());
    for (const price of askPrices.slice(0, levels)) {
      const quantity = askMap.get(price)!;
      askTotal = askTotal.plus(quantity);
      asks.push({
        price,
        quantity: quantity.toFixed(8),
        total: askTotal.toFixed(8),
      });
    }

    return {
      bids,
      asks,
      timestamp: Date.now(),
    };
  }

  /**
   * 更新挂单配置
   */
  async updateMakerConfig(
    name: string,
    updates: {
      bidEnabled?: boolean;
      bidLevels?: number;
      bidSpread?: number;
      bidLevelSpacing?: number;
      bidQuantityPerLevel?: string;
      askEnabled?: boolean;
      askLevels?: number;
      askSpread?: number;
      askLevelSpacing?: number;
      askQuantityPerLevel?: string;
      refreshIntervalMs?: number;
    },
  ): Promise<void> {
    const configRecord = await this.prisma.marketMakerConfig.findUnique({
      where: { name },
    });
    if (!configRecord) {
      throw new Error(`Market maker ${name} not found`);
    }

    await this.prisma.marketMakerConfig.update({
      where: { id: configRecord.id },
      data: updates,
    });

    this.logger.log(`Market maker ${name} maker config updated`);
  }

  /**
   * 获取做市商挂单列表
   */
  async getMakerOrders(
    name: string,
    options?: {
      side?: 'BID' | 'ASK';
      status?: 'ACTIVE' | 'FILLED' | 'CANCELLED';
      page?: number;
      pageSize?: number;
    },
  ): Promise<{ data: any[]; total: number }> {
    const configRecord = await this.prisma.marketMakerConfig.findUnique({
      where: { name },
    });
    if (!configRecord) {
      return { data: [], total: 0 };
    }

    const where: any = { marketMakerId: configRecord.id };
    if (options?.side) where.side = options.side;
    if (options?.status) where.status = options.status;

    const page = options?.page ?? 1;
    const pageSize = options?.pageSize ?? 50;

    const [data, total] = await Promise.all([
      this.prisma.marketMakerOrder.findMany({
        where,
        orderBy: { createdAt: 'desc' },
        skip: (page - 1) * pageSize,
        take: pageSize,
      }),
      this.prisma.marketMakerOrder.count({ where }),
    ]);

    return { data, total };
  }

  /**
   * 调度下一次挂单刷新
   */
  private scheduleMakerRefresh(name: string, intervalMs: number): void {
    if (!this.isMakerRunning) return;

    this.makerTimeoutId = setTimeout(async () => {
      await this.refreshMakerOrders(name);

      // 重新获取配置（可能已被更新）
      const latestConfig = await this.prisma.marketMakerConfig.findUnique({
        where: { name },
      });
      if (latestConfig && latestConfig.makerEnabled) {
        this.scheduleMakerRefresh(name, latestConfig.refreshIntervalMs);
      } else {
        this.isMakerRunning = false;
      }
    }, intervalMs);
  }
}
