package com.reading.platform.controller.teacher;

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.response.MessageResponse;
import com.reading.platform.dto.response.SchedulePlanResponse;
import com.reading.platform.dto.request.SchedulePlanCreateRequest;
import com.reading.platform.dto.request.SchedulePlanUpdateRequest;
import com.reading.platform.entity.SchedulePlan;
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.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Tag(name = "教师 - 课表", description = "教师课表视图")
@RestController
@RequestMapping("/api/v1/teacher/schedules")
@RequiredArgsConstructor
public class TeacherScheduleController {

    private final ScheduleService scheduleService;

    @Operation(summary = "获取教师课表计划")
    @GetMapping
    public Result<PageResult<SchedulePlan>> getSchedulePlans(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "20") int pageSize) {
        String tenantId = SecurityUtils.getCurrentTenantId();
        var page = scheduleService.getSchedulePlans(pageNum, pageSize, tenantId, null);
        return Result.success(PageResult.of(page));
    }

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

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

        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 = "获取今日课表")
    @GetMapping("/today")
    public Result<List<SchedulePlan>> getTodaySchedules() {
        String tenantId = SecurityUtils.getCurrentTenantId();
        var page = scheduleService.getSchedulePlans(1, 50, tenantId, null, LocalDate.now(), LocalDate.now());
        return Result.success(page.getRecords());
    }

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

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

        if (request.getStartDate() != null) {
            plan.setStartDate(request.getStartDate());
        }
        if (request.getEndDate() != null) {
            plan.setEndDate(request.getEndDate());
        }
        if (request.getStartTime() != null) {
            plan.setStartTime(request.getStartTime());
        }
        if (request.getEndTime() != null) {
            plan.setEndTime(request.getEndTime());
        }
        if (request.getStatus() != null) {
            plan.setStatus(request.getStatus());
        }
        if (request.getNote() != null) {
            plan.setNote(request.getNote());
        }

        return Result.success(scheduleService.updateSchedulePlan(id, plan));
    }

    @Operation(summary = "取消课表计划")
    @DeleteMapping("/{id}")
    public Result<MessageResponse> cancelSchedulePlan(@PathVariable String id) {
        scheduleService.deleteSchedulePlan(id);
        return Result.success(MessageResponse.of("取消成功"));
    }

}
