import { DataSource, Repository } from 'typeorm';
import { ConsultationRequest } from './consultation-request.entity';
import { CreateConsultationRequestDto, UpdateConsultationRequestDto } from './consultation-request.schema';
import { SpamProtectionService } from './spam-protection.service';

export class ConsultationRequestService {
  private repository: Repository<ConsultationRequest>;
  private spamProtectionService: SpamProtectionService;

  constructor(dataSource: DataSource) {
    this.repository = dataSource.getRepository(ConsultationRequest);
    this.spamProtectionService = new SpamProtectionService(dataSource);
  }

  /**
   * 获取客户需求列表（带分页和筛选）
   */
  async getList(
    page: number = 1,
    pageSize: number = 10,
    keyword?: string,
    status?: string
  ): Promise<[ConsultationRequest[], number]> {
    const query = this.repository.createQueryBuilder('request');

    // 关键词搜索
    if (keyword) {
      query.andWhere(
        '(request.customerName LIKE :keyword OR request.companyName LIKE :keyword OR request.projectType LIKE :keyword OR request.projectDescription LIKE :keyword)',
        { keyword: `%${keyword}%` }
      );
    }

    // 状态筛选
    if (status) {
      query.andWhere('request.status = :status', { status });
    }

    // 按创建时间倒序排列
    query.orderBy('request.createdAt', 'DESC');

    // 分页
    const [items, total] = await query
      .skip((page - 1) * pageSize)
      .take(pageSize)
      .getManyAndCount();

    return [items, total];
  }

  /**
   * 根据ID获取单个客户需求
   */
  async getById(id: number): Promise<ConsultationRequest> {
    const request = await this.repository.findOneBy({ id });
    if (!request) {
      throw new Error('客户需求不存在');
    }
    return request;
  }

  /**
   * 创建客户需求（支持游客提交）
   */
  async create(
    data: CreateConsultationRequestDto,
    ipAddress?: string,
    userAgent?: string
  ): Promise<ConsultationRequest> {
    // 反垃圾邮件验证
    if (ipAddress) {
      await this.spamProtectionService.validateSubmission(data, ipAddress);
    }

    // 创建客户需求
    const request = this.repository.create({
      ...data,
      isGuest: data.isGuest ? 1 : 0,
      ipAddress: ipAddress || null,
      userAgent: userAgent || null,
      status: 'pending'
    });

    return this.repository.save(request);
  }

  /**
   * 更新客户需求
   */
  async update(id: number, data: UpdateConsultationRequestDto): Promise<ConsultationRequest> {
    const request = await this.getById(id);

    Object.assign(request, data);
    return this.repository.save(request);
  }

  /**
   * 删除客户需求
   */
  async delete(id: number): Promise<boolean> {
    const request = await this.getById(id);
    await this.repository.remove(request);
    return true;
  }

  /**
   * 更新客户需求状态
   */
  async updateStatus(id: number, status: 'pending' | 'processing' | 'completed'): Promise<ConsultationRequest> {
    const request = await this.getById(id);
    request.status = status;
    return this.repository.save(request);
  }

  /**
   * 获取统计数据
   */
  async getStatistics(): Promise<{
    total: number;
    pending: number;
    processing: number;
    completed: number;
    guestSubmissions: number;
  }> {
    const total = await this.repository.count();
    const pending = await this.repository.countBy({ status: 'pending' });
    const processing = await this.repository.countBy({ status: 'processing' });
    const completed = await this.repository.countBy({ status: 'completed' });
    const guestSubmissions = await this.repository.countBy({ isGuest: 1 });

    return {
      total,
      pending,
      processing,
      completed,
      guestSubmissions
    };
  }
}