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

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.school.paper.domain.DbErrorList;
import com.ruoyi.school.paper.domain.DbTestPaperRecord;
import com.ruoyi.school.paper.domain.bo.DbTestPaperBo;
import com.ruoyi.school.paper.domain.bo.DbTestPaperRecordBo;
import com.ruoyi.school.paper.domain.vo.DbTestPaperRecordDetailVo;
import com.ruoyi.school.paper.domain.vo.DbTestPaperRecordVo;
import com.ruoyi.school.paper.domain.vo.DbTestPaperVo;
import com.ruoyi.school.paper.mapper.DbErrorListMapper;
import com.ruoyi.school.paper.mapper.DbTestPaperRecordDetailMapper;
import com.ruoyi.school.paper.mapper.DbTestPaperRecordMapper;
import com.ruoyi.school.paper.service.IDbTestPaperRecordService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 答题记录Service业务层处理
 *
 * @author zyf
 * @date 2023-07-20
 */
@RequiredArgsConstructor
@Service
public class DbTestPaperRecordServiceImpl implements IDbTestPaperRecordService {

    private final DbTestPaperRecordMapper baseMapper;
    private final DbTestPaperRecordDetailMapper recordDetailMapper;
    private final DbErrorListMapper errorListMapper;

    /**
     * 查询答题记录
     */
    @Override
    public DbTestPaperRecordVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询答题记录列表
     */
    @Override
    public TableDataInfo<DbTestPaperRecordVo> queryPageList(DbTestPaperRecordBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<DbTestPaperRecord> lqw = buildQueryWrapper(bo);
        Page<DbTestPaperRecordVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询答题记录列表
     */
    @Override
    public List<DbTestPaperRecordVo> queryList(DbTestPaperRecordBo bo) {
        LambdaQueryWrapper<DbTestPaperRecord> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<DbTestPaperRecord> buildQueryWrapper(DbTestPaperRecordBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<DbTestPaperRecord> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, DbTestPaperRecord::getUserId, bo.getUserId());
        lqw.eq(bo.getTestPaperId() != null, DbTestPaperRecord::getTestPaperId, bo.getTestPaperId());
        lqw.eq(bo.getStatus() != null, DbTestPaperRecord::getStatus, bo.getStatus());
        lqw.eq(bo.getTotalPoints() != null, DbTestPaperRecord::getTotalPoints, bo.getTotalPoints());
        return lqw;
    }

    /**
     * 新增答题记录
     */
    @Override
    public Boolean insertByBo(DbTestPaperRecordBo bo) {
        DbTestPaperRecord add = BeanUtil.toBean(bo, DbTestPaperRecord.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改答题记录
     */
    @Override
    public Boolean updateByBo(DbTestPaperRecordBo bo) {
        DbTestPaperRecord update = BeanUtil.toBean(bo, DbTestPaperRecord.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

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

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

    /**
     * 【小程序】查询答题记录列表
     *
     * @param bo
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<DbTestPaperRecordVo> testPaperlist(DbTestPaperRecordBo bo, PageQuery pageQuery) {
        Page<DbTestPaperRecordVo> result = baseMapper.getTestPaperlist(pageQuery.build(), bo);
        return TableDataInfo.build(result);
    }

    /**
     * 查询某条考试记录
     *
     * @param wrapper 擦汗寻条件
     * @return 结果
     */
    @Override
    public DbTestPaperRecord getOne(Wrapper<DbTestPaperRecord> wrapper) {
        return baseMapper.selectOne(wrapper);
    }

    /**
     * 审批阅卷班级列表【PC】
     */
    @Override
    public TableDataInfo<DbTestPaperVo> getPhaseList(DbTestPaperBo bo, PageQuery pageQuery) {
        Page<DbTestPaperVo> result = baseMapper.getPhaseList(pageQuery.build(), bo);
        return TableDataInfo.build(result);
    }

    /**
     * 【PC】 审批阅卷班级列表
     */
    @Override
    public TableDataInfo<DbTestPaperVo> getClassList(DbTestPaperBo bo, PageQuery pageQuery) {
        Page<DbTestPaperVo> result = baseMapper.getClassList(pageQuery.build(), bo);
        return TableDataInfo.build(result);
    }

    /**
     * 完成批卷
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<Void> completeReadOver(DbTestPaperRecordBo bo) {
        // 根据记录id获取记录详情
        List<DbTestPaperRecordDetailVo> recordDetails = recordDetailMapper.getTotalPoints(bo);
        DbTestPaperRecord record = baseMapper.selectById(bo.getId());
        // 计算总得分
        BigDecimal totalPoints = recordDetails.stream().map(DbTestPaperRecordDetailVo::getScore).reduce(BigDecimal.ZERO, BigDecimal::add);
        record.setTotalPoints(totalPoints);
        record.setStatus(3);
        // 保存总得分
        baseMapper.updateById(record);

        // 获取选择题错题集
        List<Long> collect = recordDetails.stream()
            .filter(detail -> detail.getSpecies().equals(2) && (StringUtils.isEmpty(detail.getAnswer()) || !detail.getAnswer().equals(detail.getCorrectAnswer())))
            .map(DbTestPaperRecordDetailVo::getQuestionBankId)
            .collect(Collectors.toList());
        // 创建错题列表对象
        List<DbErrorList> errorLists = new ArrayList<>();
        collect.forEach(id -> {
            DbErrorList errorList = new DbErrorList();
            errorList.setRecordId(record.getId());
            errorList.setUserId(record.getUserId());
            errorList.setPaperId(record.getTestPaperId());
            errorList.setQuestionBankId(id);
            errorLists.add(errorList);
        });
        errorListMapper.insertBatch(errorLists);
        return R.ok();
    }
}
