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

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

  constructor(private prisma: PrismaService) {}

  /**
   * 获取操作日志列表
   */
  async getLogs(tenantId: number | null, query: {
    page?: number;
    pageSize?: number;
    userId?: number;
    userType?: string;
    action?: string;
    module?: string;
    startDate?: string;
    endDate?: string;
  }) {
    const {
      page = 1,
      pageSize = 20,
      userId,
      userType,
      action,
      module,
      startDate,
      endDate,
    } = query;

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

    const where: any = {};

    if (tenantId !== null) {
      where.tenantId = tenantId;
    }

    if (userId) {
      where.userId = userId;
    }

    if (userType) {
      where.userType = userType;
    }

    if (action) {
      where.action = action;
    }

    if (module) {
      where.module = module;
    }

    if (startDate || endDate) {
      where.createdAt = {};
      if (startDate) {
        where.createdAt.gte = new Date(startDate);
      }
      if (endDate) {
        where.createdAt.lte = new Date(endDate);
      }
    }

    const [items, total] = await Promise.all([
      this.prisma.operationLog.findMany({
        where,
        skip,
        take,
        orderBy: { createdAt: 'desc' },
      }),
      this.prisma.operationLog.count({ where }),
    ]);

    return {
      items,
      total,
      page: +page,
      pageSize: +pageSize,
    };
  }

  /**
   * 获取日志详情
   */
  async getLogById(tenantId: number | null, id: number) {
    const where: any = { id };

    if (tenantId !== null) {
      where.tenantId = tenantId;
    }

    const log = await this.prisma.operationLog.findFirst({
      where,
    });

    if (!log) {
      return null;
    }

    // 解析 JSON 字段
    return {
      ...log,
      oldValue: log.oldValue ? this.safeParseJson(log.oldValue) : null,
      newValue: log.newValue ? this.safeParseJson(log.newValue) : null,
    };
  }

  /**
   * 获取模块统计
   */
  async getModuleStats(tenantId: number | null, startDate?: string, endDate?: string) {
    const where: any = {};

    if (tenantId !== null) {
      where.tenantId = tenantId;
    }

    if (startDate || endDate) {
      where.createdAt = {};
      if (startDate) {
        where.createdAt.gte = new Date(startDate);
      }
      if (endDate) {
        where.createdAt.lte = new Date(endDate);
      }
    }

    const logs = await this.prisma.operationLog.findMany({
      where,
      select: {
        module: true,
        action: true,
      },
    });

    // 统计每个模块的操作数
    const moduleStats = new Map<string, number>();
    const actionStats = new Map<string, number>();

    logs.forEach((log) => {
      moduleStats.set(log.module, (moduleStats.get(log.module) || 0) + 1);
      actionStats.set(log.action, (actionStats.get(log.action) || 0) + 1);
    });

    return {
      modules: Array.from(moduleStats.entries())
        .map(([name, count]) => ({ name, count }))
        .sort((a, b) => b.count - a.count),
      actions: Array.from(actionStats.entries())
        .map(([name, count]) => ({ name, count }))
        .sort((a, b) => b.count - a.count),
      total: logs.length,
    };
  }

  /**
   * 安全解析 JSON
   */
  private safeParseJson(str: string): any {
    try {
      return JSON.parse(str);
    } catch {
      return str;
    }
  }
}
