import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Body,
  Param,
  Query,
  UseGuards,
  Request,
  UploadedFile,
  UseInterceptors,
  BadRequestException,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { SchoolService } from './school.service';
import { CreateTeacherDto, UpdateTeacherDto } from './dto/create-teacher.dto';
import { CreateStudentDto, UpdateStudentDto } from './dto/create-student.dto';
import { CreateClassDto, UpdateClassDto } from './dto/create-class.dto';
import { AddClassTeacherDto, UpdateClassTeacherDto, TransferStudentDto } from './dto/class-teacher.dto';
import { CreateScheduleDto, UpdateScheduleDto, QueryScheduleDto, TimetableQueryDto } from './dto/schedule.dto';
import { JwtAuthGuard } from '../common/guards/jwt-auth.guard';
import { RolesGuard } from '../common/guards/roles.guard';
import { Roles } from '../common/decorators/roles.decorator';
import { LogOperation } from '../common/decorators/log-operation.decorator';
import { LogInterceptor } from '../common/interceptors/log.interceptor';

@Controller('school')
@UseGuards(JwtAuthGuard, RolesGuard)
@UseInterceptors(LogInterceptor)
@Roles('school')
export class SchoolController {
  constructor(private readonly schoolService: SchoolService) {}

  // ==================== 教师管理 ====================

  @Get('teachers')
  findTeachers(@Request() req: any, @Query() query: any) {
    return this.schoolService.findTeachers(req.user.tenantId, query);
  }

  @Get('teachers/:id')
  findTeacher(@Request() req: any, @Param('id') id: string) {
    return this.schoolService.findTeacher(req.user.tenantId, +id);
  }

  @Post('teachers')
  createTeacher(@Request() req: any, @Body() dto: CreateTeacherDto) {
    return this.schoolService.createTeacher(req.user.tenantId, dto);
  }

  @Put('teachers/:id')
  updateTeacher(
    @Request() req: any,
    @Param('id') id: string,
    @Body() dto: UpdateTeacherDto,
  ) {
    return this.schoolService.updateTeacher(req.user.tenantId, +id, dto);
  }

  @Delete('teachers/:id')
  deleteTeacher(@Request() req: any, @Param('id') id: string) {
    return this.schoolService.deleteTeacher(req.user.tenantId, +id);
  }

  @Post('teachers/:id/reset-password')
  resetTeacherPassword(@Request() req: any, @Param('id') id: string) {
    return this.schoolService.resetTeacherPassword(req.user.tenantId, +id);
  }

  // ==================== 学生管理 ====================

  @Get('students')
  findStudents(@Request() req: any, @Query() query: any) {
    return this.schoolService.findStudents(req.user.tenantId, query);
  }

  @Get('students/:id')
  findStudent(@Request() req: any, @Param('id') id: string) {
    return this.schoolService.findStudent(req.user.tenantId, +id);
  }

  @Post('students')
  createStudent(@Request() req: any, @Body() dto: CreateStudentDto) {
    return this.schoolService.createStudent(req.user.tenantId, dto);
  }

  @Put('students/:id')
  updateStudent(
    @Request() req: any,
    @Param('id') id: string,
    @Body() dto: UpdateStudentDto,
  ) {
    return this.schoolService.updateStudent(req.user.tenantId, +id, dto);
  }

  @Delete('students/:id')
  deleteStudent(@Request() req: any, @Param('id') id: string) {
    return this.schoolService.deleteStudent(req.user.tenantId, +id);
  }

  // ==================== 学生调班 ====================

  @Post('students/:id/transfer')
  transferStudent(
    @Request() req: any,
    @Param('id') id: string,
    @Body() dto: TransferStudentDto,
  ) {
    return this.schoolService.transferStudent(req.user.tenantId, +id, dto);
  }

  @Get('students/:id/history')
  getStudentClassHistory(@Request() req: any, @Param('id') id: string) {
    return this.schoolService.getStudentClassHistory(req.user.tenantId, +id);
  }

  @Post('students/import')
  @UseInterceptors(FileInterceptor('file'))
  async importStudents(
    @Request() req: any,
    @UploadedFile() file: Express.Multer.File,
    @Query('defaultClassId') defaultClassId?: string,
  ) {
    if (!file) {
      throw new BadRequestException('请上传文件');
    }

    const studentsData = await this.schoolService.parseStudentImportFile(file);
    return this.schoolService.importStudents(
      req.user.tenantId,
      studentsData,
      defaultClassId ? +defaultClassId : undefined,
    );
  }

  @Get('students/import/template')
  getImportTemplate() {
    return {
      headers: ['姓名', '性别', '出生日期', '班级ID', '家长姓名', '家长电话'],
      example: ['张小明', '男', '2020-01-15', '1', '张三', '13800138000'],
      notes: [
        '姓名为必填项',
        '性别可选：男/女，默认为男',
        '出生日期格式：YYYY-MM-DD',
        '班级ID为必填项，可在班级管理中查看',
        '家长姓名和家长电话为选填项',
      ],
    };
  }

  // ==================== 班级管理 ====================

  @Get('classes')
  findClasses(@Request() req: any) {
    return this.schoolService.findClasses(req.user.tenantId);
  }

  @Get('classes/:id')
  findClass(@Request() req: any, @Param('id') id: string) {
    return this.schoolService.findClass(req.user.tenantId, +id);
  }

  @Get('classes/:id/students')
  findClassStudents(
    @Request() req: any,
    @Param('id') id: string,
    @Query() query: any,
  ) {
    return this.schoolService.findClassStudents(req.user.tenantId, +id, query);
  }

  @Post('classes')
  createClass(@Request() req: any, @Body() dto: CreateClassDto) {
    return this.schoolService.createClass(req.user.tenantId, dto);
  }

  @Put('classes/:id')
  updateClass(
    @Request() req: any,
    @Param('id') id: string,
    @Body() dto: UpdateClassDto,
  ) {
    return this.schoolService.updateClass(req.user.tenantId, +id, dto);
  }

  @Delete('classes/:id')
  deleteClass(@Request() req: any, @Param('id') id: string) {
    return this.schoolService.deleteClass(req.user.tenantId, +id);
  }

  // ==================== 班级教师管理 ====================

  @Get('classes/:id/teachers')
  findClassTeachers(@Request() req: any, @Param('id') id: string) {
    return this.schoolService.findClassTeachers(req.user.tenantId, +id);
  }

  @Post('classes/:id/teachers')
  addClassTeacher(
    @Request() req: any,
    @Param('id') id: string,
    @Body() dto: AddClassTeacherDto,
  ) {
    return this.schoolService.addClassTeacher(req.user.tenantId, +id, dto);
  }

  @Put('classes/:id/teachers/:teacherId')
  updateClassTeacher(
    @Request() req: any,
    @Param('id') id: string,
    @Param('teacherId') teacherId: string,
    @Body() dto: UpdateClassTeacherDto,
  ) {
    return this.schoolService.updateClassTeacher(
      req.user.tenantId,
      +id,
      +teacherId,
      dto,
    );
  }

  @Delete('classes/:id/teachers/:teacherId')
  removeClassTeacher(
    @Request() req: any,
    @Param('id') id: string,
    @Param('teacherId') teacherId: string,
  ) {
    return this.schoolService.removeClassTeacher(req.user.tenantId, +id, +teacherId);
  }

  // ==================== 家长管理 ====================

  @Get('parents')
  findParents(@Request() req: any, @Query() query: any) {
    return this.schoolService.findParents(req.user.tenantId, query);
  }

  @Get('parents/:id')
  findParent(@Request() req: any, @Param('id') id: string) {
    return this.schoolService.findParent(req.user.tenantId, +id);
  }

  @Post('parents')
  createParent(@Request() req: any, @Body() dto: any) {
    return this.schoolService.createParent(req.user.tenantId, dto);
  }

  @Put('parents/:id')
  updateParent(@Request() req: any, @Param('id') id: string, @Body() dto: any) {
    return this.schoolService.updateParent(req.user.tenantId, +id, dto);
  }

  @Delete('parents/:id')
  deleteParent(@Request() req: any, @Param('id') id: string) {
    return this.schoolService.deleteParent(req.user.tenantId, +id);
  }

  @Post('parents/:id/reset-password')
  resetParentPassword(@Request() req: any, @Param('id') id: string) {
    return this.schoolService.resetParentPassword(req.user.tenantId, +id);
  }

  @Post('parents/:parentId/children/:studentId')
  addChildToParent(
    @Request() req: any,
    @Param('parentId') parentId: string,
    @Param('studentId') studentId: string,
    @Body() body: { relationship: string },
  ) {
    return this.schoolService.addChildToParent(
      req.user.tenantId,
      +parentId,
      +studentId,
      body.relationship,
    );
  }

  @Delete('parents/:parentId/children/:studentId')
  removeChildFromParent(
    @Request() req: any,
    @Param('parentId') parentId: string,
    @Param('studentId') studentId: string,
  ) {
    return this.schoolService.removeChildFromParent(req.user.tenantId, +parentId, +studentId);
  }

  // ==================== 课程管理 ====================

  @Get('courses')
  findCourses(@Request() req: any) {
    return this.schoolService.findCourses(req.user.tenantId);
  }

  @Get('courses/:id')
  findCourse(@Request() req: any, @Param('id') id: string) {
    return this.schoolService.findCourse(req.user.tenantId, +id);
  }

  // ==================== 排课管理 ====================

  @Get('schedules')
  findSchedules(@Request() req: any, @Query() query: QueryScheduleDto) {
    return this.schoolService.findSchedules(req.user.tenantId, query);
  }

  @Get('schedules/timetable')
  getTimetable(@Request() req: any, @Query() query: TimetableQueryDto) {
    return this.schoolService.getTimetable(req.user.tenantId, query);
  }

  @Get('schedules/:id')
  findSchedule(@Request() req: any, @Param('id') id: string) {
    return this.schoolService.findSchedule(req.user.tenantId, +id);
  }

  @Post('schedules')
  @LogOperation({ module: '排课管理', action: '创建排课', description: '创建新的课程排期' })
  createSchedule(@Request() req: any, @Body() dto: CreateScheduleDto) {
    return this.schoolService.createSchedule(req.user.tenantId, dto, req.user.userId);
  }

  @Put('schedules/:id')
  updateSchedule(
    @Request() req: any,
    @Param('id') id: string,
    @Body() dto: UpdateScheduleDto,
  ) {
    return this.schoolService.updateSchedule(req.user.tenantId, +id, dto);
  }

  @Delete('schedules/:id')
  cancelSchedule(@Request() req: any, @Param('id') id: string) {
    return this.schoolService.cancelSchedule(req.user.tenantId, +id);
  }

  @Post('schedules/batch')
  @LogOperation({ module: '排课管理', action: '批量创建排课', description: '批量创建课程排期' })
  batchCreateSchedules(@Request() req: any, @Body() dto: { schedules: any[] }) {
    return this.schoolService.batchCreateSchedules(req.user.tenantId, dto.schedules);
  }

  // ==================== 排课模板 ====================

  @Get('schedule-templates')
  getScheduleTemplates(@Request() req: any, @Query() query: any) {
    return this.schoolService.getScheduleTemplates(req.user.tenantId, query);
  }

  @Get('schedule-templates/:id')
  getScheduleTemplate(@Request() req: any, @Param('id') id: string) {
    return this.schoolService.getScheduleTemplate(req.user.tenantId, +id);
  }

  @Post('schedule-templates')
  createScheduleTemplate(@Request() req: any, @Body() dto: any) {
    return this.schoolService.createScheduleTemplate(req.user.tenantId, dto);
  }

  @Put('schedule-templates/:id')
  updateScheduleTemplate(@Request() req: any, @Param('id') id: string, @Body() dto: any) {
    return this.schoolService.updateScheduleTemplate(req.user.tenantId, +id, dto);
  }

  @Delete('schedule-templates/:id')
  deleteScheduleTemplate(@Request() req: any, @Param('id') id: string) {
    return this.schoolService.deleteScheduleTemplate(req.user.tenantId, +id);
  }

  @Post('schedule-templates/:id/apply')
  applyScheduleTemplate(@Request() req: any, @Param('id') id: string, @Body() dto: any) {
    return this.schoolService.applyScheduleTemplate(req.user.tenantId, +id, dto);
  }
}
