package com.yanzhu.manage.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSON;
import com.yanzhu.common.core.enums.CraftType;
import com.yanzhu.common.core.enums.IsDelEnums;
import com.yanzhu.common.core.enums.UseStateEnums;
import com.yanzhu.common.core.exception.ServiceException;
import com.yanzhu.common.core.text.Convert;
import com.yanzhu.common.core.utils.DateUtils;
import com.yanzhu.common.core.utils.StringUtils;
import com.yanzhu.common.security.utils.SecurityUtils;
import com.yanzhu.manage.domain.*;
import com.yanzhu.manage.mapper.*;
import com.yanzhu.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yanzhu.manage.service.IBusExamUserService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户试卷Service业务层处理
 * 
 * @author JiangYuQi
 * @date 2024-08-25
 */
@Service
public class BusExamUserServiceImpl implements IBusExamUserService 
{
    @Autowired
    private BusExamInfoMapper busExamInfoMapper;

    @Autowired
    private BusExamUserMapper busExamUserMapper;

    @Autowired
    private BusExamQuestionMapper busExamQuestionMapper;

    @Autowired
    private ProProjectInfoSubdeptsUsersMapper proProjectInfoSubdeptsUsersMapper;

    /**
     * 查询用户试卷
     * 
     * @param id 用户试卷主键
     * @return 用户试卷
     */
    @Override
    public BusExamUser selectBusExamUserById(Long id)
    {
        return busExamUserMapper.selectBusExamUserById(id);
    }

    /**
     * 查询用户试卷列表
     * 
     * @param busExamUser 用户试卷
     * @return 用户试卷
     */
    @Override
    public List<BusExamUser> selectBusExamUserList(BusExamUser busExamUser)
    {
        busExamUser.setActiveComId(SecurityUtils.getLoginUser().getProjectDeptId());
        busExamUser.setActiveProjectId(SecurityUtils.getLoginUser().getProjectId());
        return busExamUserMapper.selectBusExamUserList(busExamUser);
    }

    /**
     * 新增用户试卷
     *
     * @return 结果
     */
    @Override
    @Transactional
    public BusExamUser insertBusExamUser()
    {
        BusExamUser busExamUser = new BusExamUser();
        SysUser cache = SecurityUtils.getLoginUser().getSysUser();
        // 查询用户详细
        ProProjectInfoSubdeptsUsers userQuery = new ProProjectInfoSubdeptsUsers();
        userQuery.setUserId(cache.getUserId());
        userQuery.setComId(cache.getActiveComId());
        userQuery.setProjectId(cache.getActiveProjectId());
        userQuery.setUseStatus(UseStateEnums.IN.getCode());
        userQuery.setIsDel(IsDelEnums.NO.getCode());
        List<ProProjectInfoSubdeptsUsers> userList = proProjectInfoSubdeptsUsersMapper.selectProProjectInfoSubdeptsUsersList(userQuery);

        if(StringUtils.isEmpty(userList)){
            throw new ServiceException("用户信息异常...不能抽取试题...");
        }
        ProProjectInfoSubdeptsUsers userEntity = userList.get(0);

        // 查询试卷列表
        BusExamInfo query = new BusExamInfo();
        query.setComId(cache.getActiveComId());
        query.setProjectId(cache.getActiveProjectId());
        query.setCraftType(userEntity.getCraftType());
        // 管理人员获取所有管理类试卷
        if(!Objects.equals(CraftType.GLRY.getCode(),query.getCraftType())){
            query.setCraftPost(userEntity.getCraftPost());
        }
        query.setIsDel(IsDelEnums.NO.getCode());
        List<BusExamInfo> examInfoList = busExamInfoMapper.selectBusExamInfoList(query);
        if(StringUtils.isNotEmpty(examInfoList)){
            // 优先从项目试卷中获取试卷、未找到项目试卷则从所有试卷中筛选
            List<BusExamInfo> _projectExamInfolist = examInfoList.stream().filter(examInfo -> examInfo.getProjectId() != null)
                    .collect(Collectors.toList());
            Random random = new Random();
            BusExamInfo findExamInfo;
            if(StringUtils.isNotEmpty(_projectExamInfolist)){
                int randomIntBound = random.nextInt(_projectExamInfolist.size());
                findExamInfo = _projectExamInfolist.get(randomIntBound);
            }else{
                int randomIntBound = random.nextInt(examInfoList.size());
                findExamInfo = examInfoList.get(randomIntBound);
            }

            // 获取试卷试题
            List<BusExamQuestion> questions = extractExamQuestion(findExamInfo,userEntity.getCraftPost());
            // 试题重新排序
            Collections.shuffle(questions);

            busExamUser.setComId(userEntity.getComId());
            busExamUser.setProjectId(userEntity.getProjectId());
            busExamUser.setUserId(cache.getUserId());
            busExamUser.setExamTitle(findExamInfo.getExamTitle());
            busExamUser.setExamType(findExamInfo.getExamType());
            busExamUser.setCraftType(userEntity.getCraftType());
            busExamUser.setCraftPost(userEntity.getCraftPost());
            busExamUser.setSingleNum(findExamInfo.getSingleNum());
            busExamUser.setMultipleNum(findExamInfo.getMultipleNum());
            busExamUser.setEstimateNum(findExamInfo.getEstimateNum());
            busExamUser.setCreateBy(cache.getUserName());
            busExamUser.setCreateTime(DateUtils.getNowDate());
            busExamUserMapper.insertBusExamUser(busExamUser);

            List<BusExamUserResult> busExamUserResultList = new ArrayList<>();
            for(BusExamQuestion examQuestion:questions){
                BusExamQuestion question = busExamQuestionMapper.selectBusExamQuestionById(examQuestion.getId());
                BusExamUserResult entity = new BusExamUserResult();
                entity.setExamUserId(busExamUser.getId());
                entity.setQuestionId(examQuestion.getId());
                entity.setQuestionTitle(examQuestion.getQuestionDesc());
                entity.setQuestionType(examQuestion.getQuestionType());
                entity.setQuestionOption(JSON.toJSONString(question.getBusExamQuestionResultList()));
                entity.setAnswer(question.getQuestionAnswer());
                busExamUserResultList.add(entity);
            }
            busExamUser.setBusExamUserResultList(busExamUserResultList);
            busExamUserMapper.batchBusExamUserResult(busExamUserResultList);

            // 修改试卷使用次数
            busExamInfoMapper.updateExamUseNumber(findExamInfo.getId());
        }else{
            throw new ServiceException("当前项目未配置试卷信息，请联系管理员配置...");
        }
        return busExamUser;
    }

    /**
     * 根据试卷抽取考题
     * @param findExamInfo 试卷
     * @param craftPost 试题范围
     * @return
     */
    private List<BusExamQuestion> extractExamQuestion(BusExamInfo findExamInfo,String craftPost){
        BusExamQuestion questionQuery = new BusExamQuestion();
        questionQuery.setActiveComId(findExamInfo.getComId());
        questionQuery.setActiveProjectId(findExamInfo.getProjectId());
        questionQuery.setCraftPost(craftPost);
        questionQuery.setIsDel(IsDelEnums.NO.getCode());
        List<BusExamQuestion> list = new ArrayList<>();
        List<BusExamQuestion> allQuestionList = busExamQuestionMapper.selectBusExamQuestionList(questionQuery);
        if(StringUtils.isNotEmpty(allQuestionList)){
            /**
             * 根据试卷配置进行抽题
             * oxtQuestionList 单选题列表
             * dxtQuestionList 多选题列表
             * pdtQuestionList 判断题列表
             */
            List<BusExamQuestion> oxtQuestionList = allQuestionList.stream().filter(question -> question.getQuestionType() == 1L).collect(Collectors.toList());
            List<BusExamQuestion> dxtQuestionList = allQuestionList.stream().filter(question -> question.getQuestionType() == 2L).collect(Collectors.toList());
            List<BusExamQuestion> pdtQuestionList = allQuestionList.stream().filter(question -> question.getQuestionType() == 3L).collect(Collectors.toList());
            int singleNum = Convert.toInt(findExamInfo.getSingleNum(),0);
            if(singleNum>0){
                if(Objects.nonNull(oxtQuestionList) && oxtQuestionList.size()>singleNum){
                    list.addAll(getRandomQuestions(oxtQuestionList,singleNum));
                }else{
                    if(Objects.nonNull(oxtQuestionList)){
                        list.addAll(oxtQuestionList);
                    }
                }
            }
            int multipleNum = Convert.toInt(findExamInfo.getMultipleNum(),0);
            if(multipleNum>0){
                if(Objects.nonNull(dxtQuestionList) && dxtQuestionList.size()>multipleNum){
                    list.addAll(getRandomQuestions(dxtQuestionList,multipleNum));
                }else{
                    if(Objects.nonNull(dxtQuestionList)){
                        list.addAll(dxtQuestionList);
                    }
                }
            }
            int estimateNum = Convert.toInt(findExamInfo.getEstimateNum(),0);
            if(singleNum>0){
                if(Objects.nonNull(pdtQuestionList) && pdtQuestionList.size()>estimateNum){
                    list.addAll(getRandomQuestions(pdtQuestionList,estimateNum));
                }else{
                    if(Objects.nonNull(pdtQuestionList)){
                        list.addAll(pdtQuestionList);
                    }
                }
            }
        }else{
            throw new ServiceException("请联系管理员配置试题...");
        }
        return list;
    }

    /**
     * 随机试题
     * @param questionList
     * @param numberOfQuestions
     * @return
     */
    private static List<BusExamQuestion> getRandomQuestions(List<BusExamQuestion> questionList, int numberOfQuestions) {
        // 打乱列表
        Collections.shuffle(questionList);
        // 获取前 numberOfQuestions 个元素
        return questionList.stream()
                .limit(numberOfQuestions)
                .collect(Collectors.toList());
    }

    /**
     * 修改用户试卷
     * 
     * @param busExamUser 用户试卷
     * @return 结果
     */
    @Override
    public int updateBusExamUser(BusExamUser busExamUser)
    {
        busExamUser.setUpdateTime(DateUtils.getNowDate());
        return busExamUserMapper.updateBusExamUser(busExamUser);
    }

    /**
     * 批量删除用户试卷
     * 
     * @param ids 需要删除的用户试卷主键
     * @return 结果
     */
    @Override
    public int deleteBusExamUserByIds(Long[] ids)
    {
        return busExamUserMapper.deleteBusExamUserByIds(ids);
    }

    /**
     * 删除用户试卷信息
     * 
     * @param id 用户试卷主键
     * @return 结果
     */
    @Override
    public int deleteBusExamUserById(Long id)
    {
        return busExamUserMapper.deleteBusExamUserById(id);
    }

    /**
     * 新增用户试卷结果信息
     *
     * @param busExamUser 用户试卷对象
     */
    public void insertBusExamUserResult(BusExamUser busExamUser)
    {
        List<BusExamUserResult> busExamUserResultList = busExamUser.getBusExamUserResultList();
        Long id = busExamUser.getId();
        if (StringUtils.isNotNull(busExamUserResultList))
        {
            List<BusExamUserResult> list = new ArrayList<BusExamUserResult>();
            for (BusExamUserResult busExamUserResult : busExamUserResultList)
            {
                busExamUserResult.setExamUserId(id);
                list.add(busExamUserResult);
            }
            if (list.size() > 0)
            {
                busExamUserMapper.batchBusExamUserResult(list);
            }
        }
    }
}
