package top.tqx.demo_1.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.tqx.demo_1.common.Result;
import top.tqx.demo_1.dto.*;
import top.tqx.demo_1.entity.User;
import top.tqx.demo_1.enums.AnswerType;
import top.tqx.demo_1.mapper.UserMapper;
import top.tqx.demo_1.service.ExamPaperService;
import top.tqx.demo_1.service.ExamRecordService;
import top.tqx.demo_1.service.ExamService;

import java.util.Map;

/**
 * 正式考管理接口 - 管理员端
 * 管理员预览、保存、发布正式考试试卷
 */
@Slf4j
@RestController
@RequestMapping("/admin/exam")
@Tag(name = "正式考管理", description = "正式考管理接口，供管理员预览、保存、发布正式考试试卷")
public class AdminExamController extends BaseController {

    @Autowired
    private ExamPaperService examPaperService;

    @Autowired
    private ExamRecordService examRecordService;

    @Autowired
    private ExamService examService;

    @Autowired
    private UserMapper userMapper;

    @Operation(summary = "预览试卷", description = "管理员预览生成的试卷内容")
    @PostMapping("/paper/preview")
    public Result<ExamPaperGenerateResponse> previewPaper(
            @RequestBody ExamPaperGenerateRequest request,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getCurrentUserId(httpRequest);
            User user = userMapper.selectById(userId);
            log.info("预览试卷请求: userId={}, deptId={}, userType={}", userId, user.getDeptId(), user.getUserType());
            ExamPaperGenerateResponse response = examPaperService.previewPaper(request, userId, user.getDeptId(), user.getUserType());
            return Result.success(response);
        } catch (Exception e) {
            log.error("预览试卷失败: {}", e.getMessage());
            return Result.error(500, e.getMessage());
        }
    }

    @Operation(summary = "预览试卷详情", description = "管理员预览生成的试卷详细内容，包含完整的题目内容和选项")
    @PostMapping("/paper/preview/detail")
    public Result<ExamPaperPreviewResponse> previewPaperWithDetails(
            @RequestBody ExamPaperGenerateRequest request,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getCurrentUserId(httpRequest);
            User user = userMapper.selectById(userId);
            log.info("预览试卷详情请求: userId={}, deptId={}, userType={}", userId, user.getDeptId(), user.getUserType());
            ExamPaperPreviewResponse response = examPaperService.previewPaperWithDetails(request, userId, user.getDeptId(), user.getUserType());
            return Result.success(response);
        } catch (Exception e) {
            log.error("预览试卷详情失败: {}", e.getMessage());
            return Result.error(500, e.getMessage());
        }
    }

    @Operation(summary = "保存试卷", description = "管理员保存试卷到数据库")
    @PostMapping("/paper/save")
    public Result<ExamPaperResponse> savePaper(
            @RequestBody ExamPaperSaveRequest request,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getCurrentUserId(httpRequest);
            ExamPaperResponse response = examPaperService.savePaper(request, userId);
            return Result.success(response);
        } catch (Exception e) {
            log.error("保存试卷失败: {}", e.getMessage());
            return Result.error(500, e.getMessage());
        }
    }

    @Operation(summary = "发布试卷", description = "管理员发布试卷给指定部门或用户")
    @PostMapping("/paper/{paperId}/publish")
    public Result<Void> publishPaper(
            @PathVariable String paperId,
            @RequestBody ExamPublishRequest request,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getCurrentUserId(httpRequest);
            examPaperService.publishPaper(paperId, request, userId);
            return Result.success();
        } catch (Exception e) {
            log.error("发布试卷失败: {}", e.getMessage());
            return Result.error(500, e.getMessage());
        }
    }

    @Operation(summary = "撤销试卷", description = "管理员撤销已发布的试卷")
    @PostMapping("/paper/{paperId}/revoke")
    public Result<Void> revokePaper(@PathVariable String paperId) {
        try {
            examPaperService.revokePaper(paperId);
            return Result.success();
        } catch (Exception e) {
            log.error("撤销试卷失败: {}", e.getMessage());
            return Result.error(500, e.getMessage());
        }
    }

    @Operation(summary = "删除试卷", description = "管理员删除试卷")
    @DeleteMapping("/paper/{paperId}")
    public Result<Void> deletePaper(@PathVariable String paperId) {
        try {
            examPaperService.deletePaper(paperId);
            return Result.success();
        } catch (Exception e) {
            log.error("删除试卷失败: {}", e.getMessage());
            return Result.error(500, e.getMessage());
        }
    }

    @Operation(summary = "获取试卷详情", description = "管理员获取试卷详细信息")
    @GetMapping("/paper/{paperId}")
    public Result<ExamPaperResponse> getPaperById(@PathVariable String paperId) {
        try {
            ExamPaperResponse response = examPaperService.getPaperById(paperId);
            if (response == null) {
                return Result.error(404, "试卷不存在");
            }
            return Result.success(response);
        } catch (Exception e) {
            log.error("获取试卷详情失败: {}", e.getMessage());
            return Result.error(500, e.getMessage());
        }
    }

    @Operation(summary = "获取试卷分配详情", description = "获取试卷的部门分配和用户分配信息")
    @GetMapping("/paper/{paperId}/assignment")
    public Result<Map<String, Object>> getPaperAssignment(@PathVariable String paperId) {
        try {
            Map<String, Object> result = examPaperService.getPaperAssignment(paperId);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取试卷分配详情失败: {}", e.getMessage());
            return Result.error(500, e.getMessage());
        }
    }

    @Operation(summary = "获取试卷列表", description = "管理员获取试卷列表，支持按状态筛选")
    @GetMapping("/paper/list")
    public Result<PageResponse<ExamPaperResponse>> listPapers(
            @RequestParam(required = false) String status,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer pageSize) {
        try {
            PageResponse<ExamPaperResponse> response = examPaperService.listPapers(status, page, pageSize);
            return Result.success(response);
        } catch (Exception e) {
            log.error("查询试卷列表失败: {}", e.getMessage());
            return Result.error(500, e.getMessage());
        }
    }

    @Operation(summary = "获取考试记录列表", description = "管理员获取指定试卷的答题记录列表")
    @GetMapping("/records/{paperId}")
    public Result<PageResponse<ExamRecordResponse>> listRecords(
            @PathVariable String paperId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer pageSize) {
        try {
            PageResponse<ExamRecordResponse> response = examRecordService.listRecords(paperId, page, pageSize);
            return Result.success(response);
        } catch (Exception e) {
            log.error("查询答题记录失败: {}", e.getMessage());
            return Result.error(500, e.getMessage());
        }
    }

    @Operation(summary = "获取考试记录详情", description = "管理员获取指定答题记录的详细信息")
    @GetMapping("/record/{recordId}")
    public Result<ExamRecordResponse> getRecordById(@PathVariable String recordId) {
        try {
            ExamRecordResponse response = examRecordService.getRecordById(recordId);
            if (response == null) {
                return Result.error(404, "记录不存在");
            }
            return Result.success(response);
        } catch (Exception e) {
            log.error("获取答题记录失败: {}", e.getMessage());
            return Result.error(500, e.getMessage());
        }
    }

    @Operation(summary = "提交试卷", description = "管理员代用户提交试卷并批改")
    @PostMapping("/record/{recordId}/submit")
    public Result<ExamRecordResponse> submitExam(
            @PathVariable String recordId,
            @RequestBody ExamSaveRequest request,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getCurrentUserId(httpRequest);
            ExamRecordResponse response = examService.gradeAnswersForRecord(
                recordId, request, userId, AnswerType.FORMAL_EXAM.getCode());
            return Result.success(response);
        } catch (Exception e) {
            log.error("提交试卷失败: {}", e.getMessage());
            return Result.error(500, e.getMessage());
        }
    }
}