package com.miaxis.question.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.miaxis.common.exception.CustomException;
import com.miaxis.question.domain.QuestionInfo;
import com.miaxis.question.domain.TAppExamRule;
import com.miaxis.question.dto.*;
import com.miaxis.question.mapper.QuestionInfoMapper;
import com.miaxis.question.service.IQuestionInfoService;
import com.miaxis.question.service.ITAppExamRuleService;
import com.miaxis.question.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 题库Service业务层处理
 *
 * @author miaxis
 * @date 2021-10-20
 */
@Service
public class QuestionInfoServiceImpl extends ServiceImpl<QuestionInfoMapper, QuestionInfo> implements IQuestionInfoService {
    @Autowired
    private QuestionInfoMapper questionInfoMapper;

    @Autowired
    private ITAppExamRuleService appExamRuleService;

    /**
     * 查询题库列表
     *
     * @param
     * @return 题库
     */
    @Override
    public List<QuestionInfo> selectQuestionInfoList(QuestionInfoDTO questionInfoDTO) {

        //1:分类练习：class_sort;2:精选考题:excell_sort;3:顺序练习:seque_sort;4:地方专题:place_sort
        Integer sort = questionInfoDTO.getSort();
        if (sort != null) {
            switch (sort) {
                case 1:
                    questionInfoDTO.setSortName("class_sort");
                    break;
                case 2:
                    questionInfoDTO.setSortName("excell_sort");
                    break;
                case 3:
                    questionInfoDTO.setSortName("seque_sort");
                    break;
                case 4:
                    questionInfoDTO.setSortName("place_sort");
                    break;
                default:
                    throw new CustomException("请正常输入sort字段");
            }
        }
        return questionInfoMapper.selectQuestionInfoList(questionInfoDTO);
    }

    @Override
    public List<QuestionInfo> selectQuestionInfoListByIds(Long[] ids) {
        return questionInfoMapper.selectQuestionInfoListIds(ids);
    }

    @Override
    public List<QuestionInfo> selectQuestionInfoListByYdtIds(Long[] ids) {
        return questionInfoMapper.selectQuestionInfoListByYdtIds(ids);
    }

    @Override
    public List<QuestionInfoJxVO> selectJxQuestionInfo(QuestionInfoFlDTO questionInfoFlDTO) {
        return questionInfoMapper.selectJxQuestionInfo(questionInfoFlDTO);
    }

    @Override
    public List<QuestionInfoDfVO> selectDfQuestionInfo(QuestionInfoFlDTO questionInfoFlDTO) {
        return questionInfoMapper.selectDfQuestionInfo(questionInfoFlDTO);
    }

    @Override
    public List<QuestionInfoFlVO> selectFlQuestionInfo(QuestionInfoFlDTO questionInfoFlDTO) {
        return questionInfoMapper.selectFlQuestionInfo(questionInfoFlDTO);
    }

    @Override
    public List<QuestionInfo> selectNormalQuestionInfoList(QuestionInfoDTO questionInfoDTO) {
        return questionInfoMapper.selectNormalQuestionInfoList(questionInfoDTO);
    }

    @Override
    public List<QuestionInfoSxVO> selectSxQuestionInfo(QuestionInfoFlDTO questionInfoFlDTO) {
        return questionInfoMapper.selectSxQuestionInfo(questionInfoFlDTO);
    }

    @Override
    public List<QuestionInfoExcelVo> selectQuestionInfoSortList(QuestionInfoSortDTO questionInfoSortDTO) {
        return questionInfoMapper.selectQuestionInfoSortList(questionInfoSortDTO);
    }

    @Override
    public void updateSortById(QuestionInfoSortUpateDTO dto) {
        questionInfoMapper.updateSortById(dto);
    }

    @Override
    public List<QuestionInfoExcelTypeVo> getIssueTypes(int issueTypeValue, Integer subject) {
        if (issueTypeValue == 1) {
            return questionInfoMapper.selectIssueType1(subject);
        }
        if (issueTypeValue == 2) {
            return questionInfoMapper.selectIssueType2(subject);
        }
        if (issueTypeValue == 3) {
            return questionInfoMapper.selectIssueType3(subject);
        }
        if (issueTypeValue == 4) {
            return questionInfoMapper.selectIssueType4(subject);
        }
        return null;


    }


    @Override
    public List<QuestionInfo> selectFreeQuestionInfo(QuestionInfoFreeDTO freeDTO) {
        List<QuestionInfo> list = questionInfoMapper.selectFreeQuestionInfoList(freeDTO);
        return list;
    }


    public List<QuestionInfo> selectTestQuestionInfoList(QuestionInfoTestDTO questionInfoTestDTO) {
        return questionInfoMapper.selectTestQuestionInfoList(questionInfoTestDTO);
    }

    @Override
    public List<QuestionInfo> selectTestK14QuestionInfoList2(QuestionInfoTestDTO qt) {

        int total = 100;
        if ("mtc".equals(qt.getGs())) { //如果是摩托车取题50
            total = 50;
        } else if (qt.getSubject() == 1) {
            total = 100;
        } else if (qt.getSubject() == 4) {
            total = 50;
        }

        if ("mtc".equals(qt.getGs())) {
            qt.setLiceMoto("1");
        } else if ("xc".equals(qt.getGs())) {
            qt.setLiceCar("1");
        } else if ("hc".equals(qt.getGs())) {
            qt.setLiceTruck("1");
        } else if ("kc".equals(qt.getGs())) {
            qt.setLiceBus("1");
        }

        //全题库
        List<QuestionInfo> allList = new ArrayList<QuestionInfo>();

        //判断题
        List<QuestionInfo> judgeList = new ArrayList<QuestionInfo>();
        //选择题
        List<QuestionInfo> choiceList = new ArrayList<QuestionInfo>();
        //多选题
        List<QuestionInfo> multipleList = new ArrayList<QuestionInfo>();

        //简单题
        List<Integer> easyDegree = new ArrayList<Integer>();
        easyDegree.add(1);
        easyDegree.add(2);
        easyDegree.add(3);
        //难题
        List<Integer> diffDegree = new ArrayList<Integer>();
        diffDegree.add(4);
        diffDegree.add(5);
        //科目一通用
        TAppExamRule tAppExamRule = new TAppExamRule();
        tAppExamRule.setKemu(qt.getSubject());
        tAppExamRule.setGs(qt.getGs());
        tAppExamRule.setAreacode(0);

        List<TAppExamRule> list = appExamRuleService.selectTAppExamRuleList(tAppExamRule);
        if (list.size() == 0) {
            return allList;
        }
        for (int i = 0; i < list.size(); i++) {
            TAppExamRule er = list.get(i);
            int easyJudge = er.getJudgeCount();
            int easyChoice = er.getChoiceCount();
            int easyMultiple = er.getMultipleChoiceCount();
            int chapterId = er.getChapterId();

            int total2 = easyJudge + easyChoice + easyMultiple;

            QuestionInfoTestDTO questionInfoTestDTO = new QuestionInfoTestDTO();
            questionInfoTestDTO.setChapterId(chapterId);
            questionInfoTestDTO.setDiffDegree(diffDegree);
            questionInfoTestDTO.setQuestionType(1);

            if ("mtc".equals(qt.getGs())) {
                questionInfoTestDTO.setLiceMoto("1");
            } else if ("xc".equals(qt.getGs())) {
                questionInfoTestDTO.setLiceCar("1");
            } else if ("hc".equals(qt.getGs())) {
                questionInfoTestDTO.setLiceTruck("1");
            } else if ("kc".equals(qt.getGs())) {
                questionInfoTestDTO.setLiceBus("1");
            }


            int judgeTotal = questionInfoMapper.selectQuestionInfoCount(questionInfoTestDTO); //章节判断难题总数
            questionInfoTestDTO.setQuestionType(2);
            int choiceTotal = questionInfoMapper.selectQuestionInfoCount(questionInfoTestDTO); //章节选择难题总数
            questionInfoTestDTO.setQuestionType(3);
            int multipleTotal = questionInfoMapper.selectQuestionInfoCount(questionInfoTestDTO); //章节多选难题总数


            int x = i + 1;
            System.out.println("第" + x + "轮easyJudge：" + easyJudge);

            Random random = new Random();
            int p = 0; //判断题
            int d = 0; //单选题
            int m = 0; //多选题
            for (int j = 0; j < er.getDifficultCount(); j++) {
                if (random.nextInt(9) <= 2) {   //判断题
                    if (easyJudge - 1 < 0 || judgeTotal - p <= 0) {
                        j--;
                    } else {
                        p++;
                        easyJudge--;
                    }
                } else if (random.nextInt(9) <= 5) {  //单选题
                    if (easyChoice - 1 < 0 || choiceTotal - d <= 0) {
                        j--;
                    } else {
                        d++;
                        easyChoice--;
                    }
                } else if (random.nextInt(9) <= 8) {    //多选题
                    if (easyMultiple - 1 < 0 || multipleTotal - m <= 0) {
                        j--;
                    } else {
                        m++;
                        easyMultiple--;
                    }
                }
            }


                System.out.println("简单判断：" + easyJudge);
                System.out.println("简单选择：" + easyChoice);
                System.out.println("简单多选：" + easyMultiple);
                System.out.println("难题判断：" + p);
                System.out.println("难题选择：" + d);
                System.out.println("难题多择：" + m);
                System.out.println("总题数：" + total2);

            System.out.println("---------------------------------------------");

            //判断简单
            qt.setChapterId(er.getChapterId()); //章节ID
            qt.setDiffDegree(easyDegree);       //简单难度
            qt.setQuestionType(1);              //判断题
            qt.setNum(easyJudge);               //题数
            List<QuestionInfo> easyJudgeList = this.selectTestQuestionInfoList(qt);
            if (easyJudge != easyJudgeList.size()) {          //简单题不够的情况下，加到难题上
                System.out.println("easyJudge != easyJudgeList.size()");
                int easyJudgeQ = easyJudge - easyJudgeList.size();
                d = d + easyJudgeQ;
                qt.setNum(easyJudgeList.size());
            }
            //单选简单
            qt.setChapterId(er.getChapterId()); //章节ID
            qt.setDiffDegree(easyDegree);       //简单难度
            qt.setQuestionType(2);              //判断题
            qt.setNum(easyChoice);              //题数
            List<QuestionInfo> easyChoiceList = this.selectTestQuestionInfoList(qt);
            if (easyChoice != easyChoiceList.size()) {          //简单题不够的情况下，加到难题上
                System.out.println("easyChoice != easyChoiceList.size()");
                int easyChoiceQ = easyChoice - easyChoiceList.size();
                d = d + easyChoiceQ;
                qt.setNum(easyChoiceList.size());
            }

            //多选简单
            qt.setChapterId(er.getChapterId()); //章节ID
            qt.setDiffDegree(easyDegree);       //简单难度
            qt.setQuestionType(3);              //判断题
            qt.setNum(easyMultiple);              //题数
            List<QuestionInfo> easyMultipleList = this.selectTestQuestionInfoList(qt);
            if (easyMultiple != easyMultipleList.size()) {          //简单题不够的情况下，加到难题上
                System.out.println("easyMultiple != easyMultipleList.size()");
                int easyMultipleQ = easyMultiple - easyMultipleList.size();
                m = m + easyMultipleQ;
                qt.setNum(easyMultipleList.size());
            }
            //判断难题
            qt.setChapterId(er.getChapterId()); //章节ID
            qt.setDiffDegree(diffDegree);       //高难度
            qt.setQuestionType(1);              //判断题
            qt.setNum(p);                       //题数
            List<QuestionInfo> diffJudgeList = this.selectTestQuestionInfoList(qt);
            if (p != diffJudgeList.size()) {
                System.out.println("p!=diffJudgeList.size()");
                break;
            }

            //单选难题
            qt.setChapterId(er.getChapterId()); //章节ID
            qt.setDiffDegree(diffDegree);       //高难度
            qt.setQuestionType(2);              //判断题
            qt.setNum(d);                       //题数
            List<QuestionInfo> diffChoiceList = this.selectTestQuestionInfoList(qt);
            if (d != diffChoiceList.size()) {
                System.out.println("d!=diffChoiceList.size()");
                break;
            }
            //多选简单
            qt.setChapterId(er.getChapterId()); //章节ID
            qt.setDiffDegree(diffDegree);       //高难度
            qt.setQuestionType(3);              //判断题
            qt.setNum(m);                       //题数
            List<QuestionInfo> diffMultipleList = this.selectTestQuestionInfoList(qt);
            if (m != diffMultipleList.size()) {
                System.out.println("m!=diffMultipleList.size()");
                break;
            }

            judgeList.addAll(easyJudgeList);
            judgeList.addAll(diffJudgeList);
            choiceList.addAll(easyChoiceList);
            choiceList.addAll(diffChoiceList);
            multipleList.addAll(easyMultipleList);
            multipleList.addAll(diffMultipleList);
            System.out.println("easyMultipleList = " + easyMultipleList.size());
            System.out.println("diffMultipleList = " + diffMultipleList.size());
        }
        allList.addAll(judgeList);
        allList.addAll(choiceList);
        allList.addAll(multipleList);
        System.out.println("judgeList = "+judgeList.size());
        System.out.println("choiceList = " + choiceList.size());
        System.out.println("multipleList = " + multipleList.size());
        return allList;
    }

    @Override
    public List<QuestionInfo> selectTestK14QuestionInfoList(QuestionInfoTestDTO qt) {

        if ("mtc".equals(qt.getGs())) {
            qt.setLiceMoto("1");
        } else if ("xc".equals(qt.getGs())) {
            qt.setLiceCar("1");
        } else if ("hc".equals(qt.getGs())) {
            qt.setLiceTruck("1");
        } else if ("kc".equals(qt.getGs())) {
            qt.setLiceBus("1");
        }
        //全题库
        List<QuestionInfo> allList = new ArrayList<QuestionInfo>();
        TAppExamRule tAppExamRule = new TAppExamRule();
        tAppExamRule.setKemu(qt.getSubject());
        tAppExamRule.setGs(qt.getGs());
        tAppExamRule.setAreacode(0);

        List<TAppExamRule> list = appExamRuleService.selectTAppExamRuleList(tAppExamRule);
        if (list.size() == 0) {
            return allList;
        }
        int total = 0;
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT * FROM (");

        boolean shouldRetry = false;
        do {
            shouldRetry = false;
            for (int i = 0; i < list.size(); i++) {
                TAppExamRule er = list.get(i);
                int easyJudge = er.getJudgeCount(); //判断
                int easyChoice = er.getChoiceCount(); //选择
                int easyMultiple = er.getMultipleChoiceCount(); //多选

                System.out.println("i="+i);
                System.out.println(qt.getGs()+"+"+qt.getSubject());
                System.out.println("判断题："+easyJudge);
                System.out.println("选择题："+easyChoice);
                System.out.println("多选题："+easyMultiple);

                total = total + easyJudge + easyChoice + easyMultiple;

                int difficult = er.getDifficultCount(); //难题数
                int chapterId = er.getChapterId();

                Random random = new Random();
                int diffJudeg = 0; //判断题
                int diffChoice = 0; //单选题
                int diffMultiple = 0; //多选题

                int randomNum = 0;
                for (int j = 0; j < difficult; j++) {


                    if(qt.getSubject()==1 || (qt.getSubject()==4 && easyMultiple==0)) {
                        randomNum = random.nextInt(2); //随机出现 0和1  0表示判断 1表示单选
                        if (randomNum == 0) {   //判断题
                            diffJudeg++;
                            easyJudge--;
                        } else if (randomNum == 1) {  //单选题
                            diffChoice++;
                            easyChoice--;
                        }
                    } else if(qt.getSubject()==4){
                        randomNum = random.nextInt(3); //随机出现 0、1、2  0表示判断 1表示单选 2多选
                        if (randomNum == 0) {   //判断题
                            diffJudeg++;
                            easyJudge--;
                        } else if (randomNum == 1) {  //单选题
                            diffChoice++;
                            easyChoice--;
                        } else if (randomNum == 2) {    //多选题
                            diffMultiple++;
                            easyMultiple--;
                        }

                    }


                }

                if(qt.getSubject()==1) {
                    if (diffJudeg < 0 || easyJudge < 0 || diffChoice < 0 || easyChoice < 0) {
                        shouldRetry = true;
                        sql.setLength(0);  //清空还原
                        sql.append("SELECT * FROM (");
                        break;
                    }
                }
                // 检查变量值是否小于0
                if(qt.getSubject()==4) {
                    if (diffJudeg < 0 || easyJudge < 0 || diffChoice < 0 || easyChoice < 0 || diffMultiple < 0 || easyMultiple < 0) {
                        shouldRetry = true;
                        sql.setLength(0);  //清空还原
                        sql.append("SELECT * FROM (");
                        break;
                    }
                }


                if (i != 0) {
                    sql.append(" union ");
                }
                //判断题
                sql.append(" (SELECT * FROM question_info WHERE chapter_id = " + chapterId + " AND subject = " + qt.getSubject() + " AND question_type = '1' AND diff_degree in (1,2,3) ORDER BY RAND() LIMIT " + easyJudge + ") ");
                sql.append(" union ");
                sql.append(" (SELECT * FROM question_info WHERE chapter_id = " + chapterId + " AND subject = " + qt.getSubject() + " AND question_type = '1' AND diff_degree in (4,5) ORDER BY RAND() LIMIT " + diffJudeg + ") ");
                sql.append(" union ");
                //选择题
                sql.append(" (SELECT * FROM question_info WHERE chapter_id = " + chapterId + " AND subject = " + qt.getSubject() + " AND question_type = '2' AND diff_degree in (1,2,3) ORDER BY RAND() LIMIT " + easyChoice + ") ");
                sql.append(" union ");
                sql.append(" (SELECT * FROM question_info WHERE chapter_id = " + chapterId + " AND subject = " + qt.getSubject() + " AND question_type = '2' AND diff_degree in (4,5) ORDER BY RAND() LIMIT " + diffChoice + ") ");
                //多选题
                if (qt.getSubject() == 4) {
                    sql.append(" union ");
                    sql.append(" (SELECT * FROM question_info WHERE chapter_id = " + chapterId + " AND subject = " + qt.getSubject() + " AND question_type = '3' AND diff_degree in (1,2,3) ORDER BY RAND() LIMIT " + easyMultiple + ") ");
                    sql.append(" union ");
                    sql.append(" (SELECT * FROM question_info WHERE chapter_id = " + chapterId + " AND subject = " + qt.getSubject() + " AND question_type = '3' AND diff_degree in (4,5) ORDER BY RAND() LIMIT " + diffMultiple + ") ");
                }
            }

        } while (shouldRetry);

        sql.append(" ) as db");
        System.out.println(sql.toString());
        allList = questionInfoMapper.selectTestK14QuestionInfoList(sql.toString());
        if (allList.size() == total) {
            return allList;
        } else {
            new CustomException("模拟考试取题出错，请重试。");
            return null;
        }

    }


    @Override
    public List<QuestionInfo> selectMiQuestionInfoList(QuestionInfoMiDTO questionInfoMiDTO) {
        return questionInfoMapper.selectMiQuestionInfoList(questionInfoMiDTO);
    }




}
