package com.lesingle.modules.biz.review.controller;

import com.lesingle.common.result.PageResult;
import com.lesingle.common.result.Result;
import com.lesingle.common.util.SecurityUtil;
import com.lesingle.modules.biz.review.dto.AssignWorkDto;
import com.lesingle.modules.biz.review.dto.BatchAssignDto;
import com.lesingle.modules.biz.review.dto.CreateScoreDto;
import com.lesingle.modules.biz.review.dto.MarkContestWorkViolationDto;
import com.lesingle.modules.biz.review.service.IContestReviewService;
import com.lesingle.security.annotation.RequirePermission;
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;

@Tag(name = "评审管理")
@RestController
@RequestMapping("/contests/reviews")
@RequiredArgsConstructor
public class ContestReviewController {

    private final IContestReviewService contestReviewService;

    @PostMapping("/assign")
    @RequirePermission("review:assign")
    @Operation(summary = "分配作品给评委")
    public Result<Map<String, Object>> assignWork(
            @RequestParam Long contestId,
            @Valid @RequestBody AssignWorkDto dto) {
        Long creatorId = SecurityUtil.getCurrentUserId();
        return Result.success(contestReviewService.assignWork(contestId, dto.getWorkId(), dto.getJudgeIds(), creatorId));
    }

    @PostMapping("/batch-assign")
    @RequirePermission("review:assign")
    @Operation(summary = "批量分配作品给评委")
    public Result<Map<String, Object>> batchAssignWorks(
            @RequestParam Long contestId,
            @Valid @RequestBody BatchAssignDto dto) {
        Long creatorId = SecurityUtil.getCurrentUserId();
        return Result.success(contestReviewService.batchAssignWorks(contestId, dto.getWorkIds(), dto.getJudgeIds(), creatorId));
    }

    @PostMapping("/auto-assign")
    @RequirePermission("review:assign")
    @Operation(summary = "自动分配作品")
    public Result<Map<String, Object>> autoAssignWorks(@RequestParam Long contestId) {
        Long creatorId = SecurityUtil.getCurrentUserId();
        return Result.success(contestReviewService.autoAssignWorks(contestId, creatorId));
    }

    @PostMapping("/score")
    @RequirePermission("review:score")
    @Operation(summary = "评分")
    public Result<Map<String, Object>> score(@Valid @RequestBody CreateScoreDto dto) {
        Long judgeId = SecurityUtil.getCurrentUserId();
        Long tenantId = SecurityUtil.getCurrentTenantId();
        return Result.success(contestReviewService.score(dto, judgeId, tenantId));
    }

    @PostMapping("/work/{workId}/violation")
    @RequirePermission("review:score")
    @Operation(summary = "标记作品违规", description = "将作品 status 置为 violation，并结束当前评委分配任务（assignment 置为 completed）")
    public Result<Map<String, Object>> markViolation(
            @PathVariable Long workId,
            @Valid @RequestBody MarkContestWorkViolationDto dto) {
        Long judgeId = SecurityUtil.getCurrentUserId();
        return Result.success(contestReviewService.markViolation(workId, dto, judgeId));
    }

    @PatchMapping("/score/{id}")
    @RequirePermission("review:score")
    @Operation(summary = "修改评分")
    public Result<Map<String, Object>> updateScore(
            @PathVariable Long id,
            @Valid @RequestBody CreateScoreDto dto) {
        Long judgeId = SecurityUtil.getCurrentUserId();
        return Result.success(contestReviewService.updateScore(id, dto, judgeId));
    }

    @GetMapping("/assigned")
    @RequirePermission("review:read")
    @Operation(summary = "查询已分配作品")
    public Result<List<Map<String, Object>>> getAssignedWorks(@RequestParam Long contestId) {
        Long judgeId = SecurityUtil.getCurrentUserId();
        return Result.success(contestReviewService.getAssignedWorks(judgeId, contestId));
    }

    @GetMapping("/judge/contests")
    @RequirePermission("review:score")
    @Operation(summary = "获取评委参与的活动列表")
    public Result<List<Map<String, Object>>> getJudgeContests() {
        Long judgeId = SecurityUtil.getCurrentUserId();
        return Result.success(contestReviewService.getJudgeContests(judgeId));
    }

    @GetMapping("/judge/contests/{contestId}/works")
    @RequirePermission("review:score")
    @Operation(summary = "获取评委活动作品列表")
    public Result<PageResult<Map<String, Object>>> getJudgeContestWorks(
            @PathVariable Long contestId,
            @RequestParam(defaultValue = "1") Long page,
            @RequestParam(defaultValue = "10") Long pageSize,
            @RequestParam(required = false) String workNo,
            @RequestParam(required = false) String accountNo,
            @RequestParam(required = false) String reviewStatus) {
        Long judgeId = SecurityUtil.getCurrentUserId();
        return Result.success(contestReviewService.getJudgeContestWorks(judgeId, contestId, page, pageSize, workNo, accountNo, reviewStatus));
    }

    @GetMapping("/progress/{contestId}")
    @RequirePermission("review:read")
    @Operation(summary = "获取评审进度")
    public Result<Map<String, Object>> getReviewProgress(@PathVariable Long contestId) {
        return Result.success(contestReviewService.getReviewProgress(contestId));
    }

    @GetMapping("/work-status/{contestId}")
    @RequirePermission("review:read")
    @Operation(summary = "获取作品评审状态统计")
    public Result<Map<String, Object>> getWorkStatusStats(@PathVariable Long contestId) {
        return Result.success(contestReviewService.getWorkStatusStats(contestId));
    }

    @GetMapping("/work/{workId}/scores")
    @RequirePermission("review:read")
    @Operation(summary = "查询作品评分记录")
    public Result<List<Map<String, Object>>> getWorkScores(@PathVariable Long workId) {
        return Result.success(contestReviewService.getWorkScores(workId));
    }

    @GetMapping("/work/{workId}/final-score")
    @RequirePermission("review:read")
    @Operation(summary = "计算作品最终得分")
    public Result<Map<String, Object>> calculateFinalScore(@PathVariable Long workId) {
        return Result.success(contestReviewService.calculateFinalScore(workId));
    }

    @GetMapping("/judge/contests/{contestId}/detail")
    @RequirePermission("review:read")
    @Operation(summary = "获取评委视角的活动详情（含评审规则）")
    public Result<Map<String, Object>> getJudgeContestDetail(@PathVariable Long contestId) {
        Long judgeId = SecurityUtil.getCurrentUserId();
        return Result.success(contestReviewService.getJudgeContestDetail(judgeId, contestId));
    }
}
