package com.reading.platform.controller.school;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reading.platform.common.annotation.RequireRole;
import com.reading.platform.common.enums.UserRole;
import com.reading.platform.common.response.PageResult;
import com.reading.platform.common.response.Result;
import com.reading.platform.common.security.SecurityUtils;
import com.reading.platform.dto.request.SchedulePlanCreateRequest;
import com.reading.platform.dto.request.ScheduleTemplateApplyRequest;
import com.reading.platform.dto.response.SchedulePlanResponse;
import com.reading.platform.entity.SchedulePlan;
import com.reading.platform.entity.ScheduleTemplate;
import com.reading.platform.service.ScheduleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;

@Tag(name = "学校 - 课表", description = "课表管理接口（学校管理员专用）")
@RestController
@RequestMapping("/api/v1/school/schedules")
@RequiredArgsConstructor
@RequireRole(UserRole.SCHOOL)
public class SchoolScheduleController {

    private final ScheduleService scheduleService;

    @Operation(summary = "获取课表计划")
    @GetMapping
    public Result<PageResult<SchedulePlan>> getSchedulePlans(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "20") int pageSize,
            @RequestParam(required = false) String classId,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
        String tenantId = SecurityUtils.getCurrentTenantId();
        Page<SchedulePlan> page = scheduleService.getSchedulePlans(pageNum, pageSize, tenantId, classId, startDate, endDate);
        return Result.success(PageResult.of(page));
    }

    @Operation(summary = "获取课表（按日期范围）")
    @GetMapping("/timetable")
    public Result<List<SchedulePlanResponse>> getTimetable(
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
            @RequestParam(required = false) String classId) {
        String tenantId = SecurityUtils.getCurrentTenantId();
        List<Map<String, Object>> timetable = scheduleService.getTimetable(tenantId, startDate, endDate, classId);

        List<SchedulePlanResponse> result = new ArrayList<>();
        for (Map<String, Object> item : timetable) {
            SchedulePlanResponse response = new SchedulePlanResponse();
            response.setId(item.get("id") != null ? item.get("id") != null ? item.get("id").toString() : null : null);
            response.setName((String) item.get("name"));
            response.setClassName((String) item.get("className"));
            response.setCourseName((String) item.get("courseName"));
            response.setTeacherName((String) item.get("teacherName"));
            result.add(response);
        }
        return Result.success(result);
    }

    @Operation(summary = "根据 ID 获取课表计划")
    @GetMapping("/{id}")
    public Result<SchedulePlan> getSchedulePlan(@PathVariable String id) {
        return Result.success(scheduleService.getSchedulePlanById(id));
    }

    @Operation(summary = "创建课表计划")
    @PostMapping
    public Result<SchedulePlan> createSchedulePlan(@Valid @RequestBody SchedulePlanCreateRequest plan) {
        String tenantId = SecurityUtils.getCurrentTenantId();
        String userId = SecurityUtils.getCurrentUserId();
        return Result.success(scheduleService.createSchedulePlan(tenantId, userId, plan));
    }

    @Operation(summary = "更新课表计划")
    @PutMapping("/{id}")
    public Result<SchedulePlan> updateSchedulePlan(@PathVariable String id, @RequestBody SchedulePlan plan) {
        return Result.success(scheduleService.updateSchedulePlan(id, plan));
    }

    @Operation(summary = "删除课表计划")
    @DeleteMapping("/{id}")
    public Result<Void> deleteSchedulePlan(@PathVariable String id) {
        scheduleService.deleteSchedulePlan(id);
        return Result.success();
    }

    @Operation(summary = "批量创建排课")
    @PostMapping("/batch")
    public Result<List<SchedulePlan>> batchCreateSchedules(@RequestBody List<SchedulePlanCreateRequest> plans) {
        String tenantId = SecurityUtils.getCurrentTenantId();
        String userId = SecurityUtils.getCurrentUserId();
        return Result.success(scheduleService.batchCreateSchedules(tenantId, userId, plans));
    }

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

    @Operation(summary = "获取课表模板")
    @GetMapping("/templates")
    public Result<PageResult<ScheduleTemplate>> getScheduleTemplates(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "20") int pageSize) {
        String tenantId = SecurityUtils.getCurrentTenantId();
        Page<ScheduleTemplate> page = scheduleService.getScheduleTemplates(pageNum, pageSize, tenantId);
        return Result.success(PageResult.of(page));
    }

    @Operation(summary = "根据 ID 获取课表模板")
    @GetMapping("/templates/{id}")
    public Result<ScheduleTemplate> getScheduleTemplate(@PathVariable String id) {
        return Result.success(scheduleService.getScheduleTemplateById(id));
    }

    @Operation(summary = "创建课表模板")
    @PostMapping("/templates")
    public Result<ScheduleTemplate> createScheduleTemplate(@RequestBody ScheduleTemplate template) {
        String tenantId = SecurityUtils.getCurrentTenantId();
        return Result.success(scheduleService.createScheduleTemplate(tenantId, template));
    }

    @Operation(summary = "更新课表模板")
    @PutMapping("/templates/{id}")
    public Result<ScheduleTemplate> updateScheduleTemplate(@PathVariable String id, @RequestBody ScheduleTemplate template) {
        return Result.success(scheduleService.updateScheduleTemplate(id, template));
    }

    @Operation(summary = "删除课表模板")
    @DeleteMapping("/templates/{id}")
    public Result<Void> deleteScheduleTemplate(@PathVariable String id) {
        scheduleService.deleteScheduleTemplate(id);
        return Result.success();
    }

    @Operation(summary = "应用课表模板")
    @PostMapping("/templates/{id}/apply")
    public Result<List<SchedulePlan>> applyScheduleTemplate(
            @PathVariable String id,
            @Valid @RequestBody ScheduleTemplateApplyRequest request) {
        String tenantId = SecurityUtils.getCurrentTenantId();
        return Result.success(scheduleService.applyScheduleTemplate(tenantId, id, request));
    }
}
