import {
  Controller,
  Get,
  Query,
  UseGuards,
  Request,
  Res,
} from '@nestjs/common';
import { Response } from 'express';
import { ExportService } from './export.service';
import { JwtAuthGuard } from '../common/guards/jwt-auth.guard';
import { RolesGuard } from '../common/guards/roles.guard';
import { Roles } from '../common/decorators/roles.decorator';

@Controller('school')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('school')
export class ExportController {
  constructor(private readonly exportService: ExportService) {}

  @Get('export/lessons')
  async exportLessons(
    @Request() req: any,
    @Query('startDate') startDate?: string,
    @Query('endDate') endDate?: string,
    @Res() res?: Response,
  ) {
    const buffer = await this.exportService.exportLessons(
      req.user.tenantId,
      startDate,
      endDate,
    );

    const filename = `授课记录_${this.getDateRangeFilename(startDate, endDate)}.xlsx`;
    this.sendExcelResponse(res, buffer, filename);
  }

  @Get('export/teacher-stats')
  async exportTeacherStats(
    @Request() req: any,
    @Query('startDate') startDate?: string,
    @Query('endDate') endDate?: string,
    @Res() res?: Response,
  ) {
    const buffer = await this.exportService.exportTeacherStats(
      req.user.tenantId,
      startDate,
      endDate,
    );

    const filename = `教师绩效统计_${this.getDateRangeFilename(startDate, endDate)}.xlsx`;
    this.sendExcelResponse(res, buffer, filename);
  }

  @Get('export/student-stats')
  async exportStudentStats(
    @Request() req: any,
    @Query('classId') classId?: string,
    @Res() res?: Response,
  ) {
    const buffer = await this.exportService.exportStudentStats(
      req.user.tenantId,
      classId ? parseInt(classId, 10) : undefined,
    );

    const filename = `学生统计_${this.formatDate(new Date())}.xlsx`;
    this.sendExcelResponse(res, buffer, filename);
  }

  /**
   * 发送 Excel 响应
   */
  private sendExcelResponse(res: Response, buffer: Buffer, filename: string) {
    res.setHeader(
      'Content-Type',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    );
    res.setHeader(
      'Content-Disposition',
      `attachment; filename="${encodeURIComponent(filename)}"`,
    );
    res.setHeader('Content-Length', buffer.length);
    res.send(buffer);
  }

  /**
   * 生成日期范围文件名
   */
  private getDateRangeFilename(startDate?: string, endDate?: string): string {
    if (startDate && endDate) {
      return `${startDate}_${endDate}`;
    } else if (startDate) {
      return `${startDate}_至今`;
    } else if (endDate) {
      return `至${endDate}`;
    }
    return this.formatDate(new Date());
  }

  /**
   * 格式化日期
   */
  private formatDate(date: Date): string {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}${month}${day}`;
  }
}
