import { Injectable, Logger } from '@nestjs/common';
import { PrismaService } from '@core/database/prisma/prisma.service';

export interface StatsOverview {
  total: {
    count: number;
    open: number;
    inProgress: number;
    resolved: number;
    closed: number;
  };
  today: {
    created: number;
    resolved: number;
    closed: number;
  };
  sla: {
    breached: number;
    breachedRate: number;
  };
  satisfaction: {
    averageRating: number;
    totalRatings: number;
  };
}

export interface StatusDistribution {
  status: string;
  count: number;
  percentage: number;
}

export interface CategoryDistribution {
  categoryId: string;
  categoryName: string;
  count: number;
  percentage: number;
}

export interface TrendData {
  date: string;
  created: number;
  resolved: number;
  closed: number;
}

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

  constructor(private readonly prisma: PrismaService) {}

  /**
   * 获取统计概览
   */
  async getOverview(
    startDate?: Date,
    endDate?: Date,
    region?: string,
    tenantId?: string,
  ): Promise<StatsOverview> {
    const baseWhere: any = {
      deletedAt: null,
    };

    if (region) {
      baseWhere.region = region;
    }
    if (tenantId) {
      baseWhere.tenantId = tenantId;
    }

    // 总计统计
    const [total, open, inProgress, resolved, closed] = await Promise.all([
      this.prisma.ticket.count({ where: baseWhere }),
      this.prisma.ticket.count({ where: { ...baseWhere, status: 'OPEN' } }),
      this.prisma.ticket.count({
        where: {
          ...baseWhere,
          status: { in: ['ASSIGNED', 'IN_PROGRESS', 'PENDING'] },
        },
      }),
      this.prisma.ticket.count({ where: { ...baseWhere, status: 'RESOLVED' } }),
      this.prisma.ticket.count({ where: { ...baseWhere, status: 'CLOSED' } }),
    ]);

    // 今日统计
    const todayStart = new Date();
    todayStart.setHours(0, 0, 0, 0);

    const [todayCreated, todayResolved, todayClosed] = await Promise.all([
      this.prisma.ticket.count({
        where: { ...baseWhere, createdAt: { gte: todayStart } },
      }),
      this.prisma.ticket.count({
        where: { ...baseWhere, resolvedAt: { gte: todayStart } },
      }),
      this.prisma.ticket.count({
        where: { ...baseWhere, closedAt: { gte: todayStart } },
      }),
    ]);

    // SLA 统计
    const [breached, slaTotal] = await Promise.all([
      this.prisma.ticket.count({
        where: { ...baseWhere, slaBreached: true },
      }),
      this.prisma.ticket.count({
        where: { ...baseWhere, slaId: { not: null } },
      }),
    ]);
    const breachedRate = slaTotal > 0 ? (breached / slaTotal) * 100 : 0;

    // 满意度统计
    const satisfactionStats = await this.prisma.ticket.aggregate({
      where: {
        ...baseWhere,
        satisfactionRating: { not: null },
      },
      _avg: { satisfactionRating: true },
      _count: { satisfactionRating: true },
    });

    return {
      total: {
        count: total,
        open,
        inProgress,
        resolved,
        closed,
      },
      today: {
        created: todayCreated,
        resolved: todayResolved,
        closed: todayClosed,
      },
      sla: {
        breached,
        breachedRate: Math.round(breachedRate * 100) / 100,
      },
      satisfaction: {
        averageRating:
          Math.round((satisfactionStats._avg.satisfactionRating || 0) * 100) /
          100,
        totalRatings: satisfactionStats._count.satisfactionRating,
      },
    };
  }

  /**
   * 获取状态分布
   */
  async getStatusDistribution(
    region?: string,
    tenantId?: string,
  ): Promise<StatusDistribution[]> {
    const baseWhere: any = { deletedAt: null };
    if (region) baseWhere.region = region;
    if (tenantId) baseWhere.tenantId = tenantId;

    const statuses = ['OPEN', 'ASSIGNED', 'IN_PROGRESS', 'PENDING', 'RESOLVED', 'CLOSED', 'CANCELLED'];

    const counts = await Promise.all(
      statuses.map(async (status) => ({
        status,
        count: await this.prisma.ticket.count({
          where: { ...baseWhere, status },
        }),
      })),
    );

    const total = counts.reduce((sum, item) => sum + item.count, 0);

    return counts.map((item) => ({
      ...item,
      percentage: total > 0 ? Math.round((item.count / total) * 10000) / 100 : 0,
    }));
  }

  /**
   * 获取分类分布
   */
  async getCategoryDistribution(
    region?: string,
    tenantId?: string,
  ): Promise<CategoryDistribution[]> {
    const baseWhere: any = { deletedAt: null };
    if (region) baseWhere.region = region;
    if (tenantId) baseWhere.tenantId = tenantId;

    const categories = await this.prisma.ticketCategory.findMany({
      where: { isActive: true },
      select: { id: true, name: true },
    });

    const counts = await Promise.all(
      categories.map(async (category) => ({
        categoryId: category.id,
        categoryName: category.name,
        count: await this.prisma.ticket.count({
          where: { ...baseWhere, categoryId: category.id },
        }),
      })),
    );

    const total = counts.reduce((sum, item) => sum + item.count, 0);

    return counts
      .map((item) => ({
        ...item,
        percentage:
          total > 0 ? Math.round((item.count / total) * 10000) / 100 : 0,
      }))
      .sort((a, b) => b.count - a.count);
  }

  /**
   * 获取趋势数据
   */
  async getTrends(
    days: number = 30,
    region?: string,
    tenantId?: string,
  ): Promise<TrendData[]> {
    const baseWhere: any = { deletedAt: null };
    if (region) baseWhere.region = region;
    if (tenantId) baseWhere.tenantId = tenantId;

    const trends: TrendData[] = [];
    const now = new Date();

    for (let i = days - 1; i >= 0; i--) {
      const date = new Date(now);
      date.setDate(date.getDate() - i);
      date.setHours(0, 0, 0, 0);

      const nextDate = new Date(date);
      nextDate.setDate(nextDate.getDate() + 1);

      const [created, resolved, closed] = await Promise.all([
        this.prisma.ticket.count({
          where: {
            ...baseWhere,
            createdAt: { gte: date, lt: nextDate },
          },
        }),
        this.prisma.ticket.count({
          where: {
            ...baseWhere,
            resolvedAt: { gte: date, lt: nextDate },
          },
        }),
        this.prisma.ticket.count({
          where: {
            ...baseWhere,
            closedAt: { gte: date, lt: nextDate },
          },
        }),
      ]);

      trends.push({
        date: date.toISOString().split('T')[0],
        created,
        resolved,
        closed,
      });
    }

    return trends;
  }

  /**
   * 获取处理人工作量统计
   */
  async getAssigneeWorkload(
    assigneeIds?: string[],
    region?: string,
    tenantId?: string,
  ) {
    const baseWhere: any = {
      deletedAt: null,
      assigneeId: { not: null },
    };
    if (region) baseWhere.region = region;
    if (tenantId) baseWhere.tenantId = tenantId;
    if (assigneeIds && assigneeIds.length > 0) {
      baseWhere.assigneeId = { in: assigneeIds };
    }

    const workloads = await this.prisma.ticket.groupBy({
      by: ['assigneeId'],
      where: {
        ...baseWhere,
        status: { in: ['ASSIGNED', 'IN_PROGRESS', 'PENDING'] },
      },
      _count: { id: true },
    });

    return workloads.map((item) => ({
      assigneeId: item.assigneeId,
      activeTickets: item._count.id,
    }));
  }
}
