package com.ruoyi.web.controller.basic;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.RestResponse;
import com.ruoyi.basic.domain.dto.AnswerSubmitDTO;
import com.ruoyi.basic.domain.model.AnswerResultVO;
import com.ruoyi.basic.domain.model.QuestionnaireVO;
import com.ruoyi.basic.domain.question.QuestionSurvey;
import com.ruoyi.basic.mapper.QuestionSurveyMapper;
import com.ruoyi.basic.service.QuestionnaireService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/questionnaire")
@RequiredArgsConstructor
@Validated
public class QuestionnaireController {

    private final QuestionnaireService questionnaireService;
    private final QuestionSurveyMapper surveyMapper;

    /**
     * 获取所有已发布的问卷列表（简要信息）
     * @return 问卷列表
     */
    @GetMapping("/list")
    public RestResponse listSurveys() {
        List<QuestionSurvey> surveys = surveyMapper.selectList(
                new LambdaQueryWrapper<QuestionSurvey>()
                        .eq(QuestionSurvey::getStatus, 1)  // 只返回已发布的
                        .orderByDesc(QuestionSurvey::getCreateTime)
        );
        List<QuestionSurveyBriefVO> briefList = surveys.stream()
                .map(s -> new QuestionSurveyBriefVO(s.getId(), s.getTitle(), s.getDescription()))
                .collect(Collectors.toList());
        return RestResponse.success().setData(briefList);
    }

    /**
     * 获取问卷详情（包含体质、题目、选项）
     * @return 问卷完整结构
     */
    @GetMapping("/getOne")
    public RestResponse getQuestionnaire() {
        QuestionnaireVO vo = questionnaireService.getQuestionnaire();
        if (vo == null) {
            return RestResponse.failure("问卷不存在或未发布");
        }
        return RestResponse.success().setData(vo);
    }

    /**
     * 提交问卷答案并获取评估结果
     * @param dto 答案提交数据
     * @param request Http请求（用于获取IP）
     * @return 评估结果
     */
    @PostMapping("/submit")
    public RestResponse submit(@Valid @RequestBody AnswerSubmitDTO dto,
                                              HttpServletRequest request) {
        try {
            AnswerResultVO result = questionnaireService.submitAnswers(dto, request);
            return RestResponse.success().setData(result);
        } catch (IllegalArgumentException e) {
            log.warn("参数校验失败: {}", e.getMessage());
            return RestResponse.failure(e.getMessage());
        } catch (Exception e) {
            log.error("提交答案失败", e);
            return RestResponse.failure("提交失败，请稍后重试");
        }
    }

    /**
     * 根据答卷ID查询结果
     * @return 评估结果
     */
    @GetMapping("/result")
    public RestResponse getResult() {
        AnswerResultVO result = questionnaireService.getResultBySheetId();
        if (result == null) {
            return RestResponse.failure("答卷不存在");
        }
        return RestResponse.success().setData(result);
    }

    /**
     * 问卷简要信息（内部类）
     */
    @lombok.Data
    @lombok.AllArgsConstructor
    public static class QuestionSurveyBriefVO {
        private Long id;
        private String title;
        private String description;
    }
}
