import { Injectable, Logger, NotFoundException, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, DataSource, Between } from 'typeorm';
import { Cron } from '@nestjs/schedule';
import { Settlement } from '@/entities/settlement.entity';
import { SettlementItem } from '@/entities/settlement-item.entity';
import { Order } from '@/entities/order.entity';
import { AccountService } from './account.service';
import { TransactionService } from './transaction.service';
import dayjs from 'dayjs';

@Injectable()
export class SettlementService {
  private readonly logger = new Logger(SettlementService.name);

  constructor(
    @InjectRepository(Settlement)
    private settlementRepo: Repository<Settlement>,
    @InjectRepository(SettlementItem)
    private settlementItemRepo: Repository<SettlementItem>,
    @InjectRepository(Order)
    private orderRepo: Repository<Order>,
    private accountService: AccountService,
    private transactionService: TransactionService,
    private dataSource: DataSource,
  ) {}

  /**
   * 每周一凌晨2点自动执行周结算
   */
  @Cron('0 2 * * 1')
  async handleWeeklySettlement() {
    this.logger.log('开始执行周结算任务');

    try {
      const lastWeekStart = dayjs().subtract(1, 'week').startOf('week').format('YYYY-MM-DD');
      const lastWeekEnd = dayjs().subtract(1, 'week').endOf('week').format('YYYY-MM-DD');

      this.logger.log(`结算周期：${lastWeekStart} ~ ${lastWeekEnd}`);

      // 检查该周期是否已经结算过
      const existingSettlements = await this.settlementRepo.count({
        where: {
          periodStart: lastWeekStart,
          periodEnd: lastWeekEnd
        }
      });

      if (existingSettlements > 0) {
        this.logger.warn(`该周期 ${lastWeekStart} ~ ${lastWeekEnd} 已经结算过，跳过`);
        throw new BadRequestException(`该周期 ${lastWeekStart} ~ ${lastWeekEnd} 已经结算过，无法重复结算`);
      }

      const orders = await this.orderRepo
        .createQueryBuilder('o')
        .where('o.status = :status', { status: 'completed' })
        .andWhere('o.merchant_id IS NOT NULL')
        .andWhere('o.checkout_at BETWEEN :start AND :end', {
          start: `${lastWeekStart} 00:00:00`,
          end: `${lastWeekEnd} 23:59:59`
        })
        .getMany();

      if (orders.length === 0) {
        this.logger.log('没有需要结算的订单');
        throw new BadRequestException('该周期内没有需要结算的订单');
      }

      const ordersByMerchant = orders.reduce((acc, order) => {
        const merchantId = order.merchantId;
        if (!merchantId || isNaN(merchantId)) {
          this.logger.warn(`订单 ${order.id} 的 merchantId 无效: ${merchantId}`);
          return acc;
        }
        if (!acc[merchantId]) {
          acc[merchantId] = [];
        }
        acc[merchantId].push(order);
        return acc;
      }, {} as Record<number, Order[]>);

      let successCount = 0;
      let failCount = 0;

      for (const [merchantIdStr, merchantOrders] of Object.entries(ordersByMerchant)) {
        const merchantId = Number(merchantIdStr);

        try {
          await this.createSettlement(merchantId, merchantOrders, lastWeekStart, lastWeekEnd);
          this.logger.log(`商家 ${merchantId} 结算完成，订单数：${merchantOrders.length}`);
          successCount++;
        } catch (error) {
          this.logger.error(`商家 ${merchantId} 结算失败：${error.message}`);
          failCount++;
        }
      }

      this.logger.log(`周结算任务执行完成，成功：${successCount}，失败：${failCount}`);
      return { successCount, failCount, totalOrders: orders.length };
    } catch (error) {
      this.logger.error(`周结算任务执行失败：${error.message}`);
      throw error;
    }
  }

  /**
   * 创建结算单
   */
  async createSettlement(
    merchantId: number,
    orders: Order[],
    periodStart: string,
    periodEnd: string
  ) {
    // 检查该商家在该周期是否已经结算过
    const existingSettlement = await this.settlementRepo.findOne({
      where: {
        merchantId,
        periodStart,
        periodEnd
      }
    });

    if (existingSettlement) {
      this.logger.warn(`商家 ${merchantId} 在周期 ${periodStart} ~ ${periodEnd} 已经结算过，跳过`);
      throw new BadRequestException(`商家 ${merchantId} 在该周期已经结算过`);
    }

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

    try {
      const orderCount = orders.length;
      const orderAmount = orders.reduce((sum, o) => sum + Number(o.payAmount || 0), 0);
      const serviceFee = orders.reduce((sum, o) => sum + Number(o.serviceFee || 0), 0);
      const settlementAmount = orderAmount - serviceFee;

      const settlementNo = this.generateSettlementNo();

      const settlement = this.settlementRepo.create({
        settlementNo,
        merchantId,
        periodStart,
        periodEnd,
        orderCount,
        orderAmount,
        serviceFee,
        settlementAmount,
        status: 'settled',
        settledAt: new Date()
      });

      await queryRunner.manager.save(settlement);

      for (const order of orders) {
        const item = this.settlementItemRepo.create({
          settlementId: settlement.id,
          orderId: order.id,
          orderNo: order.orderNo,
          orderAmount: Number(order.payAmount),
          serviceFee: Number(order.serviceFee || 0),
          settlementAmount: Number(order.payAmount) - Number(order.serviceFee || 0)
        });
        await queryRunner.manager.save(item);
      }

      const transactionNo = this.transactionService.generateTransactionNo();

      await this.accountService.addMerchantBalance(
        merchantId,
        settlementAmount,
        transactionNo,
        'settlement',
        settlement.id,
        settlementNo,
        `商家周结算：${periodStart} ~ ${periodEnd}`
      );

      await this.accountService.deductPlatformBalance(
        settlementAmount,
        transactionNo,
        '商家结算',
        'settlement',
        settlement.id,
        settlementNo,
        `商家 ${merchantId} 周结算：${periodStart} ~ ${periodEnd}`
      );

      await queryRunner.commitTransaction();

      return settlement;
    } catch (error) {
      await queryRunner.rollbackTransaction();
      throw error;
    } finally {
      await queryRunner.release();
    }
  }

  /**
   * 获取结算记录列表
   */
  async getSettlements(params: {
    merchantId?: number;
    status?: string;
    startDate?: string;
    endDate?: string;
    page?: number;
    pageSize?: number;
  }) {
    const { merchantId, status, startDate, endDate, page = 1, pageSize = 20 } = params;

    const queryBuilder = this.settlementRepo.createQueryBuilder('s');

    if (merchantId) {
      queryBuilder.andWhere('s.merchant_id = :merchantId', { merchantId });
    }

    if (status) {
      queryBuilder.andWhere('s.status = :status', { status });
    }

    if (startDate && endDate) {
      queryBuilder.andWhere('s.period_start >= :startDate', { startDate });
      queryBuilder.andWhere('s.period_end <= :endDate', { endDate });
    }

    queryBuilder.orderBy('s.created_at', 'DESC');
    queryBuilder.skip((page - 1) * pageSize).take(pageSize);

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

    return {
      list: list.map(item => ({
        ...item,
        orderAmount: Number(item.orderAmount),
        serviceFee: Number(item.serviceFee),
        settlementAmount: Number(item.settlementAmount)
      })),
      total,
      page,
      pageSize,
      totalPages: Math.ceil(total / pageSize)
    };
  }

  /**
   * 获取结算单详情
   */
  async getSettlementDetail(id: number) {
    const settlement = await this.settlementRepo.findOne({ where: { id } });

    if (!settlement) {
      throw new NotFoundException('结算单不存在');
    }

    const items = await this.settlementItemRepo.find({
      where: { settlementId: id },
      order: { createdAt: 'ASC' }
    });

    return {
      ...settlement,
      orderAmount: Number(settlement.orderAmount),
      serviceFee: Number(settlement.serviceFee),
      settlementAmount: Number(settlement.settlementAmount),
      items: items.map(item => ({
        ...item,
        orderAmount: Number(item.orderAmount),
        serviceFee: Number(item.serviceFee),
        settlementAmount: Number(item.settlementAmount)
      }))
    };
  }

  /**
   * 手动生成结算单（管理员操作）
   */
  async manualSettlement(params: {
    merchantId: number;
    periodStart: string;
    periodEnd: string;
  }) {
    const { merchantId, periodStart, periodEnd } = params;

    const orders = await this.orderRepo.find({
      where: {
        merchantId,
        status: 'completed',
        checkoutAt: Between(
          new Date(`${periodStart} 00:00:00`),
          new Date(`${periodEnd} 23:59:59`)
        )
      }
    });

    if (orders.length === 0) {
      throw new NotFoundException('该周期内没有已完成的订单');
    }

    return await this.createSettlement(merchantId, orders, periodStart, periodEnd);
  }

  /**
   * 获取商家待结算金额
   */
  async getPendingSettlementAmount(merchantId: number): Promise<number> {
    const lastSettlement = await this.settlementRepo.findOne({
      where: { merchantId },
      order: { settledAt: 'DESC' }
    });

    const startDate = lastSettlement
      ? dayjs(lastSettlement.periodEnd).add(1, 'day').format('YYYY-MM-DD')
      : '2020-01-01';

    const orders = await this.orderRepo.find({
      where: {
        merchantId,
        status: 'completed',
        checkoutAt: Between(
          new Date(`${startDate} 00:00:00`),
          new Date()
        )
      }
    });

    const orderAmount = orders.reduce((sum, o) => sum + Number(o.payAmount), 0);
    const serviceFee = orders.reduce((sum, o) => sum + Number(o.serviceFee || 0), 0);

    return orderAmount - serviceFee;
  }

  /**
   * 预览周结算数据（不实际执行）
   */
  async previewWeeklySettlement() {
    try {
      const lastWeekStart = dayjs().subtract(1, 'week').startOf('week').format('YYYY-MM-DD');
      const lastWeekEnd = dayjs().subtract(1, 'week').endOf('week').format('YYYY-MM-DD');

      this.logger.log(`预览周结算：${lastWeekStart} ~ ${lastWeekEnd}`);

      // 检查该周期是否已经结算过
      const existingSettlements = await this.settlementRepo.count({
        where: {
          periodStart: lastWeekStart,
          periodEnd: lastWeekEnd
        }
      });

      if (existingSettlements > 0) {
        this.logger.warn(`该周期 ${lastWeekStart} ~ ${lastWeekEnd} 已经结算过`);
        throw new BadRequestException(`该周期 ${lastWeekStart} ~ ${lastWeekEnd} 已经结算过，无法重复结算`);
      }

      // 不使用 join，直接查询订单
      const queryBuilder = this.orderRepo
        .createQueryBuilder('o')
        .where('o.status = :status', { status: 'completed' })
        .andWhere('o.merchant_id IS NOT NULL')
        .andWhere('o.checkout_at BETWEEN :start AND :end', {
          start: `${lastWeekStart} 00:00:00`,
          end: `${lastWeekEnd} 23:59:59`
        });

      // 打印 SQL 语句
      const sql = queryBuilder.getSql();
      this.logger.log(`生成的 SQL: ${sql}`);
      this.logger.log(`参数: ${JSON.stringify(queryBuilder.getParameters())}`);

      const orders = await queryBuilder.getMany();

      this.logger.log(`找到 ${orders.length} 个已完成订单`);

      if (orders.length === 0) {
        throw new BadRequestException('该周期内没有需要结算的订单');
      }

      const ordersByMerchant = orders.reduce((acc, order) => {
        const merchantId = order.merchantId;
        if (!merchantId || isNaN(merchantId)) {
          this.logger.warn(`订单 ${order.id} 的 merchantId 无效: ${merchantId}`);
          return acc;
        }
        if (!acc[merchantId]) {
          acc[merchantId] = [];
        }
        acc[merchantId].push(order);
        return acc;
      }, {} as Record<number, Order[]>);

      // 获取所有商家ID
      const merchantIds = Object.keys(ordersByMerchant).map(id => Number(id));

      // 批量查询商家信息
      const merchantsData = await this.dataSource
        .getRepository('Merchant')
        .createQueryBuilder('m')
        .where('m.id IN (:...ids)', { ids: merchantIds })
        .getMany();

      const merchantMap = new Map(merchantsData.map((m: any) => [m.id, m]));

      const merchants = Object.entries(ordersByMerchant).map(([merchantIdStr, merchantOrders]) => {
        const merchantId = Number(merchantIdStr);
        const merchant = merchantMap.get(merchantId);
        const orderCount = merchantOrders.length;
        const orderAmount = merchantOrders.reduce((sum, o) => sum + Number(o.payAmount || 0), 0);
        const serviceFee = merchantOrders.reduce((sum, o) => sum + Number(o.serviceFee || 0), 0);
        const settlementAmount = orderAmount - serviceFee;

        return {
          merchantId,
          merchantName: merchant?.shopName || '未知商家',
          orderCount,
          orderAmount,
          serviceFee,
          settlementAmount
        };
      });

      const totalAmount = merchants.reduce((sum, m) => sum + m.orderAmount, 0);
      const totalServiceFee = merchants.reduce((sum, m) => sum + m.serviceFee, 0);
      const totalSettlementAmount = merchants.reduce((sum, m) => sum + m.settlementAmount, 0);

      return {
        periodStart: lastWeekStart,
        periodEnd: lastWeekEnd,
        totalOrders: orders.length,
        totalAmount,
        totalServiceFee,
        totalSettlementAmount,
        merchants
      };
    } catch (error) {
      this.logger.error(`预览周结算失败: ${error.message}`);
      this.logger.error(`错误堆栈: ${error.stack}`);
      throw error;
    }
  }

  /**
   * 生成结算单号
   */
  private generateSettlementNo(): string {
    const timestamp = Date.now();
    const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
    return `STL${timestamp}${random}`;
  }
}
