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

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

  constructor(private prisma: PrismaService) {}

  // ==================== 孩子信息 ====================

  async getChildren(parentId: number, tenantId: number) {
    const parent = await this.prisma.parent.findFirst({
      where: { id: parentId, tenantId },
      include: {
        children: {
          include: {
            student: {
              include: {
                class: {
                  select: {
                    id: true,
                    name: true,
                    grade: true,
                  },
                },
              },
            },
          },
        },
      },
    });

    if (!parent) {
      throw new NotFoundException('家长不存在');
    }

    return parent.children.map((c) => ({
      id: c.student.id,
      name: c.student.name,
      gender: c.student.gender,
      birthDate: c.student.birthDate,
      relationship: c.relationship,
      class: c.student.class,
      readingCount: c.student.readingCount,
      lessonCount: c.student.lessonCount,
    }));
  }

  async getChildProfile(parentId: number, studentId: number, tenantId: number) {
    // 验证亲子关系
    const relation = await this.prisma.parentStudent.findFirst({
      where: { parentId, studentId },
    });

    if (!relation) {
      throw new ForbiddenException('您没有查看该学生信息的权限');
    }

    const student = await this.prisma.student.findFirst({
      where: { id: studentId, tenantId },
      include: {
        class: {
          select: {
            id: true,
            name: true,
            grade: true,
          },
        },
      },
    });

    if (!student) {
      throw new NotFoundException('学生不存在');
    }

    // 获取统计数据
    const [lessonRecords, growthRecords, taskCompletions] = await Promise.all([
      this.prisma.studentRecord.count({
        where: { studentId },
      }),
      this.prisma.growthRecord.count({
        where: { studentId },
      }),
      this.prisma.taskCompletion.count({
        where: {
          studentId,
          status: 'COMPLETED',
        },
      }),
    ]);

    return {
      ...student,
      stats: {
        lessonRecords,
        growthRecords,
        taskCompletions,
      },
    };
  }

  // ==================== 阅读记录 ====================

  async getChildLessons(parentId: number, studentId: number, tenantId: number, query: any) {
    // 验证亲子关系
    const relation = await this.prisma.parentStudent.findFirst({
      where: { parentId, studentId },
    });

    if (!relation) {
      throw new ForbiddenException('您没有查看该学生信息的权限');
    }

    const { page = 1, pageSize = 10 } = query;
    const skip = (page - 1) * pageSize;
    const take = +pageSize;

    const where = { studentId };

    const [items, total] = await Promise.all([
      this.prisma.studentRecord.findMany({
        where,
        skip,
        take,
        orderBy: { createdAt: 'desc' },
        include: {
          lesson: {
            select: {
              id: true,
              startDatetime: true,
              endDatetime: true,
              actualDuration: true,
              course: {
                select: {
                  id: true,
                  name: true,
                  pictureBookName: true,
                },
              },
            },
          },
        },
      }),
      this.prisma.studentRecord.count({ where }),
    ]);

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

  // ==================== 任务列表 ====================

  async getChildTasks(parentId: number, studentId: number, tenantId: number, query: any) {
    // 验证亲子关系
    const relation = await this.prisma.parentStudent.findFirst({
      where: { parentId, studentId },
    });

    if (!relation) {
      throw new ForbiddenException('您没有查看该学生信息的权限');
    }

    const { page = 1, pageSize = 10, status } = query;
    const skip = (page - 1) * pageSize;
    const take = +pageSize;

    const where: any = {
      studentId,
      task: { tenantId, status: 'PUBLISHED' },
    };

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

    const [items, total] = await Promise.all([
      this.prisma.taskCompletion.findMany({
        where,
        skip,
        take,
        orderBy: { task: { createdAt: 'desc' } },
        include: {
          task: {
            select: {
              id: true,
              title: true,
              description: true,
              taskType: true,
              startDate: true,
              endDate: true,
              course: {
                select: {
                  id: true,
                  name: true,
                },
              },
            },
          },
        },
      }),
      this.prisma.taskCompletion.count({ where }),
    ]);

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

  // 提交家长反馈
  async submitTaskFeedback(
    parentId: number,
    studentId: number,
    taskId: number,
    tenantId: number,
    feedback: string,
  ) {
    // 验证亲子关系
    const relation = await this.prisma.parentStudent.findFirst({
      where: { parentId, studentId },
    });

    if (!relation) {
      throw new ForbiddenException('您没有操作该学生信息的权限');
    }

    const completion = await this.prisma.taskCompletion.findFirst({
      where: {
        taskId,
        studentId,
        task: { tenantId },
      },
    });

    if (!completion) {
      throw new NotFoundException('任务记录不存在');
    }

    const updated = await this.prisma.taskCompletion.update({
      where: {
        taskId_studentId: { taskId, studentId },
      },
      data: {
        parentFeedback: feedback,
      },
    });

    this.logger.log(`Parent feedback submitted: task=${taskId}, student=${studentId}`);

    return updated;
  }

  // ==================== 成长档案 ====================

  async getChildGrowthRecords(parentId: number, studentId: number, tenantId: number, query: any) {
    // 验证亲子关系
    const relation = await this.prisma.parentStudent.findFirst({
      where: { parentId, studentId },
    });

    if (!relation) {
      throw new ForbiddenException('您没有查看该学生信息的权限');
    }

    const { page = 1, pageSize = 10 } = query;
    const skip = (page - 1) * pageSize;
    const take = +pageSize;

    const where = {
      studentId,
      tenantId,
    };

    const [items, total] = await Promise.all([
      this.prisma.growthRecord.findMany({
        where,
        skip,
        take,
        orderBy: { recordDate: 'desc' },
        include: {
          class: {
            select: {
              id: true,
              name: true,
            },
          },
        },
      }),
      this.prisma.growthRecord.count({ where }),
    ]);

    return {
      items: items.map((item) => ({
        ...item,
        images: item.images ? JSON.parse(item.images) : [],
      })),
      total,
      page: +page,
      pageSize: +pageSize,
    };
  }
}
