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

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

  constructor(private prisma: PrismaService) {}

  // ==================== 导出教师列表 ====================

  async exportTeachers(tenantId: number): Promise<Buffer> {
    const teachers = await this.prisma.teacher.findMany({
      where: { tenantId },
      include: {
        classes: {
          select: { name: true },
        },
      },
      orderBy: { createdAt: 'desc' },
    });

    const workbook = new ExcelJS.Workbook();
    const worksheet = workbook.addWorksheet('教师列表');

    // 设置表头
    worksheet.columns = [
      { header: 'ID', key: 'id', width: 8 },
      { header: '姓名', key: 'name', width: 15 },
      { header: '手机号', key: 'phone', width: 15 },
      { header: '邮箱', key: 'email', width: 25 },
      { header: '登录账号', key: 'loginAccount', width: 15 },
      { header: '负责班级', key: 'classes', width: 20 },
      { header: '授课次数', key: 'lessonCount', width: 10 },
      { header: '状态', key: 'status', width: 10 },
      { header: '创建时间', key: 'createdAt', width: 20 },
    ];

    // 设置表头样式
    worksheet.getRow(1).font = { bold: true };
    worksheet.getRow(1).fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FFE0E0E0' },
    };

    // 添加数据
    teachers.forEach((teacher) => {
      worksheet.addRow({
        id: teacher.id,
        name: teacher.name,
        phone: teacher.phone,
        email: teacher.email || '-',
        loginAccount: teacher.loginAccount,
        classes: teacher.classes.map((c) => c.name).join('、') || '-',
        lessonCount: teacher.lessonCount,
        status: teacher.status === 'ACTIVE' ? '正常' : '停用',
        createdAt: teacher.createdAt.toLocaleDateString('zh-CN'),
      });
    });

    const buffer = await workbook.xlsx.writeBuffer();
    return Buffer.from(buffer);
  }

  // ==================== 导出学生列表 ====================

  async exportStudents(tenantId: number): Promise<Buffer> {
    const students = await this.prisma.student.findMany({
      where: { tenantId },
      include: {
        class: {
          select: { name: true },
        },
      },
      orderBy: [{ classId: 'asc' }, { createdAt: 'asc' }],
    });

    const workbook = new ExcelJS.Workbook();
    const worksheet = workbook.addWorksheet('学生列表');

    // 设置表头
    worksheet.columns = [
      { header: 'ID', key: 'id', width: 8 },
      { header: '姓名', key: 'name', width: 15 },
      { header: '性别', key: 'gender', width: 8 },
      { header: '班级', key: 'className', width: 15 },
      { header: '生日', key: 'birthDate', width: 15 },
      { header: '家长姓名', key: 'parentName', width: 15 },
      { header: '家长电话', key: 'parentPhone', width: 15 },
      { header: '阅读次数', key: 'readingCount', width: 10 },
      { header: '创建时间', key: 'createdAt', width: 20 },
    ];

    // 设置表头样式
    worksheet.getRow(1).font = { bold: true };
    worksheet.getRow(1).fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FFE0E0E0' },
    };

    // 添加数据
    students.forEach((student) => {
      worksheet.addRow({
        id: student.id,
        name: student.name,
        gender: student.gender || '-',
        className: student.class?.name || '-',
        birthDate: student.birthDate
          ? new Date(student.birthDate).toLocaleDateString('zh-CN')
          : '-',
        parentName: student.parentName || '-',
        parentPhone: student.parentPhone || '-',
        readingCount: student.readingCount,
        createdAt: student.createdAt.toLocaleDateString('zh-CN'),
      });
    });

    const buffer = await workbook.xlsx.writeBuffer();
    return Buffer.from(buffer);
  }

  // ==================== 导出授课记录 ====================

  async exportLessons(tenantId: number): Promise<Buffer> {
    const lessons = await this.prisma.lesson.findMany({
      where: { tenantId },
      include: {
        course: {
          select: { name: true, pictureBookName: true },
        },
        class: {
          select: { name: true },
        },
        teacher: {
          select: { name: true },
        },
      },
      orderBy: { createdAt: 'desc' },
    });

    const workbook = new ExcelJS.Workbook();
    const worksheet = workbook.addWorksheet('授课记录');

    // 设置表头
    worksheet.columns = [
      { header: 'ID', key: 'id', width: 8 },
      { header: '课程名称', key: 'courseName', width: 25 },
      { header: '绘本名称', key: 'pictureBookName', width: 20 },
      { header: '授课班级', key: 'className', width: 15 },
      { header: '授课教师', key: 'teacherName', width: 12 },
      { header: '计划时间', key: 'plannedDatetime', width: 18 },
      { header: '开始时间', key: 'startDatetime', width: 18 },
      { header: '结束时间', key: 'endDatetime', width: 18 },
      { header: '实际时长(分钟)', key: 'actualDuration', width: 12 },
      { header: '状态', key: 'status', width: 10 },
    ];

    // 设置表头样式
    worksheet.getRow(1).font = { bold: true };
    worksheet.getRow(1).fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FFE0E0E0' },
    };

    // 状态映射
    const statusMap: Record<string, string> = {
      PLANNED: '已计划',
      IN_PROGRESS: '进行中',
      COMPLETED: '已完成',
      CANCELLED: '已取消',
    };

    // 添加数据
    lessons.forEach((lesson) => {
      worksheet.addRow({
        id: lesson.id,
        courseName: lesson.course?.name || '-',
        pictureBookName: lesson.course?.pictureBookName || '-',
        className: lesson.class?.name || '-',
        teacherName: lesson.teacher?.name || '-',
        plannedDatetime: lesson.plannedDatetime
          ? new Date(lesson.plannedDatetime).toLocaleString('zh-CN')
          : '-',
        startDatetime: lesson.startDatetime
          ? new Date(lesson.startDatetime).toLocaleString('zh-CN')
          : '-',
        endDatetime: lesson.endDatetime
          ? new Date(lesson.endDatetime).toLocaleString('zh-CN')
          : '-',
        actualDuration: lesson.actualDuration || '-',
        status: statusMap[lesson.status] || lesson.status,
      });
    });

    const buffer = await workbook.xlsx.writeBuffer();
    return Buffer.from(buffer);
  }

  // ==================== 导出成长档案（简单文本格式） ====================

  async exportGrowthRecords(tenantId: number, studentId?: number): Promise<Buffer> {
    const where: any = { tenantId };
    if (studentId) {
      where.studentId = studentId;
    }

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

    const workbook = new ExcelJS.Workbook();
    const worksheet = workbook.addWorksheet('成长档案');

    // 设置表头
    worksheet.columns = [
      { header: 'ID', key: 'id', width: 8 },
      { header: '学生姓名', key: 'studentName', width: 15 },
      { header: '班级', key: 'className', width: 15 },
      { header: '标题', key: 'title', width: 25 },
      { header: '内容', key: 'content', width: 50 },
      { header: '记录类型', key: 'recordType', width: 12 },
      { header: '记录日期', key: 'recordDate', width: 15 },
      { header: '创建时间', key: 'createdAt', width: 20 },
    ];

    // 设置表头样式
    worksheet.getRow(1).font = { bold: true };
    worksheet.getRow(1).fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FFE0E0E0' },
    };

    // 添加数据
    records.forEach((record) => {
      worksheet.addRow({
        id: record.id,
        studentName: record.student?.name || '-',
        className: record.class?.name || '-',
        title: record.title,
        content: record.content || '-',
        recordType: record.recordType,
        recordDate: record.recordDate
          ? new Date(record.recordDate).toLocaleDateString('zh-CN')
          : '-',
        createdAt: record.createdAt.toLocaleDateString('zh-CN'),
      });
    });

    const buffer = await workbook.xlsx.writeBuffer();
    return Buffer.from(buffer);
  }
}
