import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Body,
  Param,
  ParseIntPipe,
  Query,
  UseGuards,
  UsePipes,
  ValidationPipe,
  Request,
  Res,
} from '@nestjs/common';
import type { Response } from 'express';
import { ClassesService } from './classes.service';
import {
  CreateClassDto,
  UpdateClassDto,
  QueryClassDto,
  AddStudentsDto,
  AddTeacherDto,
  QueryClassScheduleDto,
  QueryClassAttendanceSummaryDto,
  BatchImportStudentsDto,
} from './dto/class.dto';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { OperationLogsService } from '../operation-logs/operation-logs.service';
import { logAudit } from '../common/with-audit-log';
import { RequirePermission } from '../auth/decorators/permission.decorator';
import { NotificationsService } from '../notifications/notifications.service';
import { NotificationType } from '../entities/notification.entity';
import { TeacherRoleType } from '../entities';
import * as ExcelJS from 'exceljs';
import { AuthorizationService, CaslAction, SubjectName, AuthenticatedUser } from '../authorization';

interface AuthenticatedRequest {
  user: AuthenticatedUser;
}

const teacherRoleLabels: Record<string, string> = {
  [TeacherRoleType.SUBJECT_TEACHER]: '任课老师',
  [TeacherRoleType.HEAD_TEACHER]: '班主任',
  [TeacherRoleType.LIFE_TEACHER]: '生活老师',
  [TeacherRoleType.ACADEMIC_TEACHER]: '学服老师',
};

@UseGuards(JwtAuthGuard)
@UsePipes(new ValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true }))
@Controller('classes')
export class ClassesController {
  constructor(
    private readonly service: ClassesService,
    private readonly logService: OperationLogsService,
    private readonly notificationsService: NotificationsService,
    private readonly authz: AuthorizationService,
  ) {}

  private canManageAllClasses(req: AuthenticatedRequest): boolean {
    return (
      this.authz.can(req, CaslAction.Manage, SubjectName.Class) ||
      this.authz.can(req, CaslAction.Create, SubjectName.Class) ||
      this.authz.can(req, CaslAction.Update, SubjectName.Class)
    );
  }

  private assertReadAccess(req: AuthenticatedRequest, classId: number) {
    return this.service.assertClassAccess(
      req.user.id,
      classId,
      this.canManageAllClasses(req),
    );
  }

  @Get()
  @RequirePermission('class:view')
  async findAll(@Query() query: QueryClassDto, @Request() req: AuthenticatedRequest) {
    const classIds = await this.service.getAccessibleClassIds(
      req.user.id,
      this.canManageAllClasses(req),
    );
    return this.service.findAll(query, classIds);
  }

  @Get(':id')
  @RequirePermission('class:view')
  async findOne(@Param('id', ParseIntPipe) id: number, @Request() req: AuthenticatedRequest) {
    await this.assertReadAccess(req, +id);
    return this.service.findOne(+id);
  }

  @Get(':id/schedule')
  @RequirePermission('class:view')
  async getSchedule(
    @Param('id', ParseIntPipe) id: number,
    @Query() query: QueryClassScheduleDto,
    @Request() req: AuthenticatedRequest,
  ) {
    await this.assertReadAccess(req, +id);
    return this.service.getSchedule(+id, query);
  }

  @Get(':id/attendance-summary')
  @RequirePermission('class:view')
  async getAttendanceSummary(
    @Param('id', ParseIntPipe) id: number,
    @Query() query: QueryClassAttendanceSummaryDto,
    @Request() req: AuthenticatedRequest,
  ) {
    await this.assertReadAccess(req, +id);
    return this.service.getAttendanceSummary(+id, query);
  }

  @Post()
  @RequirePermission('class:create')
  async create(@Body() dto: CreateClassDto, @Request() req: any) {
    const result = await this.service.create(dto);
    await logAudit(this.logService, req, {
      module: '班级管理', action: '创建班级', targetId: result.id, targetType: 'class', detail: `班级${result.code} ${result.name}`,
    });
    return result;
  }

  /** 批量导入学生到班级（通过钉钉用户ID） */
  @Post(':id/students/import')
  @RequirePermission('class:edit')
  async batchImportStudents(@Param('id', ParseIntPipe) id: number, @Body() dto: BatchImportStudentsDto) {
    return this.service.batchImportStudents(+id, dto.users);
  }

  /** 归档班级 */
  @Put(':id/archive')
  @RequirePermission('class:edit')
  async archive(@Param('id', ParseIntPipe) id: number) {
    return this.service.archive(+id);
  }

  /** 取消归档 */
  @Put(':id/restore')
  @RequirePermission('class:edit')
  async restore(@Param('id', ParseIntPipe) id: number) {
    return this.service.restore(+id);
  }

  @Put(':id')
  @RequirePermission('class:edit')
  async update(@Param('id', ParseIntPipe) id: number, @Body() dto: UpdateClassDto, @Request() req: any) {
    const result = await this.service.update(+id, dto);
    await logAudit(this.logService, req, {
      module: '班级管理', action: '编辑班级', targetId: +id, targetType: 'class', detail: JSON.stringify(dto),
    });
    return result;
  }

  @Delete(':id')
  @RequirePermission('class:delete')
  async remove(@Param('id', ParseIntPipe) id: number, @Request() req: any) {
    const result = await this.service.remove(+id);
    await logAudit(this.logService, req, {
      module: '班级管理', action: '归档班级', targetId: +id, targetType: 'class',
    });
    return result;
  }

  @Delete(':id/permanent')
  @RequirePermission('class:purge')
  async purge(@Param('id', ParseIntPipe) id: number, @Request() req: any) {
    const result = await this.service.purge(+id);
    await logAudit(this.logService, req, {
      module: '班级管理', action: '永久删除班级', targetId: +id, targetType: 'class', detail: '物理删除，不可恢复',
    });
    return result;
  }

  @Get(':id/roster/export')
  @RequirePermission('class:view')
  async exportRoster(
    @Param('id', ParseIntPipe) id: number,
    @Res() res: Response,
    @Request() req: AuthenticatedRequest,
  ) {
    await this.assertReadAccess(req, +id);
    const classEntity = await this.service.findOne(+id);
    const classStudents = await this.service.getStudents(+id);

    const workbook = new ExcelJS.Workbook();
    const ws = workbook.addWorksheet('班级花名册');
    ws.columns = [
      { header: '姓名', key: 'name', width: 15 },
      { header: '学号', key: 'studentNo', width: 15 },
      { header: '加入日期', key: 'joinDate', width: 15 },
      { header: '状态', key: 'status', width: 10 },
    ];
    ws.getRow(1).font = { bold: true };
    ws.getRow(1).fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFE0E0E0' } };

    for (const cs of classStudents) {
      ws.addRow({
        name: cs.student?.name || '',
        studentNo: cs.student?.idNumber || '',
        joinDate: cs.joinDate || '',
        status: cs.status || '',
      });
    }

    res.setHeader(
      'Content-Type',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    );
    res.setHeader(
      'Content-Disposition',
      `attachment; filename=${encodeURIComponent(`班级花名册-${classEntity.name}`)}.xlsx`,
    );
    await workbook.xlsx.write(res);
    res.end();
  }

  @Get(':id/students')
  @RequirePermission('class:view')
  async getStudents(@Param('id', ParseIntPipe) id: number, @Request() req: AuthenticatedRequest) {
    await this.assertReadAccess(req, +id);
    return this.service.getStudents(+id);
  }

  @Post(':id/students')
  @RequirePermission('class:edit')
  async addStudents(@Param('id', ParseIntPipe) id: number, @Body() dto: AddStudentsDto, @Request() req: any) {
    const result = await this.service.addStudents(+id, dto.studentIds);
    await logAudit(this.logService, req, {
      module: '班级管理', action: '添加学生', targetId: +id, targetType: 'class', detail: `新增${result.added}名学生`,
    });
    try {
      const cls = await this.service.findOne(+id);
      if (cls.headTeacherId) {
        void this.notificationsService.create({
          recipientIds: [cls.headTeacherId],
          type: NotificationType.CLASS_CHANGE,
          title: '学员变动',
          content: `班级新增${result.added}名学生`,
        });
      }
    } catch {
      // 通知失败不影响班级新增结果
    }
    return result;
  }

  @Delete(':id/students/:studentId')
  @RequirePermission('class:edit')
  async removeStudent(
    @Param('id', ParseIntPipe) id: number,
    @Param('studentId', ParseIntPipe) studentId: number,
    @Request() req: any,
  ) {
    const result = await this.service.removeStudent(+id, +studentId);
    await logAudit(this.logService, req, {
      module: '班级管理', action: '移除学生', targetId: +id, targetType: 'class', detail: `移除学生${studentId}`,
    });
    return result;
  }

  @Get(':id/teachers')
  @RequirePermission('class:view')
  async getTeachers(@Param('id', ParseIntPipe) id: number, @Request() req: AuthenticatedRequest) {
    await this.assertReadAccess(req, +id);
    return this.service.getTeachers(+id);
  }

  @Post(':id/teachers')
  @RequirePermission('class:edit')
  async addTeacher(@Param('id', ParseIntPipe) id: number, @Body() dto: AddTeacherDto, @Request() req: any) {
    const result = await this.service.addTeacher(+id, dto);
    await logAudit(this.logService, req, {
      module: '班级管理', action: '添加教师', targetId: +id, targetType: 'class', detail: `教师${dto.userId} 角色${dto.roleType}`,
    });
    try {
      void this.notificationsService.create({
        recipientIds: [dto.userId],
        type: NotificationType.CLASS_CHANGE,
        title: '班级分配',
        content: `您已被分配到班级担任${teacherRoleLabels[dto.roleType] ?? dto.roleType}角色`,
      });
    } catch {
      // 通知失败不影响班级分配结果
    }
    return result;
  }

  @Delete(':id/teacher-assignments/:assignmentId')
  @RequirePermission('class:edit')
  async removeTeacherAssignment(
    @Param('id', ParseIntPipe) id: number,
    @Param('assignmentId', ParseIntPipe) assignmentId: number,
    @Request() req: any,
  ) {
    const result = await this.service.removeTeacherAssignment(+id, +assignmentId);
    await logAudit(this.logService, req, {
      module: '班级管理', action: '移除教师角色', targetId: +id, targetType: 'class', detail: `移除教师分配${assignmentId}`,
    });
    return result;
  }

  @Delete(':id/teachers/:userId')
  @RequirePermission('class:edit')
  async removeTeacher(
    @Param('id', ParseIntPipe) id: number,
    @Param('userId', ParseIntPipe) userId: number,
    @Request() req: any,
  ) {
    const result = await this.service.removeTeacher(+id, +userId);
    await logAudit(this.logService, req, {
      module: '班级管理', action: '移除教师', targetId: +id, targetType: 'class', detail: `移除教师${userId}`,
    });
    return result;
  }
}
