package com.dne.ems.controller;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.dne.ems.dto.TaskDetailDTO;
import com.dne.ems.dto.TaskSubmissionRequest;
import com.dne.ems.dto.TaskSummaryDTO;
import com.dne.ems.model.enums.TaskStatus;
import com.dne.ems.security.CustomUserDetails;
import com.dne.ems.service.GridWorkerTaskService;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;

import java.util.List;
import org.springframework.http.MediaType;

/**
 * 网格员任务控制器，处理网格员的任务管理操作
 *
 * <p>主要功能包括：
 * <ul>
 *   <li>获取分配的任务列表</li>
 *   <li>接受任务</li>
 *   <li>提交任务完成情况</li>
 *   <li>查看任务详情</li>
 * </ul>
 *
 * @author DNE开发团队
 * @version 1.0
 * @since 2024
 */
@RestController
@RequestMapping("/api/worker")
@RequiredArgsConstructor
@PreAuthorize("hasRole('GRID_WORKER')")
@Tag(name = "Grid Worker Tasks", description = "Endpoints for grid workers to manage their assigned tasks")
public class GridWorkerTaskController {

    private final GridWorkerTaskService gridWorkerTaskService;

    /**
     * 获取当前网格员分配的任务列表
     *
     * @param userDetails 当前认证用户信息
     * @param status 任务状态过滤条件(可选)
     * @param pageable 分页参数
     * @return 任务摘要列表
     * @see TaskSummaryDTO
     */
    @GetMapping
    @PreAuthorize("hasAuthority('ROLE_GRID_WORKER')")
    @Operation(summary = "Get my assigned tasks", description = "Retrieves a paginated list of tasks assigned to the currently authenticated grid worker.")
    public ResponseEntity<Page<TaskSummaryDTO>> getMyTasks(
        @AuthenticationPrincipal CustomUserDetails userDetails,
        @Parameter(description = "Filter tasks by status") @RequestParam(required = false) TaskStatus status,
        Pageable pageable
    ) {
        Page<TaskSummaryDTO> tasks = gridWorkerTaskService.getAssignedTasks(userDetails.getId(), status, pageable);
        return ResponseEntity.ok(tasks);
    }

    /**
     * 接受指定任务
     *
     * @param taskId 任务ID
     * @param userDetails 当前认证用户信息
     * @return 更新后的任务摘要
     * @throws ResourceNotFoundException 如果任务不存在
     * @throws InvalidOperationException 如果任务无法被接受
     * @see TaskSummaryDTO
     */
    @PostMapping("/{taskId}/accept")
    public ResponseEntity<TaskSummaryDTO> acceptTask(
            @PathVariable Long taskId,
            @AuthenticationPrincipal CustomUserDetails userDetails) {
        TaskSummaryDTO updatedTask = gridWorkerTaskService.acceptTask(taskId, userDetails.getId());
        return ResponseEntity.ok(updatedTask);
    }

    /**
     * 提交任务完成情况
     *
     * @param taskId 任务ID
     * @param comments 任务完成评论
     * @param files 任务完成附件
     * @param userDetails 当前认证用户信息
     * @return 更新后的任务摘要
     * @throws ResourceNotFoundException 如果任务不存在
     * @throws InvalidOperationException 如果任务无法被提交
     * @see TaskSubmissionRequest
     * @see TaskSummaryDTO
     */
    @PostMapping(value = "/{taskId}/submit", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<TaskSummaryDTO> submitTask(
            @PathVariable Long taskId,
            @RequestPart("comments") @Valid String comments,
            @RequestPart(value = "files", required = false) List<MultipartFile> files,
            @AuthenticationPrincipal CustomUserDetails userDetails) {
        TaskSubmissionRequest request = new TaskSubmissionRequest(comments);
        TaskSummaryDTO updatedTask = gridWorkerTaskService.submitTaskCompletion(taskId, userDetails.getId(), request, files);
        return ResponseEntity.ok(updatedTask);
    }
    /**
     * 获取任务详情
     *
     * @param taskId 任务ID
     * @param userDetails 当前认证用户信息
     * @return 任务详情
     * @throws ResourceNotFoundException 如果任务不存在
     * @see TaskDetailDTO
     */
    @GetMapping("/{taskId}")
    public ResponseEntity<TaskDetailDTO> getTaskDetails(
            @PathVariable Long taskId,
            @AuthenticationPrincipal CustomUserDetails userDetails) {
        TaskDetailDTO taskDetails = gridWorkerTaskService.getTaskDetails(taskId, userDetails.getId());
        return ResponseEntity.ok(taskDetails);
    }
}