package com.ruoyi.school.paper.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.school.paper.domain.DbCollectList;
import com.ruoyi.school.paper.domain.DbErrorList;
import com.ruoyi.school.paper.domain.DbQuestionBankAnswerTestPaper;
import com.ruoyi.school.paper.domain.bo.DbErrorListBo;
import com.ruoyi.school.paper.domain.request.ErrorTopicRequest;
import com.ruoyi.school.paper.domain.vo.*;
import com.ruoyi.school.paper.mapper.DbCollectListMapper;
import com.ruoyi.school.paper.mapper.DbErrorListMapper;
import com.ruoyi.school.paper.mapper.DbQuestionBankAnswerTestPaperMapper;
import com.ruoyi.school.paper.service.IDbErrorListService;
import com.ruoyi.system.mapper.SysUserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * 错题集Service业务层处理
 *
 * @author zyf
 * @date 2023-07-20
 */
@RequiredArgsConstructor
@Service
public class DbErrorListServiceImpl implements IDbErrorListService {

    private final DbErrorListMapper baseMapper;

    private final DbQuestionBankAnswerTestPaperMapper dbQuestionBankAnswerTestPaperMapper;

    private final DbCollectListMapper dbCollectListMapper;

    private final SysUserMapper sysUserMapper;

    /**
     * 查询错题集
     */
    @Override
    public ErrorTopicListDetailVo queryById(Long id) {
        ErrorTopicListDetailVo errorTopicListDetailVo = baseMapper.getErrorTopicListDetailById(id);
        if (null != errorTopicListDetailVo) {

            List<DbQuestionBankAnswerTestPaper> dbQuestionBankAnswerTestPapers = dbQuestionBankAnswerTestPaperMapper.selectList(Wrappers.<DbQuestionBankAnswerTestPaper>lambdaQuery().eq(DbQuestionBankAnswerTestPaper::getQuestionBankId, errorTopicListDetailVo.getQuestionBankId()));
            errorTopicListDetailVo.setOptions(dbQuestionBankAnswerTestPapers);
            return errorTopicListDetailVo;
        }
        return null;
    }

    /**
     * 查询错题集列表
     */
    @Override
    public TableDataInfo<DbErrorListVo> queryPageList(DbErrorListBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<DbErrorList> lqw = buildQueryWrapper(bo);
        Page<DbErrorListVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询错题集列表
     */
    @Override
    public List<DbErrorListVo> queryList(DbErrorListBo bo) {
        LambdaQueryWrapper<DbErrorList> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<DbErrorList> buildQueryWrapper(DbErrorListBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<DbErrorList> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, DbErrorList::getUserId, bo.getUserId());
        lqw.eq(bo.getPaperId() != null, DbErrorList::getPaperId, bo.getPaperId());
        lqw.eq(bo.getQuestionBankId() != null, DbErrorList::getQuestionBankId, bo.getQuestionBankId());
        return lqw;
    }

    /**
     * 新增错题集
     */
    @Override
    public Boolean insertByBo(DbErrorListBo bo) {
        DbErrorList add = BeanUtil.toBean(bo, DbErrorList.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改错题集
     */
    @Override
    public Boolean updateByBo(DbErrorListBo bo) {
        DbErrorList update = BeanUtil.toBean(bo, DbErrorList.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(DbErrorList entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除错题集
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public TableDataInfo<ErrorTopicListVo> findErrorTopicPage(PageQuery pageQuery, ErrorTopicRequest request) {
        Page<ErrorTopicListVo> result = new Page<ErrorTopicListVo>();
        Long userId = request.getUserId();
        SysUser sysUser = sysUserMapper.selectById(userId);
        if (sysUser != null) {
            String deptList = sysUser.getDeptList();
            if (StringUtils.isNotEmpty(deptList)) {
                List<SysUser> sysUsers = new ArrayList<>();
                if (deptList.contains(",")) {
                    String[] split = deptList.split(",");
                    sysUsers = sysUserMapper.selectList(Wrappers.<SysUser>lambdaQuery()
                        .eq(SysUser::getSex, "0")
                        .in(SysUser::getDeptList, split));
                } else {
                    sysUsers = sysUserMapper.selectList(Wrappers.<SysUser>lambdaQuery()
                        .eq(SysUser::getSex, "0")
                        .eq(SysUser::getDeptList, deptList));
                }
                if (!sysUsers.isEmpty()) {
                    List<Long> userIds = sysUsers.stream()
                        .map(SysUser::getUserId)
                        .collect(Collectors.toList());
                    request.setUserIds(userIds);
                    result = baseMapper.findErrorTopicPage(pageQuery.build(), request);
                }
            }
        }
        return TableDataInfo.build(result);
    }

    @Override
    public TableDataInfo<MyErrorTopicListVo> findMyErrorTopicListVoPage(PageQuery pageQuery, ErrorTopicRequest request) {
        Page<MyErrorTopicListVo> myErrorTopicListVoPage = baseMapper.findMyErrorTopicListVoPage(pageQuery.build(), request);
        List<MyErrorTopicListVo> records = myErrorTopicListVoPage.getRecords();
        if (CollectionUtils.isNotEmpty(records)) {
            //获取题目集ID
            List<Long> questionBankIds = records.stream()
                .map(MyErrorTopicListVo::getQuestionBankId)
                .collect(Collectors.toList());

            //查询所有选项并根据题目id分组
            Map<Long, List<DbQuestionBankAnswerTestPaper>> optionsMap = dbQuestionBankAnswerTestPaperMapper
                .selectList(Wrappers.<DbQuestionBankAnswerTestPaper>lambdaQuery()
                    .in(DbQuestionBankAnswerTestPaper::getQuestionBankId, questionBankIds))
                .stream()
                .collect(Collectors.groupingBy(DbQuestionBankAnswerTestPaper::getQuestionBankId));
            //选项set至每道题目中
            records.parallelStream().forEach(myErrorTopicListVo -> {
                //判读是否收藏
                Optional.ofNullable(dbCollectListMapper.selectOne(Wrappers.<DbCollectList>lambdaQuery().eq(DbCollectList::getUserId, request.getUserId())
                        .eq(DbCollectList::getQuestionBankId, myErrorTopicListVo.getQuestionBankId())))
                    .ifPresent(res -> {
                        myErrorTopicListVo.setCollectFlag(Boolean.TRUE);
                    });
                List<DbQuestionBankAnswerTestPaper> options = optionsMap.get(myErrorTopicListVo.getQuestionBankId());
                myErrorTopicListVo.setOptions(options);
            });
        }

        return TableDataInfo.build(myErrorTopicListVoPage);
    }
}
