package com.lesingle.edu.controller.parent;

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.TaskCompleteRequest;
import com.lesingle.edu.dto.request.TaskSubmitRequest;
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.dto.response.TaskWithCompletionResponse;
import com.lesingle.edu.entity.Task;
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.annotation.RequireRole;
import com.lesingle.edu.common.enums.ErrorCode;
import com.lesingle.edu.common.enums.UserRole;
import com.lesingle.edu.common.exception.BusinessException;
import com.lesingle.edu.service.ParentAuthService;
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/parent/tasks")
@RequiredArgsConstructor
@RequireRole(UserRole.PARENT)
public class ParentTaskController {

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

    @Operation(summary = "获取任务详情")
    @GetMapping("/{id}")
    public Result<TaskResponse> getTask(@PathVariable Long id) {
        Task task = taskService.getTaskById(id);
        return Result.success(taskMapper.toVO(task));
    }

    @Operation(summary = "获取孩子的任务列表（含完成信息与教师评价）")
    @GetMapping("/student/{studentId}")
    public Result<PageResult<TaskWithCompletionResponse>> getTasksByStudent(
            @PathVariable Long studentId,
            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String status) {
        Long parentId = SecurityUtils.getCurrentUserId();
        parentAuthService.validateParentStudentRelation(parentId, studentId);
        PageResult<TaskWithCompletionResponse> result = taskService.getTasksWithCompletionByStudentId(studentId, pageNum, pageSize, status);
        return Result.success(result);
    }

    @Operation(summary = "获取我的任务列表（聚合多孩子任务）")
    @GetMapping
    public Result<PageResult<TaskWithCompletionResponse>> getMyTasks(
            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String status) {
        Long parentId = SecurityUtils.getCurrentUserId();
        PageResult<TaskWithCompletionResponse> result = taskService.getMyTasksForParent(parentId, pageNum, pageSize, status);
        return Result.success(result);
    }

    // =============== 提交与评价 API ===============

    @Operation(summary = "提交任务完成")
    @Log(module = LogModule.TASK, type = LogOperationType.CREATE, description = "提交任务完成")
    @PostMapping("/{taskId}/submit")
    public Result<TaskCompletionDetailResponse> submitTask(
            @PathVariable Long taskId,
            @Valid @RequestBody TaskSubmitRequest request) {
        Long parentId = SecurityUtils.getCurrentUserId();
        parentAuthService.validateParentStudentRelation(parentId, request.getStudentId());
        Long tenantId = SecurityUtils.getCurrentTenantId();
        TaskCompletionDetailResponse response = taskService.submitTaskCompletion(taskId, request, tenantId);
        return Result.success(response);
    }

    @Operation(summary = "修改任务提交")
    @Log(module = LogModule.TASK, type = LogOperationType.UPDATE, description = "修改任务提交")
    @PutMapping("/{taskId}/submit")
    public Result<TaskCompletionDetailResponse> updateSubmission(
            @PathVariable Long taskId,
            @Valid @RequestBody TaskSubmitRequest request) {
        Long parentId = SecurityUtils.getCurrentUserId();
        parentAuthService.validateParentStudentRelation(parentId, request.getStudentId());
        Long tenantId = SecurityUtils.getCurrentTenantId();
        TaskCompletionDetailResponse response = taskService.submitTaskCompletion(taskId, request, tenantId);
        return Result.success(response);
    }

    @Operation(summary = "获取教师评价")
    @GetMapping("/completions/{completionId}/feedback")
    public Result<TaskFeedbackResponse> getFeedback(@PathVariable Long completionId) {
        Long parentId = SecurityUtils.getCurrentUserId();
        parentAuthService.validateParentCanAccessCompletion(parentId, completionId);
        TaskFeedbackResponse response = taskFeedbackService.getFeedbackByCompletionId(completionId);
        return Result.success(response);
    }

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

    // =============== 兼容旧接口 ===============

    @Operation(summary = "完成任务（旧接口，兼容使用，支持 JSON body）")
    @Log(module = LogModule.TASK, type = LogOperationType.UPDATE, description = "完成任务")
    @PostMapping("/{id}/complete")
    public Result<Void> completeTask(
            @PathVariable Long id,
            @RequestBody(required = false) TaskCompleteRequest body,
            @RequestParam(required = false) Long studentId,
            @RequestParam(required = false) String content,
            @RequestParam(required = false) String attachments) {
        Long sid = (body != null && body.getStudentId() != null) ? body.getStudentId() : studentId;
        String cnt = (body != null && body.getContent() != null) ? body.getContent() : content;
        String att = (body != null && body.getAttachments() != null) ? body.getAttachments() : attachments;
        if (sid == null) {
            throw new BusinessException(ErrorCode.INVALID_PARAMETER, "学生ID不能为空");
        }
        Long parentId = SecurityUtils.getCurrentUserId();
        parentAuthService.validateParentStudentRelation(parentId, sid);
        taskService.completeTask(id, sid, cnt, att);
        return Result.success();
    }

}
