import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserTransaction } from '@/entities/user-transaction.entity';
import { MerchantTransaction } from '@/entities/merchant-transaction.entity';
import { PlatformTransaction } from '@/entities/platform-transaction.entity';

@Injectable()
export class TransactionService {
  constructor(
    @InjectRepository(UserTransaction)
    private userTransactionRepo: Repository<UserTransaction>,
    @InjectRepository(MerchantTransaction)
    private merchantTransactionRepo: Repository<MerchantTransaction>,
    @InjectRepository(PlatformTransaction)
    private platformTransactionRepo: Repository<PlatformTransaction>,
  ) {}

  /**
   * 获取用户交易流水列表
   */
  async getUserTransactions(params: {
    userId?: number;
    accountId?: number;
    direction?: 'income' | 'expense';
    transactionType?: string;
    businessType?: string;
    startDate?: string;
    endDate?: string;
    page?: number;
    pageSize?: number;
  }) {
    const {
      userId,
      accountId,
      direction,
      transactionType,
      businessType,
      startDate,
      endDate,
      page = 1,
      pageSize = 20
    } = params;

    const queryBuilder = this.userTransactionRepo.createQueryBuilder('t');

    if (userId !== undefined) {
      queryBuilder.andWhere('t.userId = :userId', { userId });
    }

    if (accountId) {
      queryBuilder.andWhere('t.accountId = :accountId', { accountId });
    }

    if (direction) {
      queryBuilder.andWhere('t.direction = :direction', { direction });
    }

    if (transactionType) {
      queryBuilder.andWhere('t.transactionType = :transactionType', { transactionType });
    }

    if (businessType) {
      queryBuilder.andWhere('t.businessType = :businessType', { businessType });
    }

    if (startDate && endDate) {
      queryBuilder.andWhere('t.created_at BETWEEN :startDate AND :endDate', {
        startDate: `${startDate} 00:00:00`,
        endDate: `${endDate} 23:59:59`
      });
    }

    queryBuilder.orderBy('t.created_at', 'DESC');

    const skip = (page - 1) * pageSize;
    queryBuilder.skip(skip).take(pageSize);

    const [list, total] = await queryBuilder.getManyAndCount();

    return {
      list: list.map(item => ({
        ...item,
        amount: Number(item.amount),
        balanceBefore: Number(item.balance_before),
        balanceAfter: Number(item.balance_after)
      })),
      total,
      page,
      pageSize,
      totalPages: Math.ceil(total / pageSize)
    };
  }

  /**
   * 获取商家交易流水列表
   */
  async getMerchantTransactions(params: {
    merchantId?: number;
    accountId?: number;
    direction?: 'income' | 'expense';
    transactionType?: string;
    businessType?: string;
    startDate?: string;
    endDate?: string;
    page?: number;
    pageSize?: number;
  }) {
    const {
      merchantId,
      accountId,
      direction,
      transactionType,
      businessType,
      startDate,
      endDate,
      page = 1,
      pageSize = 20
    } = params;

    const queryBuilder = this.merchantTransactionRepo.createQueryBuilder('t');

    if (merchantId !== undefined) {
      queryBuilder.andWhere('t.merchantId = :merchantId', { merchantId });
    }

    if (accountId) {
      queryBuilder.andWhere('t.accountId = :accountId', { accountId });
    }

    if (direction) {
      queryBuilder.andWhere('t.direction = :direction', { direction });
    }

    if (transactionType) {
      queryBuilder.andWhere('t.transactionType = :transactionType', { transactionType });
    }

    if (businessType) {
      queryBuilder.andWhere('t.businessType = :businessType', { businessType });
    }

    if (startDate && endDate) {
      queryBuilder.andWhere('t.created_at BETWEEN :startDate AND :endDate', {
        startDate: `${startDate} 00:00:00`,
        endDate: `${endDate} 23:59:59`
      });
    }

    queryBuilder.orderBy('t.created_at', 'DESC');

    const skip = (page - 1) * pageSize;
    queryBuilder.skip(skip).take(pageSize);

    const [list, total] = await queryBuilder.getManyAndCount();

    return {
      list: list.map(item => ({
        ...item,
        amount: Number(item.amount),
        balanceBefore: Number(item.balance_before),
        balanceAfter: Number(item.balance_after)
      })),
      total,
      page,
      pageSize,
      totalPages: Math.ceil(total / pageSize)
    };
  }

  /**
   * 获取平台交易流水列表
   */
  async getPlatformTransactions(params: {
    accountId?: number;
    direction?: 'income' | 'expense';
    transactionType?: string;
    businessType?: string;
    startDate?: string;
    endDate?: string;
    page?: number;
    pageSize?: number;
  }) {
    const {
      accountId,
      direction,
      transactionType,
      businessType,
      startDate,
      endDate,
      page = 1,
      pageSize = 20
    } = params;

    const queryBuilder = this.platformTransactionRepo.createQueryBuilder('t');

    if (accountId) {
      queryBuilder.andWhere('t.accountId = :accountId', { accountId });
    }

    if (direction) {
      queryBuilder.andWhere('t.direction = :direction', { direction });
    }

    if (transactionType) {
      queryBuilder.andWhere('t.transactionType = :transactionType', { transactionType });
    }

    if (businessType) {
      queryBuilder.andWhere('t.businessType = :businessType', { businessType });
    }

    if (startDate && endDate) {
      queryBuilder.andWhere('t.created_at BETWEEN :startDate AND :endDate', {
        startDate: `${startDate} 00:00:00`,
        endDate: `${endDate} 23:59:59`
      });
    }

    queryBuilder.orderBy('t.created_at', 'DESC');

    const skip = (page - 1) * pageSize;
    queryBuilder.skip(skip).take(pageSize);

    const [list, total] = await queryBuilder.getManyAndCount();

    return {
      list: list.map(item => ({
        ...item,
        amount: Number(item.amount),
        balanceBefore: Number(item.balance_before),
        balanceAfter: Number(item.balance_after)
      })),
      total,
      page,
      pageSize,
      totalPages: Math.ceil(total / pageSize)
    };
  }

  /**
   * 根据交易流水号查询（跨三个表）
   */
  async getTransactionByNo(transactionNo: string) {
    const userTx = await this.userTransactionRepo.findOne({ where: { transaction_no: transactionNo } });
    if (userTx) {
      return { type: 'user', transaction: userTx };
    }

    const merchantTx = await this.merchantTransactionRepo.findOne({ where: { transaction_no: transactionNo } });
    if (merchantTx) {
      return { type: 'merchant', transaction: merchantTx };
    }

    const platformTx = await this.platformTransactionRepo.findOne({ where: { transaction_no: transactionNo } });
    if (platformTx) {
      return { type: 'platform', transaction: platformTx };
    }

    return null;
  }

  /**
   * 根据业务单号查询用户交易流水
   */
  async getUserTransactionsByBusinessNo(businessNo: string) {
    const transactions = await this.userTransactionRepo.find({
      where: { business_no: businessNo },
      order: { created_at: 'ASC' }
    });

    return transactions.map(item => ({
      ...item,
      amount: Number(item.amount),
      balanceBefore: Number(item.balance_before),
      balanceAfter: Number(item.balance_after)
    }));
  }

  /**
   * 根据业务单号查询商家交易流水
   */
  async getMerchantTransactionsByBusinessNo(businessNo: string) {
    const transactions = await this.merchantTransactionRepo.find({
      where: { business_no: businessNo },
      order: { created_at: 'ASC' }
    });

    return transactions.map(item => ({
      ...item,
      amount: Number(item.amount),
      balanceBefore: Number(item.balance_before),
      balanceAfter: Number(item.balance_after)
    }));
  }

  /**
   * 根据业务单号查询平台交易流水
   */
  async getPlatformTransactionsByBusinessNo(businessNo: string) {
    const transactions = await this.platformTransactionRepo.find({
      where: { business_no: businessNo },
      order: { created_at: 'ASC' }
    });

    return transactions.map(item => ({
      ...item,
      amount: Number(item.amount),
      balanceBefore: Number(item.balance_before),
      balanceAfter: Number(item.balance_after)
    }));
  }

  /**
   * 统计用户交易金额
   */
  async sumUserTransactions(params: {
    userId?: number;
    accountId?: number;
    direction?: 'income' | 'expense';
    transactionType?: string;
    startDate?: string;
    endDate?: string;
  }) {
    const {
      userId,
      accountId,
      direction,
      transactionType,
      startDate,
      endDate
    } = params;

    const queryBuilder = this.userTransactionRepo.createQueryBuilder('t');
    queryBuilder.select('SUM(t.amount)', 'total');

    if (userId !== undefined) {
      queryBuilder.andWhere('t.userId = :userId', { userId });
    }

    if (accountId) {
      queryBuilder.andWhere('t.accountId = :accountId', { accountId });
    }

    if (direction) {
      queryBuilder.andWhere('t.direction = :direction', { direction });
    }

    if (transactionType) {
      queryBuilder.andWhere('t.transactionType = :transactionType', { transactionType });
    }

    if (startDate && endDate) {
      queryBuilder.andWhere('t.created_at BETWEEN :startDate AND :endDate', {
        startDate: `${startDate} 00:00:00`,
        endDate: `${endDate} 23:59:59`
      });
    }

    const result = await queryBuilder.getRawOne();
    return Number(result?.total || 0);
  }

  /**
   * 统计商家交易金额
   */
  async sumMerchantTransactions(params: {
    merchantId?: number;
    accountId?: number;
    direction?: 'income' | 'expense';
    transactionType?: string;
    startDate?: string;
    endDate?: string;
  }) {
    const {
      merchantId,
      accountId,
      direction,
      transactionType,
      startDate,
      endDate
    } = params;

    const queryBuilder = this.merchantTransactionRepo.createQueryBuilder('t');
    queryBuilder.select('SUM(t.amount)', 'total');

    if (merchantId !== undefined) {
      queryBuilder.andWhere('t.merchantId = :merchantId', { merchantId });
    }

    if (accountId) {
      queryBuilder.andWhere('t.accountId = :accountId', { accountId });
    }

    if (direction) {
      queryBuilder.andWhere('t.direction = :direction', { direction });
    }

    if (transactionType) {
      queryBuilder.andWhere('t.transactionType = :transactionType', { transactionType });
    }

    if (startDate && endDate) {
      queryBuilder.andWhere('t.created_at BETWEEN :startDate AND :endDate', {
        startDate: `${startDate} 00:00:00`,
        endDate: `${endDate} 23:59:59`
      });
    }

    const result = await queryBuilder.getRawOne();
    return Number(result?.total || 0);
  }

  /**
   * 统计平台交易金额
   */
  async sumPlatformTransactions(params: {
    accountId?: number;
    direction?: 'income' | 'expense';
    transactionType?: string;
    startDate?: string;
    endDate?: string;
  }) {
    const {
      accountId,
      direction,
      transactionType,
      startDate,
      endDate
    } = params;

    const queryBuilder = this.platformTransactionRepo.createQueryBuilder('t');
    queryBuilder.select('SUM(t.amount)', 'total');

    if (accountId) {
      queryBuilder.andWhere('t.accountId = :accountId', { accountId });
    }

    if (direction) {
      queryBuilder.andWhere('t.direction = :direction', { direction });
    }

    if (transactionType) {
      queryBuilder.andWhere('t.transactionType = :transactionType', { transactionType });
    }

    if (startDate && endDate) {
      queryBuilder.andWhere('t.created_at BETWEEN :startDate AND :endDate', {
        startDate: `${startDate} 00:00:00`,
        endDate: `${endDate} 23:59:59`
      });
    }

    const result = await queryBuilder.getRawOne();
    return Number(result?.total || 0);
  }

  /**
   * 生成唯一交易流水号
   */
  generateTransactionNo(): string {
    const timestamp = Date.now();
    const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
    return `TXN${timestamp}${random}`;
  }
}
