package com.lesingle.creation.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lesingle.creation.common.core.Result;
import com.lesingle.creation.dto.homework.*;
import com.lesingle.creation.vo.school.ClassTreeNodeVO;
import com.lesingle.creation.service.HomeworkService;
import com.lesingle.creation.vo.homework.HomeworkDetailVO;
import com.lesingle.creation.vo.homework.HomeworkListVO;
import com.lesingle.creation.vo.homework.ReviewRuleVO;
import com.lesingle.creation.vo.homework.SubmissionVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import com.lesingle.creation.common.security.UserPrincipal;
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/homeworks")
@RequiredArgsConstructor
public class HomeworkController {

    private final HomeworkService homeworkService;

    @PostMapping
    @Operation(summary = "创建作业")
    @PreAuthorize("hasAuthority('homework:create')")
    public Result<HomeworkDetailVO> create(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @RequestBody @Validated CreateHomeworkDTO dto) {
        Long tenantId = userPrincipal.getTenantId();
        Long creatorId = userPrincipal.getUserId();
        HomeworkDetailVO result = homeworkService.create(dto, tenantId, creatorId);
        return Result.success(result);
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新作业")
    @PreAuthorize("hasAuthority('homework:update')")
    public Result<HomeworkDetailVO> update(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @PathVariable Long id,
            @RequestBody @Validated UpdateHomeworkDTO dto) {
        Long tenantId = userPrincipal.getTenantId();
        HomeworkDetailVO result = homeworkService.update(id, dto, tenantId);
        return Result.success(result);
    }

    @PostMapping("/{id}/publish")
    @Operation(summary = "发布作业")
    @PreAuthorize("hasAuthority('homework:publish')")
    public Result<HomeworkDetailVO> publish(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @PathVariable Long id) {
        Long tenantId = userPrincipal.getTenantId();
        HomeworkDetailVO result = homeworkService.publish(id, tenantId);
        return Result.success(result);
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除作业")
    @PreAuthorize("hasAuthority('homework:delete')")
    public Result<Void> delete(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @PathVariable Long id) {
        Long tenantId = userPrincipal.getTenantId();
        homeworkService.delete(id, tenantId);
        return Result.success(null);
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取作业详情")
    public Result<HomeworkDetailVO> getDetail(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @PathVariable Long id) {
        Long tenantId = userPrincipal.getTenantId();
        HomeworkDetailVO result = homeworkService.getDetail(id, tenantId);
        return Result.success(result);
    }

    @GetMapping("/page")
    @Operation(summary = "分页查询作业列表")
    public Result<Page<HomeworkListVO>> pageQuery(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @ModelAttribute HomeworkQueryDTO queryDTO) {
        Long tenantId = userPrincipal.getTenantId();
        Page<HomeworkListVO> result = homeworkService.pageQuery(queryDTO, tenantId);
        return Result.success(result);
    }

    @PostMapping("/submit")
    @Operation(summary = "提交作业")
    public Result<SubmissionVO> submit(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @RequestBody @Validated SubmitHomeworkDTO dto) {
        Long tenantId = userPrincipal.getTenantId();
        Long studentId = userPrincipal.getUserId();
        SubmissionVO result = homeworkService.submit(dto, tenantId, studentId);
        return Result.success(result);
    }

    @PostMapping("/review")
    @Operation(summary = "批改作业")
    @PreAuthorize("hasAuthority('homework:review')")
    public Result<SubmissionVO> review(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @RequestBody @Validated ReviewHomeworkDTO dto) {
        Long tenantId = userPrincipal.getTenantId();
        Long reviewerId = userPrincipal.getUserId();
        SubmissionVO result = homeworkService.review(dto, tenantId, reviewerId);
        return Result.success(result);
    }

    @GetMapping("/{homeworkId}/submissions")
    @Operation(summary = "获取作业提交列表")
    @PreAuthorize("hasAuthority('homework:review')")
    public Result<List<SubmissionVO>> getSubmissions(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @PathVariable Long homeworkId) {
        Long tenantId = userPrincipal.getTenantId();
        List<SubmissionVO> result = homeworkService.getSubmissions(homeworkId, tenantId);
        return Result.success(result);
    }

    @PostMapping("/review-rules")
    @Operation(summary = "创建评审规则")
    @PreAuthorize("hasAuthority('homework:review-rule:create')")
    public Result<ReviewRuleVO> createReviewRule(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @RequestParam String ruleName,
            @RequestParam(required = false, defaultValue = "custom") String ruleType,
            @RequestParam(required = false) java.math.BigDecimal totalScore,
            @RequestParam(required = false) String description) {
        Long tenantId = userPrincipal.getTenantId();
        ReviewRuleVO result = homeworkService.createReviewRule(
                ruleName, ruleType, totalScore, description, tenantId);
        return Result.success(result);
    }

    @GetMapping("/review-rules")
    @Operation(summary = "获取评审规则列表")
    public Result<List<ReviewRuleVO>> getReviewRules(
            @AuthenticationPrincipal UserPrincipal userPrincipal) {
        Long tenantId = userPrincipal.getTenantId();
        List<ReviewRuleVO> result = homeworkService.getReviewRules(tenantId);
        return Result.success(result);
    }

    @GetMapping("/review-rules/select")
    @Operation(summary = "获取可选的评审规则")
    public Result<List<ReviewRuleVO>> getReviewRulesForSelect(
            @AuthenticationPrincipal UserPrincipal userPrincipal) {
        Long tenantId = userPrincipal.getTenantId();
        List<ReviewRuleVO> result = homeworkService.getReviewRulesForSelect(tenantId);
        return Result.success(result);
    }

    @PutMapping("/review-rules/{id}")
    @Operation(summary = "更新评审规则")
    @PreAuthorize("hasAuthority('homework:review-rule:update')")
    public Result<ReviewRuleVO> updateReviewRule(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @PathVariable Long id,
            @RequestBody @Validated UpdateReviewRuleDTO dto) {
        Long tenantId = userPrincipal.getTenantId();
        ReviewRuleVO result = homeworkService.updateReviewRule(id, dto, tenantId);
        return Result.success(result);
    }

    @DeleteMapping("/review-rules/{id}")
    @Operation(summary = "删除评审规则")
    @PreAuthorize("hasAuthority('homework:review-rule:delete')")
    public Result<Void> deleteReviewRule(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @PathVariable Long id) {
        Long tenantId = userPrincipal.getTenantId();
        homeworkService.deleteReviewRule(id, tenantId);
        return Result.success(null);
    }

    @GetMapping("/my")
    @Operation(summary = "我的作业列表（学生端）")
    public Result<Page<HomeworkListVO>> getMyHomeworks(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @ModelAttribute HomeworkQueryDTO queryDTO) {
        Long userId = userPrincipal.getUserId();
        Long tenantId = userPrincipal.getTenantId();
        Page<HomeworkListVO> result = homeworkService.getMyHomeworks(queryDTO, userId, tenantId);
        return Result.success(result);
    }

    @PostMapping("/{id}/unpublish")
    @Operation(summary = "取消发布作业")
    @PreAuthorize("hasAuthority('homework:publish')")
    public Result<HomeworkDetailVO> unpublish(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @PathVariable Long id) {
        Long tenantId = userPrincipal.getTenantId();
        HomeworkDetailVO result = homeworkService.unpublish(id, tenantId);
        return Result.success(result);
    }

    @GetMapping("/submissions")
    @Operation(summary = "获取提交记录列表")
    @PreAuthorize("hasAuthority('homework:review')")
    public Result<Page<SubmissionVO>> getSubmissionsList(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @ModelAttribute SubmissionQueryDTO queryDTO) {
        Long tenantId = userPrincipal.getTenantId();
        Page<SubmissionVO> result = homeworkService.getSubmissionsList(queryDTO, tenantId);
        return Result.success(result);
    }

    @GetMapping("/submissions/{id}")
    @Operation(summary = "获取提交记录详情")
    @PreAuthorize("hasAuthority('homework:review')")
    public Result<SubmissionVO> getSubmissionDetail(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @PathVariable Long id) {
        Long tenantId = userPrincipal.getTenantId();
        SubmissionVO result = homeworkService.getSubmissionDetail(id, tenantId);
        return Result.success(result);
    }

    @GetMapping("/submissions/class-tree")
    @Operation(summary = "获取班级树结构")
    @PreAuthorize("hasAuthority('homework:review')")
    public Result<List<ClassTreeNodeVO>> getClassTree(
            @AuthenticationPrincipal UserPrincipal userPrincipal) {
        Long tenantId = userPrincipal.getTenantId();
        List<ClassTreeNodeVO> result = homeworkService.getClassTree(tenantId);
        return Result.success(result);
    }

    @GetMapping("/submissions/my/{homeworkId}")
    @Operation(summary = "获取我的提交记录")
    public Result<SubmissionVO> getMySubmission(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @PathVariable Long homeworkId) {
        Long userId = userPrincipal.getUserId();
        Long tenantId = userPrincipal.getTenantId();
        SubmissionVO result = homeworkService.getMySubmission(homeworkId, userId, tenantId);
        return result != null ? Result.success(result) : Result.success(null);
    }

    @PostMapping("/scores")
    @Operation(summary = "提交评分")
    @PreAuthorize("hasAuthority('homework:review')")
    public Result<SubmissionVO> createScore(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @RequestBody @Validated CreateScoreDTO dto) {
        Long tenantId = userPrincipal.getTenantId();
        Long reviewerId = userPrincipal.getUserId();
        SubmissionVO result = homeworkService.createScore(dto, tenantId, reviewerId);
        return Result.success(result);
    }

    @PostMapping("/scores/{submissionId}/violation")
    @Operation(summary = "标记作品违规")
    @PreAuthorize("hasAuthority('homework:review')")
    public Result<Void> markViolation(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @PathVariable Long submissionId,
            @RequestParam(required = false) String reason) {
        Long tenantId = userPrincipal.getTenantId();
        homeworkService.markViolation(submissionId, reason, tenantId);
        return Result.success(null);
    }

    @PostMapping("/scores/{submissionId}/reset")
    @Operation(summary = "重置评分")
    @PreAuthorize("hasAuthority('homework:review')")
    public Result<Void> resetScore(
            @AuthenticationPrincipal UserPrincipal userPrincipal,
            @PathVariable Long submissionId) {
        Long tenantId = userPrincipal.getTenantId();
        homeworkService.resetScore(submissionId, tenantId);
        return Result.success(null);
    }
}
