package com.ruoyi.web.controller.front;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.content.VistorContextHolder;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.AjaxResult2;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.NumberUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.dz.domain.DzControl;
import com.ruoyi.dz.domain.DzSubject;
import com.ruoyi.dz.service.IDzControlService;
import com.ruoyi.dz.service.IDzSubjectService;
import com.ruoyi.enums.PaperType;
import com.ruoyi.learn.domain.LearnPaper;
import com.ruoyi.learn.domain.LearnStudent;
import com.ruoyi.learn.domain.LearnTest;
import com.ruoyi.learn.service.ILearnPaperService;
import com.ruoyi.learn.service.ILearnStudentService;
import com.ruoyi.learn.service.ILearnTestService;
import com.ruoyi.web.service.LearnTeacherService;
import com.ruoyi.web.service.PaperService;
import com.ruoyi.web.service.StudentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/front/paper")
@Api(tags = "前台-学习-试卷")
public class FrontPaperController {
    private final IDzControlService dzControlService;
    private final IDzSubjectService dzSubjectService;
    private final PaperService paperService;
    private final ILearnPaperService learnPaperService;
    private final ILearnTestService testService;
    private final ILearnStudentService learnStudentService;
    private final LearnTeacherService learnTeacherService;
    private final StudentService studentService;

    public FrontPaperController(IDzControlService dzControlService, IDzSubjectService dzSubjectService, PaperService paperService, ILearnPaperService learnPaperService, ILearnTestService testService, ILearnStudentService learnStudentService, LearnTeacherService learnTeacherService, StudentService studentService) {
        this.dzControlService = dzControlService;
        this.dzSubjectService = dzSubjectService;
        this.paperService = paperService;
        this.learnPaperService = learnPaperService;
        this.testService = testService;
        this.learnStudentService = learnStudentService;
        this.learnTeacherService = learnTeacherService;
        this.studentService = studentService;
    }

    @ApiOperation("01 考试批次")
    @GetMapping(value = "batch")
    public List<LearnTest> getBatch() {
        DzControl dzControl = dzControlService.selectDzControl(VistorContextHolder.getContext());
        LearnTest cond = new LearnTest();
        cond.setYear(dzControl.getPlanYear());
        return testService.selectLearnTestList(cond);
    }

    @ApiOperation("02 考试科目")
    @GetMapping(value = "subject")
    public AjaxResult2<List<DzSubject>> getSubject(@ApiParam("定向") @RequestParam(defaultValue = "false") boolean directed) {
        return AjaxResult2.success(studentService.getSubjectList(directed));
    }

    @ApiOperation("03 知识点树")
    @GetMapping(value = "knowledge")
    public AjaxResult getKnowledge(@ApiParam("定向") @RequestParam(defaultValue = "false") boolean directed, @ApiParam("科目ID") Long subjectId,
                                   @ApiParam("考卷题类别0普通2必刷") @RequestParam(required = false) Integer questionType) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Set<Long> knowledgeIdSet = null;
        if(directed) {
            LearnStudent learnStudent = learnStudentService.selectLearnStudentByStudentId(sysUser.getUserId());
            if(null != learnStudent) {
                knowledgeIdSet = learnTeacherService.getKnowledgeIdSet(subjectId, learnStudent.getMajorPlanId(), dzControlService.selectDzControl(sysUser).getPlanYear(), sysUser.getExamType().name());
            }
        }
        List<LearnTeacherService.TreeNode> nodeList = learnTeacherService.getKnowledgeTree(sysUser.getExamType().title(), subjectId, knowledgeIdSet, sysUser.getUserId(), questionType);
        if(CollectionUtils.isEmpty(knowledgeIdSet)) {
            return AjaxResult.success(nodeList);
        }
        List<LearnTeacherService.TreeNode> finalList = Lists.newArrayList();
        for(LearnTeacherService.TreeNode parent : nodeList) {
            if(CollectionUtils.isEmpty(parent.getChildren())) {
                if(parent.getQuestionCount() > 0 && parent.getStatus().equals(1)) {
                    finalList.add(parent);
                }
                continue;
            }
            parent.setQuestionCount(0);
            parent.setFinishedCount(0);
            parent.setRightCount(0);
            List<LearnTeacherService.TreeNode> childList = Lists.newArrayList();
            for(LearnTeacherService.TreeNode child : parent.getChildren()) {
                if(child.getStatus().equals(1)) { // TODO 暂不过滤无题的  && child.getQuestionCount() > 0
                    childList.add(child);
                    parent.setQuestionCount(parent.getQuestionCount() + child.getQuestionCount());
                    parent.setFinishedCount(parent.getFinishedCount() + child.getFinishedCount());
                    parent.setRightCount(parent.getRightCount() + child.getRightCount());
                }
            }
            parent.calcRatio();
            if(childList.size() > 0) {
                parent.setChildren(childList);
                finalList.add(parent);
            }
        }
        return AjaxResult.success(finalList);
    }

    @ApiOperation("03 课程同步知识点树")
    @GetMapping(value = "courseKnowledge")
    public AjaxResult getCourseKnowledge() {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        List<LearnTeacherService.TreeNode> nodeList = learnTeacherService.getCourseKnowledgeTree(sysUser.getUserId());
        return AjaxResult.success(nodeList);
    }

    @ApiOperation("04 取试卷")
    @GetMapping(value = "paper")
    public AjaxResult loadPaper(@ApiParam("考卷类型PaperType") PaperType type, @ApiParam("考卷标识") Long id) {
        return AjaxResult.success(paperService.loadPaper(id));
    }

    @ApiOperation("05 取模拟卷列表")
    @GetMapping("/list")
    public AjaxResult2<List<JSONObject>> list(LearnPaper learnPaper) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        learnPaper.setPaperType(PaperType.Simulated.name());
        String subjectKey = NumberUtils.isPositive(learnPaper.getSubjectId()) ? String.valueOf(sysUser.getExamMajor()) : "0";
        learnPaper.setLocations(sysUser.getLocation());
        learnPaper.setDirectKey(sysUser.getExamType().name() + "_" + subjectKey);
        learnPaper.setSubjectId(null);
        learnPaper.setStatus(1);
        learnPaper.setExamineeId(sysUser.getUserId());
        List<LearnPaper> list = learnPaperService.selectLearnPaperForExam(learnPaper);
        Map<Long, String> subjectMap = dzSubjectService.selectDzSubjectList(new DzSubject()).stream().collect(Collectors.toMap(DzSubject::getSubjectId, DzSubject::getSubjectName));
        List<JSONObject> jsonList = list.stream().map(t -> {
            JSONObject o = JSONObject.from(t);
            o.put("subjectName", subjectMap.get(t.getSubjectId()));
            return o;
        }).collect(Collectors.toList());
        return AjaxResult2.success(jsonList);
    }
}
