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.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
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.DbErrorListMapper;
import com.ruoyi.school.paper.mapper.DbQuestionBankAnswerTestPaperMapper;
import com.ruoyi.school.paper.service.IDbErrorListService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
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;

    /**
     * 查询错题集
     */
    @Override
    public ErrorTopicListDetailVo queryById(Long id) {
        List<ErrorTopicListDetailVo> errorTopicListDetailVoList = baseMapper.findErrorTopicListDetailById(id);
        if (CollectionUtils.isNotEmpty(errorTopicListDetailVoList)) {
            List<OptionVo> list = errorTopicListDetailVoList.stream()
                .map(errorTopicListDetailVo -> {
                    OptionVo optionVo = new OptionVo();
                    optionVo.setOptionTag(errorTopicListDetailVo.getOptionTag());
                    optionVo.setOptionContent(errorTopicListDetailVo.getOptionContent());
                    return optionVo;
                })
                .collect(Collectors.toList());
            ErrorTopicListDetailVo firstErrorTopicListDetailVo = errorTopicListDetailVoList.get(0);
            ErrorTopicListDetailVo errorTopicListDetailVo = new ErrorTopicListDetailVo();
            errorTopicListDetailVo.setTopic(firstErrorTopicListDetailVo.getTopic());
            errorTopicListDetailVo.setIntensity(firstErrorTopicListDetailVo.getIntensity());
            errorTopicListDetailVo.setSpecies(firstErrorTopicListDetailVo.getSpecies());
            errorTopicListDetailVo.setTypeName(firstErrorTopicListDetailVo.getTypeName());
            errorTopicListDetailVo.setRightAnswers(firstErrorTopicListDetailVo.getRightAnswers());
            errorTopicListDetailVo.setOptions(list);

            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());
        lqw.eq(bo.getStatus() != null, DbErrorList::getStatus, bo.getStatus());
        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 = 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)) {
            records.forEach(myErrorTopicListVo -> {
                //根据每到题目查询对应的选项
                //拿到对应选项填充至每道错题当中
                Optional.ofNullable(dbQuestionBankAnswerTestPaperMapper.selectList(Wrappers.<DbQuestionBankAnswerTestPaper>lambdaQuery().eq(DbQuestionBankAnswerTestPaper::getQuestionBankId, myErrorTopicListVo.getQuestionBankId())))
                    .ifPresent(myErrorTopicListVo::setOptions);
            });
        }
        return TableDataInfo.build(myErrorTopicListVoPage);
    }
}
