package com.ruoyi.web.controller.learn;

import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.enums.CardAction;
import com.ruoyi.enums.QuestionType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.learn.domain.LearnQuestions;
import com.ruoyi.learn.domain.LearnKnowledgeQuestion;
import com.ruoyi.learn.domain.LearnKnowledgeTree;
import com.ruoyi.learn.domain.LearnKnowledgeTree2;
import com.ruoyi.learn.service.ILearnQuestionsService;
import com.ruoyi.learn.service.ILearnKnowledgeQuestionService;
import com.ruoyi.learn.service.ILearnKnowledgeTreeService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 试题Controller
 *
 * @author ruoyi
 * @date 2025-09-18
 */
@RestController
@RequestMapping("/learn/questions")
@Api(tags = "后台-学习 - 题")
public class LearnQuestionsController extends BaseController
{
    @Autowired
    private ILearnQuestionsService learnQuestionsService;

    @Autowired
    private ILearnKnowledgeQuestionService learnKnowledgeQuestionService;

    @Autowired
    private ILearnKnowledgeTreeService learnKnowledgeTreeService;

    /**
     * 查询试题列表
     */
    @PreAuthorize("@ss.hasPermi('learn:questions:list')")
    @GetMapping("/list")
    @ApiOperation("查询列表")
    public TableDataInfo list(LearnQuestions learnQuestions)
    {
        if(null != learnQuestions.getTypeId()) {
            QuestionType qt = QuestionType.of(learnQuestions.getTypeId());
            learnQuestions.setQtpye(qt.getTitle());
            learnQuestions.setTypeId(null);
        }
        startPage();
        List<LearnQuestions> list = learnQuestionsService.selectLearnQuestionsList(learnQuestions);
        
        // 查询知识点并设置到题目中
        if (!list.isEmpty()) {
            List<Long> questionIds = list.stream().map(LearnQuestions::getId).collect(Collectors.toList());
            // 直接查询知识点（包含questionId）
            List<LearnKnowledgeTree2> knowledgeList = learnKnowledgeTreeService.selectLearnKnowledgeByQuestionIds(questionIds);
            if (!knowledgeList.isEmpty()) {
                // 按题目ID分组知识点
                java.util.Map<Long, List<LearnKnowledgeTree2>> questionKnowledgeMap = knowledgeList.stream()
                    .collect(Collectors.groupingBy(LearnKnowledgeTree2::getQuestionId, Collectors.toList()));
                // 设置到每个题目
                list.forEach(q -> q.setKnowledgeTrees(questionKnowledgeMap.get(q.getId())));
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出试题列表
     */
    @PreAuthorize("@ss.hasPermi('learn:questions:export')")
    @Log(title = "试题", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, LearnQuestions learnQuestions)
    {
        List<LearnQuestions> list = learnQuestionsService.selectLearnQuestionsList(learnQuestions);
        ExcelUtil<LearnQuestions> util = new ExcelUtil<LearnQuestions>(LearnQuestions.class);
        util.exportExcel(response, list, "试题数据");
    }

    /**
     * 获取试题详细信息
     */
    @PreAuthorize("@ss.hasPermi('learn:questions:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(learnQuestionsService.selectLearnQuestionsById(id));
    }

    /**
     * 新增试题
     */
    @PreAuthorize("@ss.hasPermi('learn:questions:add')")
    @Log(title = "试题", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody LearnQuestions learnQuestions)
    {
        return toAjax(learnQuestionsService.insertLearnQuestions(learnQuestions));
    }

    /**
     * 修改试题
     */
    @PreAuthorize("@ss.hasPermi('learn:questions:edit')")
    @Log(title = "试题", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody LearnQuestions learnQuestions)
    {
        return toAjax(learnQuestionsService.updateLearnQuestions(learnQuestions));
    }

    /**
     * 删除试题
     */
    @PreAuthorize("@ss.hasPermi('learn:questions:remove')")
    @Log(title = "试题", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(learnQuestionsService.deleteLearnQuestionsByIds(ids));
    }

    @Log(title = "修改题型", businessType = BusinessType.UPDATE)
    @PostMapping("/changeType")
    @ApiOperation("修改题型")
    public AjaxResult updateQuestionType(@RequestBody JSONObject param)
    {
        QuestionType qt = QuestionType.of(param.getInteger("type"));
        List<Long> ids = param.getList ("ids", Long.class);
        learnQuestionsService.updateQuestionType(qt.getTitle(), ids);
        return AjaxResult.success();
    }
}
