package com.reading.platform.controller.teacher;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.LessonCreateRequest;
import com.reading.platform.dto.request.LessonUpdateRequest;
import com.reading.platform.dto.response.BatchSaveStudentRecordResponse;
import com.reading.platform.dto.response.StudentRecordListResponse;
import com.reading.platform.dto.response.StudentRecordResponse;
import com.reading.platform.entity.Lesson;
import com.reading.platform.entity.LessonFeedback;
import com.reading.platform.entity.StudentRecord;
import com.reading.platform.service.LessonService;
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.*;

@Tag(name = "教师 - 课时", description = "课时接口（教师专用）")
@RestController
@RequestMapping("/api/v1/teacher/lessons")
@RequiredArgsConstructor
public class TeacherLessonController {

    private final LessonService lessonService;

    @Operation(summary = "创建课时")
    @PostMapping
    public Result<Lesson> createLesson(@Valid @RequestBody LessonCreateRequest request) {
        String tenantId = SecurityUtils.getCurrentTenantId();
        return Result.success(lessonService.createLesson(tenantId, request));
    }

    @Operation(summary = "更新课时")
    @PutMapping("/{id}")
    public Result<Lesson> updateLesson(@PathVariable String id, @RequestBody LessonUpdateRequest request) {
        return Result.success(lessonService.updateLesson(id, request));
    }

    @Operation(summary = "根据ID获取课时")
    @GetMapping("/{id}")
    public Result<Lesson> getLesson(@PathVariable String id) {
        return Result.success(lessonService.getLessonById(id));
    }

    @Operation(summary = "获取我的课时")
    @GetMapping
    public Result<PageResult<Lesson>> getMyLessons(
            @RequestParam(value = "page", required = false) Integer pageNum,
            @RequestParam(required = false) Integer pageSize,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
        String teacherId = SecurityUtils.getCurrentUserId();
        Page<Lesson> page = lessonService.getTeacherLessons(teacherId, pageNum, pageSize, status, startDate, endDate);
        return Result.success(PageResult.of(page));
    }

    @Operation(summary = "开始课时")
    @PostMapping("/{id}/start")
    public Result<Void> startLesson(@PathVariable String id) {
        lessonService.startLesson(id);
        return Result.success();
    }

    @Operation(summary = "结束课时")
    @PostMapping("/{id}/finish")
    public Result<Lesson> finishLesson(@PathVariable String id, @RequestBody LessonFinishRequest request) {
        return Result.success(lessonService.finishLesson(id, request.getActualDuration(), request.getOverallRating(), request.getParticipationRating(), request.getCompletionNote()));
    }

    @Operation(summary = "完成课时 (别名接口)")
    @PostMapping("/{id}/complete")
    public Result<Lesson> completeLesson(@PathVariable String id, @RequestBody LessonFinishRequest request) {
        // 调用 finishLesson 方法
        return finishLesson(id, request);
    }

    @Operation(summary = "取消课时")
    @PostMapping("/{id}/cancel")
    public Result<Void> cancelLesson(@PathVariable String id) {
        lessonService.cancelLesson(id);
        return Result.success();
    }

    @Operation(summary = "获取今天课时")
    @GetMapping("/today")
    public Result<List<Lesson>> getTodayLessons() {
        String tenantId = SecurityUtils.getCurrentTenantId();
        return Result.success(lessonService.getTodayLessons(tenantId));
    }

    @Operation(summary = "保存学生评价记录")
    @PostMapping("/{lessonId}/students/{studentId}/record")
    public Result<StudentRecord> saveStudentRecord(
            @PathVariable String lessonId,
            @PathVariable String studentId,
            @RequestBody StudentRecordRequest request) {
        return Result.success(lessonService.saveStudentRecord(lessonId, studentId, request.getFocus(), request.getParticipation(), request.getInterest(), request.getUnderstanding(), request.getNotes()));
    }

    @Operation(summary = "获取课程所有学生记录")
    @GetMapping("/{lessonId}/student-records")
    public Result<StudentRecordListResponse> getStudentRecords(@PathVariable String lessonId) {
        Lesson lesson = lessonService.getLessonById(lessonId);
        List<StudentRecord> records = lessonService.getStudentRecords(lessonId);

        StudentRecordListResponse response = new StudentRecordListResponse();

        StudentRecordListResponse.LessonSimpleInfo lessonInfo = new StudentRecordListResponse.LessonSimpleInfo();
        lessonInfo.setId(lesson.getId());
        lessonInfo.setStatus(lesson.getStatus());
        lessonInfo.setClassName(""); // TODO: 需要关联班级表获取班级名称
        response.setLesson(lessonInfo);

        List<StudentRecordResponse> studentRecords = new ArrayList<>();
        for (StudentRecord record : records) {
            StudentRecordResponse item = new StudentRecordResponse();
            item.setId(record.getId());
            item.setStudentId(record.getStudentId());
            item.setFocus(record.getFocus());
            item.setParticipation(record.getParticipation());
            item.setInterest(record.getInterest());
            item.setUnderstanding(record.getUnderstanding());
            item.setNotes(record.getNotes());
            studentRecords.add(item);
        }
        response.setStudents(studentRecords);

        return Result.success(response);
    }

    @Operation(summary = "批量保存学生评价记录")
    @PostMapping("/{lessonId}/student-records/batch")
    public Result<BatchSaveStudentRecordResponse> batchSaveStudentRecords(
            @PathVariable String lessonId,
            @RequestBody BatchStudentRecordRequest request) {
        int count = lessonService.batchSaveStudentRecords(lessonId, request.getRecords());

        List<StudentRecord> records = lessonService.getStudentRecords(lessonId);
        List<StudentRecordResponse> studentRecords = new ArrayList<>();
        for (StudentRecord record : records) {
            StudentRecordResponse item = new StudentRecordResponse();
            item.setId(record.getId());
            item.setStudentId(record.getStudentId());
            item.setFocus(record.getFocus());
            item.setParticipation(record.getParticipation());
            item.setInterest(record.getInterest());
            item.setUnderstanding(record.getUnderstanding());
            item.setNotes(record.getNotes());
            studentRecords.add(item);
        }

        BatchSaveStudentRecordResponse response = new BatchSaveStudentRecordResponse();
        response.setCount(count);
        response.setRecords(studentRecords);
        return Result.success(response);
    }

    @Operation(summary = "提交课程反馈")
    @PostMapping("/{lessonId}/feedback")
    public Result<LessonFeedback> submitFeedback(
            @PathVariable String lessonId,
            @RequestBody LessonFeedbackRequest request) {
        String tenantId = SecurityUtils.getCurrentTenantId();
        String teacherId = SecurityUtils.getCurrentUserId();
        Map<String, Object> feedbackData = new HashMap<>();
        feedbackData.put("designQuality", request.getDesignQuality());
        feedbackData.put("participation", request.getParticipation());
        feedbackData.put("goalAchievement", request.getGoalAchievement());
        feedbackData.put("stepFeedbacks", request.getStepFeedbacks() != null ? request.getStepFeedbacks().toString() : null);
        feedbackData.put("pros", request.getPros());
        feedbackData.put("suggestions", request.getSuggestions());
        feedbackData.put("activitiesDone", request.getActivitiesDone() != null ? request.getActivitiesDone().toString() : null);
        return Result.success(lessonService.saveLessonFeedback(tenantId, lessonId, teacherId, feedbackData));
    }

    @Operation(summary = "获取课程反馈")
    @GetMapping("/{lessonId}/feedback")
    public Result<LessonFeedback> getFeedback(@PathVariable String lessonId) {
        return Result.success(lessonService.getLessonFeedback(lessonId));
    }

    /**
     * 课程结束请求 DTO
     */
    public static class LessonFinishRequest {
        private Integer actualDuration;
        private String overallRating;
        private String participationRating;
        private String completionNote;

        public Integer getActualDuration() { return actualDuration; }
        public void setActualDuration(Integer actualDuration) { this.actualDuration = actualDuration; }
        public String getOverallRating() { return overallRating; }
        public void setOverallRating(String overallRating) { this.overallRating = overallRating; }
        public String getParticipationRating() { return participationRating; }
        public void setParticipationRating(String participationRating) { this.participationRating = participationRating; }
        public String getCompletionNote() { return completionNote; }
        public void setCompletionNote(String completionNote) { this.completionNote = completionNote; }
    }

    /**
     * 学生记录请求 DTO
     */
    public static class StudentRecordRequest {
        private Integer focus;
        private Integer participation;
        private Integer interest;
        private Integer understanding;
        private String notes;

        public Integer getFocus() { return focus; }
        public void setFocus(Integer focus) { this.focus = focus; }
        public Integer getParticipation() { return participation; }
        public void setParticipation(Integer participation) { this.participation = participation; }
        public Integer getInterest() { return interest; }
        public void setInterest(Integer interest) { this.interest = interest; }
        public Integer getUnderstanding() { return understanding; }
        public void setUnderstanding(Integer understanding) { this.understanding = understanding; }
        public String getNotes() { return notes; }
        public void setNotes(String notes) { this.notes = notes; }
    }

    /**
     * 批量学生记录请求 DTO
     */
    public static class BatchStudentRecordRequest {
        private List<Map<String, Object>> records;

        public List<Map<String, Object>> getRecords() { return records; }
        public void setRecords(List<Map<String, Object>> records) { this.records = records; }
    }

    /**
     * 课程反馈请求 DTO
     */
    public static class LessonFeedbackRequest {
        private Integer designQuality;
        private Integer participation;
        private Integer goalAchievement;
        private Object stepFeedbacks;
        private String pros;
        private String suggestions;
        private Object activitiesDone;

        public Integer getDesignQuality() { return designQuality; }
        public void setDesignQuality(Integer designQuality) { this.designQuality = designQuality; }
        public Integer getParticipation() { return participation; }
        public void setParticipation(Integer participation) { this.participation = participation; }
        public Integer getGoalAchievement() { return goalAchievement; }
        public void setGoalAchievement(Integer goalAchievement) { this.goalAchievement = goalAchievement; }
        public Object getStepFeedbacks() { return stepFeedbacks; }
        public void setStepFeedbacks(Object stepFeedbacks) { this.stepFeedbacks = stepFeedbacks; }
        public String getPros() { return pros; }
        public void setPros(String pros) { this.pros = pros; }
        public String getSuggestions() { return suggestions; }
        public void setSuggestions(String suggestions) { this.suggestions = suggestions; }
        public Object getActivitiesDone() { return activitiesDone; }
        public void setActivitiesDone(Object activitiesDone) { this.activitiesDone = activitiesDone; }
    }

}
