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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.module.train.course.model.domain.TTrainCourse;
import com.testor.module.train.exam.dao.TTrainQuestionBankDao;
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.TTrainQuestionBank;
import com.testor.module.train.exam.model.domain.TTrainTestQuestions;
import com.testor.module.train.exam.model.dto.TTrainQuestionBankDelParam;
import com.testor.module.train.exam.service.TTrainExamChoiceService;
import com.testor.module.train.exam.service.TTrainExamJudgmentService;
import com.testor.module.train.exam.service.TTrainQuestionBankService;
import com.testor.module.train.exam.service.TTrainTestQuestionsService;
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.testor.module.train.project.model.dto.MyManagement;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.biz.models.BaseResponseList;
import com.tongtech.tfw.backend.common.biz.models.BizGeneralResponse;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.exception.BusinessException;
import com.tongtech.tfw.backend.common.models.supers.SuperServiceImpl;
import com.tongtech.tfw.backend.common.models.sys.UserInfo;
import com.tongtech.tfw.backend.core.helper.IdHelper;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.TypeHelper;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 题库——安全培训教育Service业务层处理
 *
 * @author testor-framework
 * @date 2022-07-13 15:19:22
 */
@Service
public class TTrainQuestionBankServiceImpl extends SuperServiceImpl<TTrainQuestionBankDao, TTrainQuestionBank> implements TTrainQuestionBankService {
    @Autowired(required = false)
    private TTrainQuestionBankDao tTrainQuestionBankDao;
    @Autowired
    private SysOrgService sysOrgService;

    @Autowired
    private TTrainTestQuestionsService tTrainTestQuestionsService;

    @Autowired
    private TTrainMyManagementService tTrainMyManagementService;

    @Autowired
    private TTrainTestQuestionsExerciseService tTrainTestQuestionsExerciseService;
    @Autowired
    private TTrainExamJudgmentService tTrainExamJudgmentService;
    @Autowired
    private TTrainExamChoiceService tTrainExamChoiceService;

    @Override
    public BaseResponse<TTrainQuestionBank> addEntity(TTrainQuestionBank addRequest) throws Exception {
        if (ObjectHelper.isEmpty(addRequest)) {
            throw new BusinessException("请求参数有误");
        }
        UserInfo loginUser = ContextUtils.getLoginUser();
        SysOrg sysOrg = sysOrgService.getById(loginUser.getOrgId());
        if (Objects.isNull(sysOrg)) {
            throw new BusinessException("当前登录人部门信息不存在，请联系管理员！");
        }
        BaseResponse<TTrainQuestionBank> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(addRequest)) {
            String id = IdHelper.getId32bit();
            TTrainQuestionBank data = BeanHelper.beanToBean(addRequest, TTrainQuestionBank.class);
            List<TTrainQuestionBank> list = this.list(new QueryWrapper<TTrainQuestionBank>()
                    .eq(TTrainQuestionBank.QUESTION_BANK_NAME, data.getQuestionBankName())
                    .eq(TTrainQuestionBank.ORG_ID, sysOrg.getOrgId())
                    .ne(TTrainQuestionBank.STATUS, BizConstants.STATUS_DELETE)
            );
            if (ObjectHelper.isNotEmpty(list)) {
                throw new BusinessException("题库已存在");
            }
            data.setQuestionBankSource(sysOrg.getOrgName());
            data.setOrgId(sysOrg.getOrgId());
            data.setProcessStatus("3");
            data.setId(id);
            boolean result = this.save(data);
            if (result) {
                TTrainQuestionBank newEntity = new TTrainQuestionBank();
                newEntity.setId(id);
                baseResponse.setData(newEntity);
            }
        }
        return baseResponse;
    }

    @Override
    public BaseResponse<TTrainQuestionBank> getByIds(String id) throws Exception {
        BaseResponse<TTrainQuestionBank> baseResponse = new BaseResponse<>();
        if (StringHelper.isNotEmpty(id)) {
            TTrainQuestionBank data = this.getById(id);
            baseResponse.setData(data);
        } else {
            throw new BusinessException("请求参数为不正确");
        }
        return baseResponse;
    }

    @Override
    public BaseResponse<BizGeneralResponse> updateEntity(TTrainQuestionBank updateRequest) throws Exception {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(updateRequest) && StringHelper.isNotEmpty(updateRequest.getId())) {
            TTrainQuestionBank data = BeanHelper.beanToBean(updateRequest, TTrainQuestionBank.class);
            //ToDo  校验题库名称
            TTrainQuestionBank byId = this.getById(data.getId());
            if (!byId.getQuestionBankName().equals(data.getQuestionBankName()) && this.count(new QueryWrapper<TTrainQuestionBank>()
                    .eq(TTrainQuestionBank.QUESTION_BANK_NAME, data.getQuestionBankName())
                    .eq(TTrainQuestionBank.ORG_ID, byId.getOrgId())
                    .ne(TTrainQuestionBank.STATUS, BizConstants.STATUS_DELETE)
            )>0) {
                throw new BusinessException("已存在相同名称题库");
            }

            boolean result = this.updateById(data);
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        } else {
            throw new BusinessException("请求参数为不正确");
        }
        return baseResponse;
    }

    @Override
    public BaseResponse<BizGeneralResponse> deleteEntity(TTrainQuestionBankDelParam deleteRequest) throws Exception {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(deleteRequest) && StringHelper.isNotEmpty(deleteRequest.getId())) {
            TTrainQuestionBank data = new TTrainQuestionBank();
            data.setId(deleteRequest.getId());
            data.setStatus(BizConstants.STATUS_DELETE);
            boolean result = this.updateById(data);
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        } else {
            throw new BusinessException("请求参数为不正确");
        }
        return baseResponse;
    }

    @Override
    public void joinLearnBank(TTrainQuestionBank addRequest) throws Exception{
        UserInfo loginUser = ContextUtils.getLoginUser();
        SysOrg sysOrg = sysOrgService.getById(loginUser.getOrgId());
        // 题库id
        String id = addRequest.getId();
        if (StringHelper.isNotEmpty(id)) {
            TTrainQuestionBank trainQuestionBank = this.getOne(new QueryWrapper<TTrainQuestionBank>()
                    .eq(TTrainCourse.ID, id)
                    .ne(TTrainCourse.STATUS, BizConstants.STATUS_DELETE)
            );
            // 获取题库里面的所有试题
            int count = tTrainTestQuestionsService.count(new QueryWrapper<TTrainTestQuestions>()
                    .eq(TTrainTestQuestions.QUESTION_BANK_ID, id)
                    .ne(TTrainTestQuestions.STATUS, BizConstants.STATUS_DELETE)
            );
            MyManagement myManagement = new MyManagement();
            myManagement.setOrgId(loginUser.getOrgId());
            myManagement.setTestQuestionsNum(Integer.toString(count));
            myManagement.setPersonId(loginUser.getUserId());
            myManagement.setTaskName(trainQuestionBank.getQuestionBankName());
            myManagement.setCurrentStatus("0");
            myManagement.setTabStatus("3");
            myManagement.setIsAddExam("0");
            myManagement.setTaskId(id);
            tTrainMyManagementService.addCourse(myManagement);
        }
    }

    @Override
    public BaseResponse<BaseResponseList<TestQuestionsContent>> getTestQuestions(Exercise exercise) throws Exception {
        BaseResponse<BaseResponseList<TestQuestionsContent>> baseResponse1 = new BaseResponse<>();
        if (StringHelper.isNotEmpty(exercise.getId())) {
            Long pages =
                    StringHelper.isEmpty(exercise.getPage()) ? BizConstants.PAGE : Long.valueOf(exercise.getPage());
            Long limits =
                    StringHelper.isEmpty(exercise.getLimit()) ? BizConstants.LIMIT : Long.valueOf(exercise.getLimit());
            Page<TTrainTestQuestions> resultPage = new Page<>(pages, limits);
            QueryWrapper<TTrainTestQuestions> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq(TTrainTestQuestions.QUESTION_BANK_ID, exercise.getId());
            queryWrapper1.ne(TTrainTestQuestions.STATUS, BizConstants.STATUS_DELETE);
            Page<TTrainTestQuestions> page1 = tTrainTestQuestionsService.page(resultPage, queryWrapper1);
            BaseResponseList<TestQuestionsContent> baseResponseList = new BaseResponseList<>();
            // 通过条件获取题库所有试题
            List<TTrainTestQuestions> records = page1.getRecords();
            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);
                }
            }
//            UserInfo loginUser = ContextUtils.getLoginUser();
            //得到已经做过的题目
//            List<TTrainTestQuestionsExercise> list = tTrainTestQuestionsExerciseService.list(new QueryWrapper<TTrainTestQuestionsExercise>()
//                    .eq(TTrainTestQuestionsExercise.PERSON_ID, loginUser.getUserId())
//            );
//            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");
//                                }
//                            }
//                        }
//                    }
//                }
//            }
            baseResponseList.setData(testQuestionsContents);
            baseResponseList.setTotal(page1.getTotal());
            baseResponse1.setData(baseResponseList);
        } else {
            throw new BusinessException("请求参数不正确");
        }
        return baseResponse1;
    }
}
