package com.ruoyi.web.controller.front;

import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.ExamType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.dz.domain.DzSubject;
import com.ruoyi.dz.service.IDzSubjectService;
import com.ruoyi.enums.PaperType;
import com.ruoyi.learn.domain.AnswerSheet;
import com.ruoyi.learn.domain.LearnCultureKnowledge;
import com.ruoyi.learn.domain.LearnStudent;
import com.ruoyi.learn.service.ILearnCultureKnowledgeService;
import com.ruoyi.learn.service.ILearnStudentService;
import com.ruoyi.mxjb.domain.MxjbContants;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.syzy.domain.BBusiWishUniversities;
import com.ruoyi.syzy.service.IBBusiWishUniversitiesService;
import com.ruoyi.web.domain.PaperDto;
import com.ruoyi.web.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/front/exam")
@Api(tags = "前台-学习-考试练习")
public class FrontExamController {
    private final ExamService examService;
    private final SyTestMajorService syTestMajorService;
    private final CacheService cacheService;
    private final IDzSubjectService dzSubjectService;
    private final StudentService studentService;
    private final ISysUserService sysUserService;
    private final ILearnStudentService learnStudentService;
    private final ILearnCultureKnowledgeService learnCultureKnowledgeService;
    private final IBBusiWishUniversitiesService wishUniversitiesService;
    private final LearnTeacherService learnTeacherService;

    public FrontExamController(ExamService examService, SyTestMajorService syTestMajorService, CacheService cacheService, IDzSubjectService dzSubjectService, IDzSubjectService dzSubjectService1, StudentService studentService, ISysUserService sysUserService, ILearnStudentService learnStudentService, ILearnCultureKnowledgeService learnCultureKnowledgeService, IBBusiWishUniversitiesService wishUniversitiesService, LearnTeacherService learnTeacherService) {
        this.examService = examService;
        this.syTestMajorService = syTestMajorService;
        this.cacheService = cacheService;
        this.dzSubjectService = dzSubjectService1;
        this.studentService = studentService;
        this.sysUserService = sysUserService;
        this.learnStudentService = learnStudentService;
        this.learnCultureKnowledgeService = learnCultureKnowledgeService;
        this.wishUniversitiesService = wishUniversitiesService;
        this.learnTeacherService = learnTeacherService;
    }

    @GetMapping("/subjects")
    @ApiOperation("科目列表")
    public AjaxResult subjects()
    {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Long[] subjectIds;
        if(ExamType.SVS.equals(sysUser.getExamType())) {
            Set<Long> subjectIdSet;
            LearnStudent ls = learnStudentService.selectLearnStudentByStudentId(sysUser.getUserId());
            if(null != ls && null != ls.getMajorPlanId()) {
                subjectIdSet = learnTeacherService.getLearnCultureKnowledgeList(ls.getMajorPlanId()).stream().map(t -> Long.parseLong(t.getSubjects())).collect(Collectors.toSet());
                if(subjectIdSet.isEmpty()) {
                    BBusiWishUniversities u = wishUniversitiesService.selectBBusiWishUniversitiesById(ls.getUniversityId());
                    if(null != u.getBxLevel() && u.getBxLevel().contains("民办")) {
                        subjectIdSet.add(1L);
                        subjectIdSet.add(2L);
                        subjectIdSet.add(3L);
                    }
                }
            } else {
                subjectIdSet = Sets.newHashSet();
            }
            subjectIdSet.add(11L);
            subjectIds = subjectIdSet.toArray(new Long[subjectIdSet.size()]);
        } else {
            subjectIds = new Long[] {11L};
        }
        List<DzSubject> list = dzSubjectService.selectDzSubjectBySubjectIds(subjectIds); // 中职暂停 1L, 2L, 3L,
        JSONObject evalCounts = JSONObject.parseObject(sysUserService.selectUserById(sysUser.getUserId()).getEvalCounts());
        return AjaxResult.success(list.stream().map(t -> {
            JSONObject o = new JSONObject();
            o.put("subjectId", t.getSubjectId());
            o.put("subject", t.getSubjectName());
            o.put("examTime", evalCounts.getIntValue(t.getSubjectId().toString()));
            return o;
        }).collect(Collectors.toList()));
    }

    // 试卷: 真题卷,批次测试卷,自组卷, 生成考试记录
    // 定向模拟卷: 根据用户选择生成记录
    // 组卷: 知识点 错题 必刷题 实时组卷后才生成记录
    @ApiOperation("01 开卷")
    @PostMapping(value = "openExaminee")
    public AjaxResult openExaminee(@ApiParam("0默认1价值2职业3知识") @RequestParam(required = false) Integer testType,
                                   @ApiParam("定向") @RequestParam(defaultValue = "false") boolean directed,
                                   @ApiParam("考卷类型PaperType") @RequestParam(required = false) PaperType paperType,
                                   @ApiParam("考卷类型关联ID") @RequestParam(required = false) Long relateId,
                                   @ApiParam("考卷类型关联ID") @RequestParam(required = false) Long subjectId,
                                   @ApiParam("考卷题类别0普通2必刷") @RequestParam(required = false) Integer questionType,
                                   @RequestBody JSONObject body) {
        if(null != testType && testType > 0) {
            PaperDto paperDto = syTestMajorService.loadPaperByTestMajorTypeId(testType);
            Map<String, String> stateMap = cacheService.selectDictDataMapByType(MxjbContants.StateTypeExaminee);
            paperDto.setStateStr(stateMap.get(String.valueOf(paperDto.getState())));
            paperDto.calculateAllow();
            return AjaxResult.success(paperDto);
        }
        if(null == subjectId && null == paperType) {
            subjectId = body.getLongValue("subjectId");
            paperType = PaperType.valueOf(body.getString("paperType"));
            questionType = body.getInteger("questionType");
        }
        return AjaxResult.success(examService.openExaminee(directed, paperType, relateId, subjectId, questionType));
    }

    @ApiOperation("04 开始考试")
    @GetMapping(value = "beginExaminee")
    public AjaxResult beginExaminee(@ApiParam("答卷ID") Long examineeId) {
        // 检查状态，以决定是否返回答案
        return AjaxResult.success(examService.loadExaminee(examineeId, true));
    }

    @ApiOperation("04 取答卷")
    @GetMapping(value = "loadExaminee")
    public AjaxResult loadExaminee(@ApiParam("答卷ID") @RequestParam(required = false) Long examineeId) {
        return AjaxResult.success(examService.loadExaminee(examineeId, false));
    }

    @ApiOperation("02 交卷")
    @PostMapping(value = "commitExamineePaper")
    public AjaxResult commitExamineePaper(@RequestBody AnswerSheet answerSheet) {
        if(null == answerSheet.getIsDone()) {
            answerSheet.setIsDone(false);
        }
        examService.commitAnswerSheet(answerSheet);
        return AjaxResult.success();
    }

    @ApiOperation("02 原交卷,测试")
    @PostMapping(value = "commitTestPaper")
    public AjaxResult commitExamineePaper(@RequestBody PaperDto paperDto) {
        return syTestMajorService.saveTestPaper(paperDto);
    }

    /*@ApiOperation("02 答题")
    @PostMapping(value = "commitExamineeQuestion")
    public AjaxResult commitExamineeQuestion(@RequestBody PaperDto paperDto) {
        return adminExaminationService.saveQuestion(paperDto);
    }


    @ApiOperation("04 阅卷打分")
    @PostMapping(value = "scoreExamineeQuestions")
    public AjaxResult scoreExamineeQuestions(@RequestBody PaperDto paperDto) {
        if (MxjbContants.ExamineeTypeIeValue.equals(paperDto.getExamineeType())) {
            return mxjbPaperExamService.scoreExamineeQuestion(paperDto, true);
        }
        return AjaxResult.error("不支持: " + paperDto.getExamineeType());
    }

    @ApiOperation("05 阅卷结束")
    @PostMapping(value = "scoreFinish")
    public AjaxResult scoreFinish(
            @ApiParam("考生答卷Id") @RequestParam Long examineeId,
            @ApiParam("考生类型 1是测评evaluation(default)，2是竞赛competitor 3 ai 5 homework 6 ie") @RequestParam(required = false, defaultValue = "1") Integer examineeType) {
        if (MxjbContants.ExamineeTypeIeValue.equals(examineeType)) {
            return mxjbPaperExamService.scoreFinish(examineeId);
        }
        return AjaxResult.error("不支持： " + examineeType);
    }
    @ApiOperation("06 查看题")
    @GetMapping(value = "openQuestion")
    public QuestionDto openQuestion(@ApiParam("考生答卷Id") @RequestParam Long examineeId, @ApiParam("考生试题ID") @RequestParam Long questionId,
                                    @ApiParam("考生类型 1是测评evaluation(default)，2是竞赛competitor 3 ai 5 homework 6 ie") @RequestParam(required = false, defaultValue = "1") Integer examineeType) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (MxjbContants.ExamineeTypeIeValue.equals(examineeType)) {
            return mxjbPaperExamService.openQuestion(examineeId, loginUser.getUser().getUserId(), questionId);
        }
        return new QuestionDto();
    }
*/
}
