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.*;
import com.reading.platform.dto.response.TaskStatsResponse;
import com.reading.platform.dto.response.TaskStatsByClassResponse;
import com.reading.platform.dto.response.TaskStatsByTypeResponse;
import com.reading.platform.dto.response.MonthlyTaskStatsResponse;
import com.reading.platform.entity.Task;
import com.reading.platform.entity.TaskCompletion;
import com.reading.platform.entity.TaskTemplate;
import com.reading.platform.service.TaskService;
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.web.bind.annotation.*;

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

@Tag(name = "教师 - 任务", description = "任务接口（教师专用）")
@RestController
@RequestMapping("/api/v1/teacher/tasks")
@RequiredArgsConstructor
public class TeacherTaskController {

    private final TaskService taskService;

    @Operation(summary = "创建任务")
    @PostMapping
    public Result<Task> createTask(@Valid @RequestBody TaskCreateRequest request) {
        String tenantId = SecurityUtils.getCurrentTenantId();
        String userId = SecurityUtils.getCurrentUserId();
        return Result.success(taskService.createTask(tenantId, userId, "teacher", request));
    }

    @Operation(summary = "更新任务")
    @PutMapping("/{id}")
    public Result<Task> updateTask(@PathVariable String id, @RequestBody TaskUpdateRequest request) {
        return Result.success(taskService.updateTask(id, request));
    }

    @Operation(summary = "根据 ID 获取任务")
    @GetMapping("/{id}")
    public Result<Task> getTask(@PathVariable String id) {
        return Result.success(taskService.getTaskById(id));
    }

    @Operation(summary = "获取任务分页")
    @GetMapping
    public Result<PageResult<Task>> getTaskPage(
            @RequestParam(value = "page", required = false) Integer pageNum,
            @RequestParam(required = false) Integer pageSize,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) String status) {
        String tenantId = SecurityUtils.getCurrentTenantId();
        Page<Task> page = taskService.getTaskPage(tenantId, pageNum, pageSize, keyword, type, status);
        return Result.success(PageResult.of(page));
    }

    @Operation(summary = "删除任务")
    @DeleteMapping("/{id}")
    public Result<Void> deleteTask(@PathVariable String id) {
        taskService.deleteTask(id);
        return Result.success();
    }

    // ==================== 任务统计 ====================

    @Operation(summary = "获取任务统计数据")
    @GetMapping("/stats")
    public Result<TaskStatsResponse> getStats() {
        String tenantId = SecurityUtils.getCurrentTenantId();
        Map<String, Object> stats = taskService.getTaskStats(tenantId);

        TaskStatsResponse response = new TaskStatsResponse();
        response.setTotalTasks((Integer) stats.get("totalTasks"));
        response.setPublishedTasks((Integer) stats.get("publishedTasks"));
        response.setCompletedTasks((Integer) stats.get("completedTasks"));
        response.setInProgressTasks((Integer) stats.get("inProgressTasks"));
        response.setPendingCount((Integer) stats.get("pendingCount"));
        response.setTotalCompletions((Integer) stats.get("totalCompletions"));
        response.setCompletionRate((Integer) stats.get("completionRate"));

        return Result.success(response);
    }

    @Operation(summary = "按任务类型统计")
    @GetMapping("/stats/by-type")
    public Result<List<TaskStatsByTypeResponse>> getStatsByType() {
        String tenantId = SecurityUtils.getCurrentTenantId();
        Map<String, Object> stats = taskService.getStatsByType(tenantId);

        List<TaskStatsByTypeResponse> result = new ArrayList<>();
        if (stats != null) {
            for (Map.Entry<String, Object> entry : stats.entrySet()) {
                TaskStatsByTypeResponse response = new TaskStatsByTypeResponse();
                response.setType(entry.getKey());
                if (entry.getValue() instanceof Map) {
                    Map<String, Object> typeData = (Map<String, Object>) entry.getValue();
                    response.setTotal(typeData.get("total") != null ? ((Number) typeData.get("total")).intValue() : 0);
                    response.setCompleted(typeData.get("completed") != null ? ((Number) typeData.get("completed")).intValue() : 0);
                    response.setRate(typeData.get("rate") != null ? ((Number) typeData.get("rate")).intValue() : 0);
                }
                result.add(response);
            }
        }
        return Result.success(result);
    }

    @Operation(summary = "按班级统计")
    @GetMapping("/stats/by-class")
    public Result<List<TaskStatsByClassResponse>> getStatsByClass() {
        String tenantId = SecurityUtils.getCurrentTenantId();
        List<Map<String, Object>> stats = taskService.getStatsByClass(tenantId);

        List<TaskStatsByClassResponse> result = new ArrayList<>();
        if (stats != null) {
            for (Map<String, Object> item : stats) {
                TaskStatsByClassResponse response = new TaskStatsByClassResponse();
                response.setClassId(item.get("classId") != null ? item.get("classId").toString() : null);
                response.setClassName((String) item.get("className"));
                response.setGrade((String) item.get("grade"));
                response.setTotal(item.get("total") != null ? ((Number) item.get("total")).intValue() : 0);
                response.setCompleted(item.get("completed") != null ? ((Number) item.get("completed")).intValue() : 0);
                response.setRate(item.get("rate") != null ? ((Number) item.get("rate")).intValue() : 0);
                result.add(response);
            }
        }
        return Result.success(result);
    }

    @Operation(summary = "获取月度统计趋势")
    @GetMapping("/stats/monthly")
    public Result<List<MonthlyTaskStatsResponse>> getMonthlyStats(
            @RequestParam(value = "months", required = false, defaultValue = "6") Integer months) {
        String tenantId = SecurityUtils.getCurrentTenantId();
        List<Map<String, Object>> stats = taskService.getMonthlyStats(tenantId, months);

        List<MonthlyTaskStatsResponse> result = new ArrayList<>();
        if (stats != null) {
            for (Map<String, Object> item : stats) {
                MonthlyTaskStatsResponse response = new MonthlyTaskStatsResponse();
                response.setMonth((String) item.get("month"));
                response.setTasks(item.get("tasks") != null ? ((Number) item.get("tasks")).intValue() : 0);
                response.setCompletions(item.get("completions") != null ? ((Number) item.get("completions")).intValue() : 0);
                response.setCompleted(item.get("completed") != null ? ((Number) item.get("completed")).intValue() : 0);
                result.add(response);
            }
        }
        return Result.success(result);
    }

    @Operation(summary = "获取任务完成情况分页")
    @GetMapping("/{id}/completions")
    public Result<PageResult<TaskCompletion>> getCompletions(
            @PathVariable String id,
            @RequestParam(value = "page", required = false) Integer pageNum,
            @RequestParam(required = false) Integer pageSize,
            @RequestParam(required = false) String status) {
        String tenantId = SecurityUtils.getCurrentTenantId();
        Page<TaskCompletion> page = taskService.getTaskCompletions(tenantId, id, pageNum, pageSize, status);
        return Result.success(PageResult.of(page));
    }

    @Operation(summary = "更新任务完成状态")
    @PutMapping("/{taskId}/completions/{studentId}")
    public Result<TaskCompletion> updateCompletion(
            @PathVariable String taskId,
            @PathVariable String studentId,
            @RequestParam String status,
            @RequestParam(required = false) String feedback) {
        String tenantId = SecurityUtils.getCurrentTenantId();
        return Result.success(taskService.updateTaskCompletion(tenantId, taskId, studentId, status, feedback));
    }

    // ==================== 任务模板（只读） ====================

    @Operation(summary = "获取任务模板列表")
    @GetMapping("/task-templates")
    public Result<PageResult<TaskTemplate>> getTemplates(
            @RequestParam(value = "page", required = false) Integer pageNum,
            @RequestParam(required = false) Integer pageSize,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String type) {
        String tenantId = SecurityUtils.getCurrentTenantId();
        Page<TaskTemplate> page = taskService.getTemplatePage(tenantId, pageNum, pageSize, keyword, type);
        return Result.success(PageResult.of(page));
    }

    @Operation(summary = "根据 ID 获取任务模板")
    @GetMapping("/task-templates/{id}")
    public Result<TaskTemplate> getTemplate(@PathVariable String id) {
        String tenantId = SecurityUtils.getCurrentTenantId();
        return Result.success(taskService.getTemplateById(tenantId, id));
    }

    @Operation(summary = "获取默认模板（按类型）")
    @GetMapping("/task-templates/default/{taskType}")
    public Result<TaskTemplate> getDefaultTemplate(@PathVariable String taskType) {
        String tenantId = SecurityUtils.getCurrentTenantId();
        return Result.success(taskService.getDefaultTemplate(tenantId, taskType));
    }

    @Operation(summary = "从模板创建任务")
    @PostMapping("/from-template")
    public Result<Task> createFromTemplate(@Valid @RequestBody CreateTaskFromTemplateRequest request) {
        String tenantId = SecurityUtils.getCurrentTenantId();
        String userId = SecurityUtils.getCurrentUserId();
        return Result.success(taskService.createTaskFromTemplate(tenantId, userId, "teacher", request));
    }

    @Operation(summary = "获取即将到期任务")
    @GetMapping("/upcoming")
    public Result<PageResult<Task>> getUpcomingTasks(
            @RequestParam(value = "page", required = false) Integer pageNum,
            @RequestParam(required = false) Integer pageSize,
            @RequestParam(required = false) Integer days) {
        String tenantId = SecurityUtils.getCurrentTenantId();
        Page<Task> page = taskService.getUpcomingTasks(tenantId, pageNum, pageSize, days);
        return Result.success(PageResult.of(page));
    }

    @Operation(summary = "发送任务提醒")
    @PostMapping("/{id}/remind")
    public Result<Void> sendReminder(@PathVariable String id) {
        taskService.sendTaskReminder(id);
        return Result.success();
    }

    @Operation(summary = "获取任务完成记录")
    @GetMapping("/{id}/completions/{studentId}")
    public Result<TaskCompletion> getCompletion(@PathVariable String id, @PathVariable String studentId) {
        return Result.success(taskService.getTaskCompletion(id, studentId));
    }

}
