package com.ruoyi.web.controller.learn;

import cn.hutool.core.lang.Dict;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.Lists;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.AjaxResult2;
import com.ruoyi.common.enums.ExamType;
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.LearnTestPaper;
import com.ruoyi.learn.domain.TestPaperVO;
import com.ruoyi.learn.service.ILearnPaperQuestionService;
import com.ruoyi.learn.service.ILearnPaperService;
import com.ruoyi.learn.service.ILearnTestPaperService;
import com.ruoyi.web.service.LearnTeacherService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/learn/teaching")
@Api(tags = "后台-学习 - 老师业务")
public class LearnTeacherController extends BaseController {
    private final IDzControlService dzControlService;
    private final IDzSubjectService dzSubjectService;
    private final LearnTeacherService learnTeacherService;
    private final ILearnPaperService paperService;
    private final ILearnTestPaperService testPaperService;
    private final ILearnPaperQuestionService paperQuestionService;

    public LearnTeacherController(IDzControlService dzControlService, IDzSubjectService dzSubjectService, LearnTeacherService learnTeacherService, ILearnPaperService paperService, ILearnTestPaperService testPaperService, ILearnPaperQuestionService paperQuestionService) {
        this.dzControlService = dzControlService;
        this.dzSubjectService = dzSubjectService;
        this.learnTeacherService = learnTeacherService;
        this.paperService = paperService;
        this.testPaperService = testPaperService;
        this.paperQuestionService = paperQuestionService;
    }

    /**
     -- 1. 查询考试批次(假设每个老师自已控制)
     -- 2. 查询班老师班级列表
     -- 3. 查询定向院校列表
     -- 5. 查询定向院校专业组
     -- 6. 查询科目(分是否定向)
     -- 7. 查询知识点(分是否定向)
     -- 8. 查询单个定向时知识点树
     -- 9. 设置题型数量(预置题型要求，或人工指定，不指定时平均分配， 题型是针对院校的)
     */


    @GetMapping(value = "provinces")
    @Anonymous
    @ApiOperation("省份列表")
    public AjaxResult provinces()
    {
        DzControl cond = new DzControl();
        cond.setIsValid(1);
        return AjaxResult.success(dzControlService.selectDzControlList(cond).stream().map(t -> {
            JSONObject o = new JSONObject();
            o.put("dictValue", t.getLocation());
            o.put("dictLabel", t.getLocation());
            return o;
        }).collect(Collectors.toList()));
    }

    @GetMapping(value = "examTypes")
    @Anonymous
    @ApiOperation("考生类型列表")
    public AjaxResult examTypes(@RequestParam String location)
    {
        DzControl cond = new DzControl();
        cond.setIsValid(1);
        cond.setLocation(location);
        List<DzControl> list = dzControlService.selectDzControlList(cond);
        String examTypes;
        if(CollectionUtils.isEmpty(list) || StringUtils.isBlank(examTypes = list.get(0).getExamTypes())) {
            return AjaxResult.success(Collections.emptyList());
        }
        return AjaxResult.success(Arrays.stream(examTypes.split(",")).map(t -> {
            JSONObject o = new JSONObject();
            o.put("dictValue", t);
            o.put("dictLabel", ExamType.valueOf(t).title());
            return o;
        }).collect(Collectors.toList()));
    }

    @GetMapping("/classes")
    @ApiOperation("2. 班级列表")
    public AjaxResult classes()
    {
        return AjaxResult.success(learnTeacherService.getClasses(getUserId()));
    }

    @GetMapping("/students")
    @ApiOperation("学生列表")
    public AjaxResult students(@ApiParam("批次ID") Long batchId)
    {
        return AjaxResult.success(learnTeacherService.getStudents(batchId, getUserId()));
    }

    @GetMapping("/universities")
    @ApiOperation("院校列表")
    public AjaxResult universities(@ApiParam("批次ID") Long batchId)
    {
        return AjaxResult.success(learnTeacherService.selectUniversityList(getUserId(), batchId));
    }

    @GetMapping("/majors")
    @ApiOperation("专业列表")
    public AjaxResult majors(@ApiParam("省份") String location, @ApiParam("考生类型") ExamType examType, @ApiParam("批次ID") Long batchId, @RequestParam(required = false) @ApiParam("院校列表") Long universityId)
    {
        DzControl control = dzControlService.selectDzControl(location, examType);
        return AjaxResult.success(learnTeacherService.selectMajorList(universityId, control.getPlanYear(), batchId));
    }

    @GetMapping("/subjects")
    @ApiOperation("科目列表")
    public AjaxResult2<List<DzSubject>> subjects(@RequestParam(required = false) @ApiParam("院校列表") Long universityId)
    {
        DzSubject sCond = new DzSubject();
        List<DzSubject> list = dzSubjectService.selectDzSubjectList(sCond);
        return AjaxResult2.success(list);
    }

    @GetMapping("/knowledges")
    @ApiOperation("知识点列表")
    public AjaxResult knowledges(@ApiParam("科目ID") Long subjectId, @RequestParam(required = false) @ApiParam("专业计划ID") Long[] majorPlanIds)
    {
        return AjaxResult.success(learnTeacherService.getKnowledgeTree(subjectId, majorPlanIds));
    }

    @GetMapping("/questionTypes")
    @ApiOperation("题型列表")
    public AjaxResult questionTypes(@ApiParam("科目ID") Long subjectId, @RequestParam(required = false) @ApiParam("专业计划ID") Long[] knowledgeIds)
    {
        List<Dict> dictList = Lists.newArrayList();
        dictList.add(Dict.create().set("dictLabel", "单选题").set("dictValue", "1"));
        dictList.add(Dict.create().set("dictLabel", "多选题").set("dictValue", "2"));
        dictList.add(Dict.create().set("dictLabel", "判断题").set("dictValue", "3"));
        dictList.add(Dict.create().set("dictLabel", "分析题").set("dictValue", "4"));
        return AjaxResult.success(dictList);
    }

    @PreAuthorize("@ss.hasPermi('learn:test_paper:add')")
    @PostMapping("/build/auto")
    @ApiOperation("批量自动组卷")
    public AjaxResult batchBuildAuto(@RequestBody TestPaperVO.TestPapersBuildAutoReq req)
    {
        req.setBuildType(TestPaperVO.PaperBuildType.Auto);
        return AjaxResult.success(learnTeacherService.buildPapersAuto(req));
    }

    @PreAuthorize("@ss.hasPermi('learn:test_paper:add')")
    @PostMapping("/build/manual")
    @ApiOperation("批量手动组卷")
    public AjaxResult batchBuildManual(@RequestBody TestPaperVO.TestPapersBuildManualReq req)
    {
        req.setBuildType(TestPaperVO.PaperBuildType.Manual);
        return AjaxResult.success(learnTeacherService.buildPapersManual(req));
    }

    @PreAuthorize("@ss.hasPermi('learn:test_paper:query')")
    @GetMapping("/publish")
    @ApiOperation("批量发布查询")
    public AjaxResult batchQuery(@RequestBody TestPaperVO.TestPapersQueryReq req)
    {
        return AjaxResult.success(true);
    }

    @PreAuthorize("@ss.hasPermi('learn:test_paper:add')")
    @PostMapping("/publish/papers")
    @ApiOperation("批量发布生成")
    public AjaxResult publishBatch(@RequestBody TestPaperVO.TestPapersPublishReq req)
    {
        return toAjax(true);
    }

    @PreAuthorize("@ss.hasPermi('learn:test_paper:add')")
    @PostMapping("/publish/paper")
    @ApiOperation("批量发布生成")
    public AjaxResult publishSingle(@RequestBody TestPaperVO.TestPaperPublishReq req)
    {
        return toAjax(true);
    }


    @PreAuthorize("@ss.hasPermi('learn:test_paper:add')")
    @ApiOperation("04 取试卷列表")
    @GetMapping(value = "papers")
    public AjaxResult papers(@ApiParam("批次") @RequestParam(required = false) Integer batchId) {
        LearnTestPaper tpCond = new LearnTestPaper();
        tpCond.setCreatorId(SecurityUtils.getUserId());
        tpCond.setBatchId(batchId);
        List<LearnTestPaper> testPaperList = testPaperService.selectLearnTestPaperList(tpCond);
        List<JSONObject> paperList = Lists.newArrayList();
        for(LearnTestPaper tp : testPaperList) {
            JSONObject root = JSONObject.from(tp);
            root.put("paper", paperService.selectLearnPaperById(tp.getPaperId()));
            paperList.add(root);
        }
        return AjaxResult.success(paperList);
    }

    @PreAuthorize("@ss.hasPermi('learn:test_paper:add')")
    @ApiOperation("04 取试卷详情")
    @GetMapping(value = "paper")
    public AjaxResult loadPaper(@ApiParam("考卷类型PaperType") PaperType type, @ApiParam("考卷标识") Long id) {
        LearnPaper paper = paperService.selectLearnPaperById(id);
        JSONObject root = JSONObject.from(paper);
        root.put("questions", paperQuestionService.selectLearnPaperQuestionById(id));
        return AjaxResult.success(root);
    }
}
