package top.tqx.demo_1.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.tqx.demo_1.common.PageResult;
import top.tqx.demo_1.common.Result;
import top.tqx.demo_1.dto.QuestionCreateRequest;
import top.tqx.demo_1.dto.QuestionStatsRequest;
import top.tqx.demo_1.dto.QuestionStatsResponse;
import top.tqx.demo_1.dto.QuestionUpdateRequest;
import top.tqx.demo_1.entity.Question;
import top.tqx.demo_1.service.QuestionService;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import jakarta.servlet.http.HttpServletRequest;

@Tag(name = "题目管理", description = "题目的增删改查管理接口")
@RestController
@RequestMapping("/question")
@Slf4j
public class QuestionController extends BaseController {

    @Autowired
    private QuestionService questionService;

    @Operation(summary = "创建题目", description = "创建新的题目记录")
    @PostMapping
    public Result<Question> createQuestion(@RequestBody QuestionCreateRequest request) {
        if (request.getQuestionType() == null || request.getQuestionType().isEmpty()) {
            return Result.error(400, "题目类型不能为空");
        }
        if (request.getDifficulty() == null || request.getDifficulty() < 1 || request.getDifficulty() > 5) {
            return Result.error(400, "难度等级必须在1-5之间");
        }
        if (request.getContent() == null) {
            return Result.error(400, "题目内容不能为空");
        }

        try {
            Question question = questionService.createQuestion(request);
            log.info("创建题目成功: id={}, questionType={}", question.getId(), question.getQuestionType());
            return Result.success("题目创建成功", question);
        } catch (Exception e) {
            log.error("创建题目失败: {}", e.getMessage(), e);
            return Result.error(500, "创建题目失败: " + e.getMessage());
        }
    }

    @Operation(summary = "分页查询题目", description = "根据条件分页查询题目列表")
    @GetMapping("/page")
    public Result<PageResult<Question>> pageQuestions(
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页大小", example = "10") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "题目类型") @RequestParam(required = false) String questionType,
            @Parameter(description = "难度等级") @RequestParam(required = false) Integer difficulty,
            @Parameter(description = "审核状态") @RequestParam(required = false) String status) {
        PageResult<Question> result = questionService.pageQuestions(pageNum, pageSize, questionType, difficulty, status);
        return Result.success(result);
    }

    @Operation(summary = "获取题目详情", description = "根据题目UUID获取题目详细信息")
    @GetMapping("/{questionId}")
    public Result<Question> getQuestionById(
            @Parameter(description = "题目UUID") @PathVariable String questionId) {
        Question question = questionService.getByQuestionId(questionId);
        if (question == null) {
            return Result.error(404, "题目不存在");
        }
        return Result.success(question);
    }

    @Operation(summary = "获取待审核题目列表", description = "获取所有待审核的题目")
    @GetMapping("/pending")
    public Result<List<Question>> getPendingQuestions() {
        List<Question> questions = questionService.getPendingQuestions();
        return Result.success(questions);
    }

    @Operation(summary = "更新题目", description = "更新题目信息，支持部分字段更新")
    @PutMapping("/{questionId}")
    public Result<Question> updateQuestion(
            @Parameter(description = "题目UUID") @PathVariable String questionId,
            @RequestBody QuestionUpdateRequest request) {
        try {
            Question existing = questionService.getByQuestionId(questionId);
            if (existing == null) {
                return Result.error(404, "题目不存在");
            }

            Question updated = questionService.updateQuestion(existing.getId(), request);
            log.info("更新题目成功: questionId={}", questionId);
            return Result.success("题目更新成功", updated);
        } catch (Exception e) {
            log.error("更新题目失败: {}", e.getMessage(), e);
            return Result.error(500, "更新题目失败: " + e.getMessage());
        }
    }

    @Operation(summary = "删除题目", description = "根据UUID删除题目")
    @DeleteMapping("/{questionId}")
    public Result<Void> deleteQuestion(
            @Parameter(description = "题目UUID") @PathVariable String questionId) {
        try {
            Question existing = questionService.getByQuestionId(questionId);
            if (existing == null) {
                return Result.error(404, "题目不存在");
            }

            boolean success = questionService.deleteById(existing.getId());
            if (success) {
                log.info("删除题目成功: questionId={}", questionId);
                return Result.success("题目删除成功");
            } else {
                return Result.error(500, "删除题目失败");
            }
        } catch (Exception e) {
            log.error("删除题目失败: {}", e.getMessage(), e);
            return Result.error(500, "删除题目失败: " + e.getMessage());
        }
    }

    @Operation(summary = "批量删除题目", description = "根据ID列表批量删除题目")
    @DeleteMapping("/batch")
    public Result<Integer> batchDeleteQuestions(
            @Parameter(description = "题目ID列表") @RequestParam String ids) {
        try {
            List<Long> idList = Arrays.stream(ids.split(","))
                    .map(String::trim)
                    .filter(s -> !s.isEmpty())
                    .map(Long::parseLong)
                    .collect(Collectors.toList());

            if (idList.isEmpty()) {
                return Result.error(400, "ID列表不能为空");
            }

            int deletedCount = questionService.batchDelete(idList);
            log.info("批量删除题目成功: count={}", deletedCount);
            return Result.success("批量删除成功", deletedCount);
        } catch (NumberFormatException e) {
            return Result.error(400, "ID格式不正确，请提供逗号分隔的数字ID");
        } catch (Exception e) {
            log.error("批量删除题目失败: {}", e.getMessage(), e);
            return Result.error(500, "批量删除失败: " + e.getMessage());
        }
    }

    @Operation(summary = "审核题目", description = "审核通过或拒绝题目")
    @PutMapping("/review/{questionId}")
    public Result<Void> reviewQuestion(
            @Parameter(description = "题目UUID") @PathVariable String questionId,
            @Parameter(description = "审核状态：approved/rejected") @RequestParam String status,
            @Parameter(description = "审核评论") @RequestParam(required = false) String reviewerComment) {
        if (!"approved".equals(status) && !"rejected".equals(status)) {
            return Result.error(400, "审核状态必须是approved或rejected");
        }
        boolean success = questionService.updateReviewStatus(questionId, status, reviewerComment);
        if (success) {
            return Result.success("审核操作成功");
        } else {
            return Result.error(500, "审核失败");
        }
    }

    @Operation(summary = "条件查询题目列表", description = "根据多种条件查询题目，支持按用户权限过滤（本人库、本部门库、公共库）")
    @GetMapping("/list")
    public Result<List<Question>> listQuestions(
            @Parameter(description = "题目类型") @RequestParam(required = false) String questionType,
            @Parameter(description = "难度等级") @RequestParam(required = false) Integer difficulty,
            @Parameter(description = "审核状态") @RequestParam(required = false) String status,
            @Parameter(description = "文档名称") @RequestParam(required = false) String documentName,
            @Parameter(description = "返回数量限制") @RequestParam(defaultValue = "100") Integer limit,
            HttpServletRequest httpRequest) {
        try {
            String token = httpRequest.getHeader("Authorization");
            if (token == null || !token.startsWith("Bearer ")) {
                return Result.error(401, "用户未登录");
            }
            top.tqx.demo_1.entity.User user = authService.validateToken(token.substring(7));
            if (user == null) {
                return Result.error(401, "用户未登录");
            }
            Long userId = user.getId();
            Long deptId = user.getDeptId();
            Integer userType = user.getUserType();
            log.info("条件查询题目列表: userId={}, deptId={}, userType={}, questionType={}, difficulty={}, status={}, documentName={}, limit={}",
                    userId, deptId, userType, questionType, difficulty, status, documentName, limit);
            List<Question> questions = questionService.listQuestions(questionType, difficulty, status, documentName, limit, userId, deptId, userType);
            return Result.success(questions);
        } catch (Exception e) {
            log.error("查询题目列表失败: {}", e.getMessage(), e);
            return Result.error(500, "查询失败: " + e.getMessage());
        }
    }

    @Operation(summary = "题目数量统计", description = "按不同维度统计题目数量")
    @PostMapping("/stats")
    public Result<QuestionStatsResponse> getQuestionStats(@RequestBody QuestionStatsRequest request) {
        try {
            log.info("题目数量统计请求: deptId={}, fileIds={}, collection={}, questionTypes={}, status={}",
                    request.getDeptId(), request.getFileIds(), request.getCollection(),
                    request.getQuestionTypes(), request.getStatus());

            QuestionStatsResponse response = questionService.getQuestionStats(request);
            return Result.success("统计成功", response);
        } catch (Exception e) {
            log.error("题目数量统计失败: {}", e.getMessage(), e);
            return Result.error(500, "统计失败: " + e.getMessage());
        }
    }
}
