package com.ruoyi.abuwx.controller.exam;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.abuwx.domain.exam.ExmQuestion;
import com.ruoyi.abuwx.domain.exam.ExmQuestionAnswer;
import com.ruoyi.abuwx.domain.exam.ExmQuestionOption;
import com.ruoyi.abuwx.service.exam.IExmQuestionAnswerService;
import com.ruoyi.abuwx.service.exam.IExmQuestionOptionService;
import com.ruoyi.abuwx.service.exam.IExmQuestionService;
import com.ruoyi.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
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.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 试题Controller
 * 
 * @author ruoyi
 * @date 2024-05-17
 */
@RestController
@RequestMapping("/system/question")
@Api(tags = "试题管理")
public class ExmQuestionController extends BaseController
{
    @Autowired
    private IExmQuestionService exmQuestionService;

    @Autowired
    private IExmQuestionOptionService questionOptionService;

    @Resource
    private IExmQuestionAnswerService questionAnswerService;

    /**
     * 查询试题列表
     */
    @ApiOperation("试卷列表")
    @PreAuthorize("@ss.hasPermi('system:question:list')")
    @GetMapping("/list")
    public TableDataInfo list(ExmQuestion exmQuestion)
    {
        startPage();
        List<ExmQuestion> list = exmQuestionService.selectExmQuestionList(exmQuestion);
        list.stream().forEach(question->{
            Long id = (Long) question.getId();
            Integer type = (Integer) question.getType();
            Integer markType = (Integer) question.getMarkType();

            if (question.getMarkOptions()!= null) {// 前后端分离下，接口定义只有数组形式
                question.setMarkOptionVos(StringUtils.toIntList((String)question.getMarkOptions()));
            } else {
                question.setMarkOptionVos(new ArrayList<>());
            }

            if (type == 1 || type == 2) {// 如果是单选或多选，添加选项字段
                List<ExmQuestionOption> questionOptionList = questionOptionService.getList(id);
                List<String> options = new ArrayList<>();
                for (ExmQuestionOption questionOption : questionOptionList) {
                    options.add(questionOption.getOptions());
                }
                question.setQuestionOptions(options);
            }

            List<ExmQuestionAnswer> questionAnswerList = questionAnswerService.getList(id);
            List<String> answers = new ArrayList<>();
            List<BigDecimal> scores = new ArrayList<>();
            for(ExmQuestionAnswer answer : questionAnswerList){
                if (type == 1 || type == 4 || (type == 5 && markType == 2)) {
                    answers.add(answer.getAnswer());
                } else if (type == 2) {
                    Collections.addAll(answers, answer.getAnswer().split(","));
                    scores.add(answer.getScore());
                } else if (type == 3 || (type == 5 && markType == 1)) {
                    answers.add(answer.getAnswer());
                    scores.add(answer.getScore());
                }
            }
            question.setQuestionAnswers(answers);
            question.setScores(scores);
        });
        return getDataTable(list);
    }

    /**
     * 导出试题列表
     */
    @ApiOperation("导出")
    @PreAuthorize("@ss.hasPermi('system:question:export')")
    @Log(title = "试题", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ExmQuestion exmQuestion)
    {
        List<ExmQuestion> list = exmQuestionService.selectExmQuestionList(exmQuestion);
        ExcelUtil<ExmQuestion> util = new ExcelUtil<ExmQuestion>(ExmQuestion.class);
        util.exportExcel(response, list, "试题数据");
    }

    /**
     * 获取试题详细信息
     */
    @ApiOperation("详情")
    @PreAuthorize("@ss.hasPermi('system:question:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(exmQuestionService.selectExmQuestionById(id));
    }

    /**
     * 新增试题
     */
    @ApiOperation("新增")
    @PreAuthorize("@ss.hasPermi('system:question:add')")
    @Log(title = "试题", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ExmQuestion exmQuestion)
    {
        return toAjax(exmQuestionService.insertExmQuestion(exmQuestion));
    }

    /**
     * 修改试题
     */
    @ApiOperation("修改")
    @PreAuthorize("@ss.hasPermi('system:question:edit')")
    @Log(title = "试题", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ExmQuestion exmQuestion)
    {
        return toAjax(exmQuestionService.updateExmQuestion(exmQuestion));
    }

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