import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { MerchantAccount } from '@/entities/merchant-account.entity';
import { MerchantTransaction } from '@/entities/merchant-transaction.entity';

@Injectable()
export class MerchantFinanceService {
  constructor(
    @InjectRepository(MerchantAccount)
    private merchantAccountRepo: Repository<MerchantAccount>,
    @InjectRepository(MerchantTransaction)
    private merchantTransactionRepo: Repository<MerchantTransaction>,
  ) {}

  async getMerchantAccount(merchantId: number) {
    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 {
      id: account.id,
      balance: Number(account.balance),
      frozenAmount: Number(account.frozen_balance),
      availableAmount: Number(account.balance) - Number(account.frozen_balance),
      totalIncome: Number(account.total_income),
      totalExpense: Number(account.total_expense),
      totalSettlement: Number(account.total_settlement),
      totalWithdraw: Number(account.total_withdraw),
      pendingSettlement: Number(account.pending_settlement),
      debtAmount: Number(account.debt_amount),
      status: account.status,
      lastSettlementAt: account.last_settlement_at,
    };
  }

  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.merchant_id = :merchantId', { merchantId });
    }

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

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

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

    if (businessType) {
      queryBuilder.andWhere('t.business_type = :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),
        balance_before: Number(item.balance_before),
        balance_after: Number(item.balance_after)
      })),
      total,
      page,
      pageSize,
      totalPages: Math.ceil(total / pageSize)
    };
  }

  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.merchant_id = :merchantId', { merchantId });
    }

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

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

    if (transactionType) {
      queryBuilder.andWhere('t.transaction_type = :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);
  }
}
