package com.testor.module.train.myManagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.testor.module.train.exam.model.domain.TTrainExamChoice;
import com.testor.module.train.exam.model.domain.TTrainExamJudgment;
import com.testor.module.train.exam.model.domain.TTrainTestQuestions;
import com.testor.module.train.exam.service.TTrainExamChoiceService;
import com.testor.module.train.exam.service.TTrainExamJudgmentService;
import com.testor.module.train.exam.service.TTrainTestQuestionsService;
import com.testor.module.train.myManagement.model.domain.TTrainMyManagement;
import com.testor.module.train.myManagement.model.domain.TTrainTestQuestionsExercise;
import com.testor.module.train.myManagement.service.TTrainMyManagementService;
import com.testor.module.train.myManagement.service.TTrainTestQuestionsExerciseService;
import com.testor.module.train.paper.model.dto.Options;
import com.testor.module.train.paper.model.dto.TestQuestionsContent;
import com.testor.module.train.project.model.dto.Exercise;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.exception.BusinessException;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Lazy
public class AsyncTestQuestions {
    @Autowired
    private TTrainTestQuestionsService tTrainTestQuestionsService;
    @Autowired
    private TTrainExamChoiceService tTrainExamChoiceService;
    @Autowired
    private TTrainExamJudgmentService tTrainExamJudgmentService;
    @Autowired
    private TTrainTestQuestionsExerciseService tTrainTestQuestionsExerciseService;
    @Autowired
    private TTrainMyManagementService tTrainMyManagementService;

    @Async
    public void getTestQuestions(Exercise exercise, String userId) throws Exception {
        if (StringHelper.isNotEmpty(exercise.getId())) {
            QueryWrapper<TTrainTestQuestions> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq(TTrainTestQuestions.QUESTION_BANK_ID, exercise.getId());
            queryWrapper1.ne(TTrainTestQuestions.STATUS, BizConstants.STATUS_DELETE);
            // 通过条件获取题库所有试题
            List<TTrainTestQuestions> records = tTrainTestQuestionsService.list(queryWrapper1);
            List<TestQuestionsContent> testQuestionsContents = new ArrayList<>();
            int num = 0;
            for (TTrainTestQuestions tTrainTestQuestions : records) {
                String testQuestionsType = tTrainTestQuestions.getTestQuestionsType();
                //试题id
                String questionsId = tTrainTestQuestions.getId();
                num++;
                if ("SELECT".equals(testQuestionsType) || "MORE_SELECT".equals(testQuestionsType)) {
                    // 每一个题目
                    TestQuestionsContent testQuestionsContent = BeanHelper.beanToBean(tTrainTestQuestions, TestQuestionsContent.class);
                    QueryWrapper<TTrainExamChoice> wrapper = new QueryWrapper<>();
                    wrapper.eq(TTrainExamChoice.TEST_QUESTIONS_ID, questionsId);
                    // 当前题目包含的所有选项
                    List<TTrainExamChoice> list1 = tTrainExamChoiceService.list(wrapper);
                    // 按照选项排序
                    list1 = list1.stream().sorted(Comparator.comparing(TTrainExamChoice::getOptions))
                            .collect(Collectors.toList());
                    List<Options> optionsList = new ArrayList<>();
                    for (TTrainExamChoice tTrainExamChoice : list1) {
                        Options options = BeanHelper.beanToBean(tTrainExamChoice, Options.class);
                        String optionsTest = options.getOptions() + ": " + options.getOptionText();
                        options.setOptionText(optionsTest);
                        optionsList.add(options);
                    }
                    String testQuestionsContent1 = num + "." + testQuestionsContent.getTestQuestionsContent();
                    testQuestionsContent.setTestQuestionsContent(testQuestionsContent1);
                    testQuestionsContent.setOptions(optionsList);
                    String score = "";
                    testQuestionsContent.setScore(score);
                    testQuestionsContent.setDictKey(testQuestionsType);
                    testQuestionsContents.add(testQuestionsContent);
                }
                if ("JUDGE".equals(testQuestionsType)) {
                    // 每一个题目
                    TestQuestionsContent testQuestionsContent = BeanHelper.beanToBean(tTrainTestQuestions, TestQuestionsContent.class);
                    QueryWrapper<TTrainExamJudgment> wrapper = new QueryWrapper<>();
                    wrapper.eq(TTrainExamJudgment.TEST_QUESTIONS_ID, questionsId);
                    // 当前题目包含的所有选项
                    List<TTrainExamJudgment> list1 = tTrainExamJudgmentService.list(wrapper);
                    // 按照选项排序
                    list1 = list1.stream().sorted(Comparator.comparing(TTrainExamJudgment::getOptions))
                            .collect(Collectors.toList());
                    List<Options> optionsList = new ArrayList<>();
                    for (TTrainExamJudgment tTrainExamChoice : list1) {
                        Options options = BeanHelper.beanToBean(tTrainExamChoice, Options.class);
                        String optionsTest = options.getOptions() + ": " + options.getOptionText();
                        options.setOptionText(optionsTest);
                        optionsList.add(options);
                    }
                    String testQuestionsContent1 = num + "." + testQuestionsContent.getTestQuestionsContent();
                    testQuestionsContent.setTestQuestionsContent(testQuestionsContent1);
                    testQuestionsContent.setOptions(optionsList);
                    String score = "";
                    testQuestionsContent.setScore(score);
                    testQuestionsContent.setDictKey(testQuestionsType);
                    testQuestionsContents.add(testQuestionsContent);
                }
            }
            //得到已经做过的题目
            List<TTrainTestQuestionsExercise> list = tTrainTestQuestionsExerciseService.list(new QueryWrapper<TTrainTestQuestionsExercise>()
                    .eq(TTrainTestQuestionsExercise.PERSON_ID, userId)
            );
            for (TestQuestionsContent test : testQuestionsContents) {
                for (TTrainTestQuestionsExercise tTrain : list) {
                    if (test.getId().equals(tTrain.getTestQuestionsId())) {
                        test.setIsSelect("1");
                        test.setIsCorrect(tTrain.getIsCorrect());
                        String[] split = tTrain.getOptionsId().split(",");
                        for (Options option : test.getOptions()) {
                            for (String s : split) {
                                if (option.getId().equals(s)) {
                                    option.setIsSelect("1");
                                }
                            }
                        }
                    }
                }
            }
            // 试题总数
            int sum = testQuestionsContents.size();
            // 练习数量
            int exerciseNum = 0;
            // 错题数
            int errors = 0;
            for (TestQuestionsContent testQuestionsContent : testQuestionsContents) {
                if ("1".equals(testQuestionsContent.getIsSelect())) {
                    exerciseNum += 1;
                }
                if ("0".equals(testQuestionsContent.getIsCorrect())) {
                    errors += 1;
                }
            }
            // 题库id
            String bankId = exercise.getId();
            // 获取练习计划的主键id
            String taskId = getTastId(bankId, userId);
            // 练习率
            String ratio = getRatio(exerciseNum, sum);
            tTrainMyManagementService.update(new UpdateWrapper<TTrainMyManagement>()
                    .eq(TTrainMyManagement.ID, taskId)
                    .set(TTrainMyManagement.TEST_QUESTIONS_NUM, sum)
                    .set(TTrainMyManagement.EXERCISE_NUM, exerciseNum)
                    .set(TTrainMyManagement.EXERCISE_RATE, ratio)
                    .set(TTrainMyManagement.ERRORS_NUM, errors)
            );
        } else {
            throw new BusinessException("请求参数不正确");
        }
    }

    /**
     * 计算百分比
     * @param number1 练习数
     * @param number2 总数
     * @return
     */
    public String getRatio(Integer number1, Integer number2) {
        DecimalFormat df = new DecimalFormat("0.0");
        if (number2 != 0) {
            return df.format((float) (number1 / (double) number2) * 100) + "%";
        } else {
            return "0%";
        }
    }

    /**
     * 获取练习计划的主键id
     *
     * @param bankId 题库id
     * @param userId 用户id
     * @return
     */
    private String getTastId(String bankId, String userId) {
        TTrainMyManagement one = tTrainMyManagementService.getOne(new QueryWrapper<TTrainMyManagement>()
                .eq(TTrainMyManagement.TASK_ID, bankId)
                .eq(TTrainMyManagement.PERSON_ID, userId)
        );
        return one.getId();
    }
}
