package com.lesingle.edu.controller.teacher;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lesingle.edu.common.annotation.Log;
import com.lesingle.edu.common.enums.LogModule;
import com.lesingle.edu.common.enums.LogOperationType;
import com.lesingle.edu.common.mapper.TaskMapper;
import com.lesingle.edu.common.response.PageResult;
import com.lesingle.edu.common.response.Result;
import com.lesingle.edu.common.security.SecurityUtils;
import com.lesingle.edu.dto.request.TaskCreateRequest;
import com.lesingle.edu.dto.request.TaskFeedbackRequest;
import com.lesingle.edu.dto.request.TaskUpdateRequest;
import com.lesingle.edu.dto.response.TaskCompletionDetailResponse;
import com.lesingle.edu.dto.response.TaskFeedbackResponse;
import com.lesingle.edu.dto.response.TaskResponse;
import com.lesingle.edu.entity.Task;
import com.lesingle.edu.service.TaskFeedbackService;
import com.lesingle.edu.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;

@Tag(name = "教师端 - 任务管理", description = "教师端任务 API")
@RestController
@RequestMapping("/api/v1/teacher/tasks")
@RequiredArgsConstructor
public class TeacherTaskController {

    private final TaskService taskService;
    private final TaskMapper taskMapper;
    private final TaskFeedbackService taskFeedbackService;

    @Operation(summary = "创建任务")
    @Log(module = LogModule.TASK, type = LogOperationType.CREATE, description = "创建任务")
    @PostMapping
    public Result<TaskResponse> createTask(@Valid @RequestBody TaskCreateRequest request) {
        Long tenantId = SecurityUtils.getCurrentTenantId();
        Long userId = SecurityUtils.getCurrentUserId();
        Task task = taskService.createTask(tenantId, userId, "teacher", request);
        return Result.success(taskMapper.toVO(task));
    }

    @Operation(summary = "更新任务")
    @Log(module = LogModule.TASK, type = LogOperationType.UPDATE, description = "更新任务")
    @PutMapping("/{id}")
    public Result<TaskResponse> updateTask(@PathVariable Long id, @RequestBody TaskUpdateRequest request) {
        Task task = taskService.updateTask(id, request);
        return Result.success(taskMapper.toVO(task));
    }

    @Operation(summary = "根据 ID 获取任务")
    @GetMapping("/{id}")
    public Result<TaskResponse> getTask(@PathVariable Long id) {
        Long tenantId = SecurityUtils.getCurrentTenantId();
        TaskResponse detail = taskService.getTaskDetailWithTargets(id, tenantId);
        return Result.success(detail);
    }

    @Operation(summary = "获取任务分页列表")
    @GetMapping
    public Result<PageResult<TaskResponse>> getTaskPage(
            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) String taskType,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        Long tenantId = SecurityUtils.getCurrentTenantId();
        Long teacherId = SecurityUtils.getCurrentUserId();
        String typeFilter = (type != null && !type.isEmpty()) ? type : taskType;
        Page<Task> page = taskService.getTaskPage(tenantId, pageNum, pageSize, keyword, typeFilter, status, teacherId, startDate, endDate);
        List<TaskResponse> voList = taskMapper.toVO(page.getRecords());
        for (int i = 0; i < voList.size(); i++) {
            taskService.enrichTaskResponseWithStats(voList.get(i), page.getRecords().get(i).getId());
        }
        return Result.success(PageResult.of(voList, page.getTotal(), page.getCurrent(), page.getSize()));
    }

    @Operation(summary = "删除任务")
    @Log(module = LogModule.TASK, type = LogOperationType.DELETE, description = "删除任务")
    @DeleteMapping("/{id}")
    public Result<Void> deleteTask(@PathVariable Long id) {
        taskService.deleteTask(id);
        return Result.success();
    }

    // =============== 完成情况与评价 API ===============

    @Operation(summary = "获取任务完成情况列表")
    @GetMapping("/{taskId}/completions")
    public Result<PageResult<TaskCompletionDetailResponse>> getTaskCompletions(
            @PathVariable Long taskId,
            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String status) {
        Long tenantId = SecurityUtils.getCurrentTenantId();
        PageResult<TaskCompletionDetailResponse> result = taskService.getTaskCompletions(taskId, tenantId, pageNum, pageSize, status);
        return Result.success(result);
    }

    @Operation(summary = "获取提交详情")
    @GetMapping("/completions/{completionId}")
    public Result<TaskCompletionDetailResponse> getCompletionDetail(@PathVariable Long completionId) {
        Long tenantId = SecurityUtils.getCurrentTenantId();
        TaskCompletionDetailResponse response = taskService.getCompletionDetail(completionId, tenantId);
        return Result.success(response);
    }

    @Operation(summary = "提交评价")
    @Log(module = LogModule.TASK_FEEDBACK, type = LogOperationType.CREATE, description = "提交任务评价")
    @PostMapping("/completions/{completionId}/feedback")
    public Result<TaskFeedbackResponse> submitFeedback(
            @PathVariable Long completionId,
            @Valid @RequestBody TaskFeedbackRequest request) {
        Long teacherId = SecurityUtils.getCurrentUserId();
        TaskFeedbackResponse response = taskFeedbackService.createOrUpdateFeedback(completionId, request, teacherId);
        return Result.success(response);
    }

    @Operation(summary = "修改评价")
    @Log(module = LogModule.TASK_FEEDBACK, type = LogOperationType.UPDATE, description = "修改任务评价")
    @PutMapping("/completions/{completionId}/feedback")
    public Result<TaskFeedbackResponse> updateFeedback(
            @PathVariable Long completionId,
            @Valid @RequestBody TaskFeedbackRequest request) {
        Long teacherId = SecurityUtils.getCurrentUserId();
        TaskFeedbackResponse response = taskFeedbackService.createOrUpdateFeedback(completionId, request, teacherId);
        return Result.success(response);
    }

}
