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

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

  constructor(private prisma: PrismaService) {}

  /**
   * 导出授课记录
   */
  async exportLessons(tenantId: number, startDate?: string, endDate?: string) {
    const where: any = {
      tenantId,
      status: 'COMPLETED',
    };

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

    const lessons = await this.prisma.lesson.findMany({
      where,
      orderBy: {
        createdAt: 'desc',
      },
      include: {
        course: {
          select: {
            name: true,
            pictureBookName: true,
            duration: true,
          },
        },
        teacher: {
          select: {
            name: true,
          },
        },
        class: {
          select: {
            name: true,
            grade: true,
          },
        },
      },
    });

    // 转换为 Excel 数据格式
    const data = lessons.map((lesson, index) => ({
      '序号': index + 1,
      '课程名称': lesson.course?.name || '',
      '绘本名称': lesson.course?.pictureBookName || '',
      '授课教师': lesson.teacher?.name || '',
      '班级': lesson.class?.name || '',
      '年级': lesson.class?.grade || '',
      '计划时长(分钟)': lesson.course?.duration || '',
      '实际时长(分钟)': lesson.actualDuration || '',
      '授课日期': lesson.startDatetime
        ? new Date(lesson.startDatetime).toLocaleDateString('zh-CN')
        : '',
      '开始时间': lesson.startDatetime
        ? new Date(lesson.startDatetime).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
        : '',
      '结束时间': lesson.endDatetime
        ? new Date(lesson.endDatetime).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
        : '',
      '状态': this.getStatusText(lesson.status),
      '备注': lesson.completionNote || '',
    }));

    return this.generateExcelBuffer(data, '授课记录');
  }

  /**
   * 导出教师绩效统计
   */
  async exportTeacherStats(tenantId: number, startDate?: string, endDate?: string) {
    // 获取所有教师
    const teachers = await this.prisma.teacher.findMany({
      where: {
        tenantId,
        status: 'ACTIVE',
      },
      select: {
        id: true,
        name: true,
        phone: true,
        email: true,
        lessonCount: true,
        createdAt: true,
      },
    });

    // 构建查询条件
    const lessonWhere: any = {
      tenantId,
      status: 'COMPLETED',
    };

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

    // 获取每个教师的详细统计
    const teacherStats = await Promise.all(
      teachers.map(async (teacher) => {
        // 该时间段内的授课次数
        const periodLessons = await this.prisma.lesson.count({
          where: {
            ...lessonWhere,
            teacherId: teacher.id,
          },
        });

        // 获取反馈统计
        const feedbackWhere: any = {
          teacherId: teacher.id,
        };

        if (startDate || endDate) {
          feedbackWhere.lesson = {
            endDatetime: {},
          };
          if (startDate) feedbackWhere.lesson.endDatetime.gte = new Date(startDate);
          if (endDate) feedbackWhere.lesson.endDatetime.lte = new Date(endDate);
        }

        const feedbacks = await this.prisma.lessonFeedback.findMany({
          where: feedbackWhere,
          select: {
            designQuality: true,
            participation: true,
            goalAchievement: true,
          },
        });

        let avgRating = 0;
        if (feedbacks.length > 0) {
          const totalRating = feedbacks.reduce((sum, f) => {
            const ratings = [f.designQuality, f.participation, f.goalAchievement].filter((r) => r !== null);
            const avg = ratings.length > 0 ? ratings.reduce((s, r) => s + r, 0) / ratings.length : 0;
            return sum + avg;
          }, 0);
          avgRating = Math.round((totalRating / feedbacks.length) * 100) / 100;
        }

        // 获取关联班级数
        const classCount = await this.prisma.classTeacher.count({
          where: {
            teacherId: teacher.id,
          },
        });

        return {
          '教师姓名': teacher.name,
          '联系电话': teacher.phone,
          '邮箱': teacher.email || '',
          '关联班级数': classCount,
          '累计授课次数': teacher.lessonCount,
          '本期授课次数': periodLessons,
          '平均评分': avgRating || '暂无评分',
          '入职日期': new Date(teacher.createdAt).toLocaleDateString('zh-CN'),
        };
      }),
    );

    // 按本期授课次数排序
    teacherStats.sort((a, b) => (b['本期授课次数'] as number) - (a['本期授课次数'] as number));

    // 添加排名
    const dataWithRank = teacherStats.map((item, index) => ({
      '排名': index + 1,
      ...item,
    }));

    return this.generateExcelBuffer(dataWithRank, '教师绩效');
  }

  /**
   * 导出学生统计
   */
  async exportStudentStats(tenantId: number, classId?: number) {
    const where: any = { tenantId };

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

    const students = await this.prisma.student.findMany({
      where,
      include: {
        class: {
          select: {
            name: true,
            grade: true,
          },
        },
      },
      orderBy: {
        createdAt: 'desc',
      },
    });

    const data = students.map((student, index) => ({
      '序号': index + 1,
      '学生姓名': student.name,
      '性别': student.gender === 'MALE' ? '男' : student.gender === 'FEMALE' ? '女' : '',
      '出生日期': student.birthDate
        ? new Date(student.birthDate).toLocaleDateString('zh-CN')
        : '',
      '班级': student.class?.name || '',
      '年级': student.class?.grade || '',
      '家长姓名': student.parentName || '',
      '联系电话': student.parentPhone || '',
      '参与课程数': student.lessonCount,
      '阅读记录数': student.readingCount,
      '入校日期': new Date(student.createdAt).toLocaleDateString('zh-CN'),
    }));

    return this.generateExcelBuffer(data, '学生统计');
  }

  /**
   * 生成 Excel Buffer
   */
  private generateExcelBuffer(data: any[], sheetName: string): Buffer {
    const worksheet = XLSX.utils.json_to_sheet(data);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, sheetName);

    // 设置列宽
    const colWidths = this.calculateColumnWidths(data);
    worksheet['!cols'] = colWidths;

    return XLSX.write(workbook, { type: 'buffer', bookType: 'xlsx' });
  }

  /**
   * 计算列宽
   */
  private calculateColumnWidths(data: any[]): { wch: number }[] {
    if (data.length === 0) return [];

    const headers = Object.keys(data[0]);
    return headers.map((header) => {
      // 计算该列的最大宽度
      let maxWidth = header.length;
      data.forEach((row) => {
        const value = String(row[header] || '');
        maxWidth = Math.max(maxWidth, value.length);
      });
      // 限制最大宽度并添加一些padding
      return { wch: Math.min(maxWidth + 2, 50) };
    });
  }

  /**
   * 状态文本转换
   */
  private getStatusText(status: string): string {
    const statusMap: Record<string, string> = {
      PLANNED: '已计划',
      IN_PROGRESS: '进行中',
      COMPLETED: '已完成',
      CANCELLED: '已取消',
    };
    return statusMap[status] || status;
  }
}
