package com.lesingle.creation.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lesingle.creation.common.core.Result;
import com.lesingle.creation.common.security.UserPrincipal;
import com.lesingle.creation.dto.review.*;
import com.lesingle.creation.service.ContestReviewService;
import com.lesingle.creation.vo.review.ReviewAssignmentVO;
import com.lesingle.creation.vo.review.ReviewStatsVO;
import com.lesingle.creation.vo.review.WorkScoreVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 竞赛评审管理控制器
 */
@Tag(name = "竞赛评审管理")
@RestController
@RequestMapping("/api/contests/reviews")
@RequiredArgsConstructor
public class ContestReviewController {

    private final ContestReviewService reviewService;

    @PostMapping("/assign")
    @Operation(summary = "分配作品给评委")
    @PreAuthorize("hasAuthority('contest:review:assign')")
    public Result<List<ReviewAssignmentVO>> assignWork(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @RequestParam Long contestId,
            @RequestBody @Validated AssignWorkDTO dto) {
        Long tenantId = userPrincipal.getTenantId();
        List<ReviewAssignmentVO> result = reviewService.assignWork(contestId, dto, tenantId);
        return Result.success(result);
    }

    @PostMapping("/batch-assign")
    @Operation(summary = "批量分配作品")
    @PreAuthorize("hasAuthority('contest:review:assign')")
    public Result<List<ReviewAssignmentVO>> batchAssign(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @RequestBody @Validated BatchAssignDTO dto) {
        Long tenantId = userPrincipal.getTenantId();
        List<ReviewAssignmentVO> result = reviewService.batchAssign(dto, tenantId);
        return Result.success(result);
    }

    @PostMapping("/score")
    @Operation(summary = "评分")
    @PreAuthorize("hasAuthority('contest:review:score')")
    public Result<WorkScoreVO> score(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @RequestBody @Validated CreateScoreDTO dto) {
        Long tenantId = userPrincipal.getTenantId();
        Long judgeId = userPrincipal.getUserId();
        WorkScoreVO result = reviewService.score(dto, judgeId, tenantId);
        return Result.success(result);
    }

    @PutMapping("/score/{scoreId}")
    @Operation(summary = "更新评分")
    @PreAuthorize("hasAuthority('contest:review:score')")
    public Result<WorkScoreVO> updateScore(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @PathVariable Long scoreId,
            @RequestBody @Validated CreateScoreDTO dto) {
        Long tenantId = userPrincipal.getTenantId();
        WorkScoreVO result = reviewService.updateScore(scoreId, dto, tenantId);
        return Result.success(result);
    }

    @GetMapping("/assignments/page")
    @Operation(summary = "分页查询评审分配列表")
    @PreAuthorize("hasAuthority('contest:read')")
    public Result<Page<ReviewAssignmentVO>> pageQuery(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @ModelAttribute ReviewAssignmentQueryDTO queryDTO) {
        Long tenantId = userPrincipal.getTenantId();
        Page<ReviewAssignmentVO> result = reviewService.pageQuery(queryDTO, tenantId);
        return Result.success(result);
    }

    @GetMapping("/my-assignments")
    @Operation(summary = "获取评委待评审作品列表")
    @PreAuthorize("hasAuthority('contest:review:score')")
    public Result<List<ReviewAssignmentVO>> getMyAssignments(
            @AuthenticationPrincipal UserPrincipal userPrincipal) {
        Long judgeId = userPrincipal.getUserId();
        Long tenantId = userPrincipal.getTenantId();
        List<ReviewAssignmentVO> result = reviewService.getMyAssignments(judgeId, tenantId);
        return Result.success(result);
    }

    @GetMapping("/stats")
    @Operation(summary = "评审统计")
    @PreAuthorize("hasAuthority('contest:read')")
    public Result<ReviewStatsVO> getStats(@RequestParam(required = false) Long contestId) {
        ReviewStatsVO result = reviewService.getStats(contestId);
        return Result.success(result);
    }

    @GetMapping("/works/{workId}/scores")
    @Operation(summary = "获取作品的评分列表")
    @PreAuthorize("hasAuthority('contest:read')")
    public Result<List<WorkScoreVO>> getWorkScores(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @PathVariable Long workId) {
        Long tenantId = userPrincipal.getTenantId();
        List<WorkScoreVO> result = reviewService.getWorkScores(workId, tenantId);
        return Result.success(result);
    }

    @GetMapping("/works/{workId}/average-score")
    @Operation(summary = "获取作品的平均分")
    @PreAuthorize("hasAuthority('contest:read')")
    public Result<java.math.BigDecimal> getAverageScore(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @PathVariable Long workId) {
        Long tenantId = userPrincipal.getTenantId();
        java.math.BigDecimal result = reviewService.getAverageScore(workId, tenantId);
        return Result.success(result);
    }

    @PostMapping("/auto-assign")
    @Operation(summary = "自动分配作品给评委")
    @PreAuthorize("hasAuthority('contest:review:assign')")
    public Result<String> autoAssign(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @RequestParam Long contestId) {
        Long tenantId = userPrincipal.getTenantId();
        String result = reviewService.autoAssign(contestId, tenantId);
        return Result.success(result);
    }

    @GetMapping("/progress/{contestId}")
    @Operation(summary = "获取评审进度统计")
    @PreAuthorize("hasAuthority('contest:read')")
    public Result<com.lesingle.creation.vo.review.ReviewProgressVO> getReviewProgress(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @PathVariable Long contestId) {
        Long tenantId = userPrincipal.getTenantId();
        com.lesingle.creation.vo.review.ReviewProgressVO result =
                reviewService.getReviewProgress(contestId, tenantId);
        return Result.success(result);
    }

    @GetMapping("/work-status/{contestId}")
    @Operation(summary = "获取作品状态统计")
    @PreAuthorize("hasAuthority('contest:read')")
    public Result<com.lesingle.creation.vo.review.WorkStatusStatsVO> getWorkStatusStats(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @PathVariable Long contestId) {
        Long tenantId = userPrincipal.getTenantId();
        com.lesingle.creation.vo.review.WorkStatusStatsVO result =
                reviewService.getWorkStatusStats(contestId, tenantId);
        return Result.success(result);
    }

    @GetMapping("/works/{workId}/final-score")
    @Operation(summary = "获取作品的最终得分")
    @PreAuthorize("hasAuthority('contest:read')")
    public Result<com.lesingle.creation.vo.review.FinalScoreVO> getFinalScore(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @PathVariable Long workId) {
        Long tenantId = userPrincipal.getTenantId();
        com.lesingle.creation.vo.review.FinalScoreVO result =
                reviewService.getFinalScore(workId, tenantId);
        return Result.success(result);
    }

    @PostMapping("/replace-judge")
    @Operation(summary = "替换评委")
    @PreAuthorize("hasAuthority('contest:review:assign')")
    public Result<Void> replaceJudge(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @RequestParam Long assignmentId,
            @RequestParam Long newJudgeId) {
        Long tenantId = userPrincipal.getTenantId();
        reviewService.replaceJudge(assignmentId, newJudgeId, tenantId);
        return Result.success(null);
    }

    @GetMapping("/judge/contests")
    @Operation(summary = "获取评委参与的活动列表")
    public Result<java.util.List<com.lesingle.creation.vo.review.JudgeContestVO>> getJudgeContests(
            @AuthenticationPrincipal UserPrincipal userPrincipal) {
        Long judgeId = userPrincipal.getUserId();
        Long tenantId = userPrincipal.getTenantId();
        java.util.List<com.lesingle.creation.vo.review.JudgeContestVO> result =
                reviewService.getJudgeContests(judgeId, tenantId);
        return Result.success(result);
    }

    @GetMapping("/judge/contests/{contestId}/works")
    @Operation(summary = "获取评委在某个活动下的作品列表")
    public Result<com.baomidou.mybatisplus.extension.plugins.pagination.Page<com.lesingle.creation.vo.review.JudgeWorkVO>>
            getJudgeContestWorks(
                    @AuthenticationPrincipal UserPrincipal userPrincipal,
                    @PathVariable Long contestId,
                    @ModelAttribute com.lesingle.creation.dto.review.JudgeWorkQueryDTO queryDTO) {
        Long judgeId = userPrincipal.getUserId();
        Long tenantId = userPrincipal.getTenantId();
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<com.lesingle.creation.vo.review.JudgeWorkVO> result =
                reviewService.getJudgeContestWorks(contestId, judgeId, tenantId, queryDTO);
        return Result.success(result);
    }
}
