package com.ruoyi.wgz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.wgz.bo.req.WgzAppSubmitATestPaperReq;
import com.ruoyi.wgz.bo.res.WgzAppSubmitATestPaperRes;
import com.ruoyi.wgz.domain.WgzQuestionBank;
import com.ruoyi.wgz.domain.WgzQuestionsConfiguration;
import com.ruoyi.wgz.service.IWgzQuestionBankService;
import com.ruoyi.wgz.service.IWgzQuestionsConfigurationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.core.mybatisplus.core.ServicePlusImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.wgz.bo.WgzQuestionSaveQueryBo;
import com.ruoyi.wgz.domain.WgzQuestionSave;
import com.ruoyi.wgz.mapper.WgzQuestionSaveMapper;
import com.ruoyi.wgz.service.IWgzQuestionSaveService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 用户试卷存储Service业务层处理
 *
 * @author ruoyi
 * @date 2025-02-17
 */
@Service
public class WgzQuestionSaveServiceImpl extends ServicePlusImpl<WgzQuestionSaveMapper, WgzQuestionSave> implements IWgzQuestionSaveService {

	@Autowired
	private IWgzQuestionsConfigurationService iWgzQuestionsConfigurationService;

	@Autowired
	private IWgzQuestionBankService iWgzQuestionBankService;

    @Override
    public WgzQuestionSave queryById(Long id){
        return getById(id);
    }

    @Override
    public TableDataInfo<WgzQuestionSave> queryPageList(WgzQuestionSaveQueryBo bo) {
        Page<WgzQuestionSave> result = page(PageUtils.buildPage(), buildQueryWrapper(bo));
        return PageUtils.buildDataInfo(result);
    }

    @Override
    public List<WgzQuestionSave> queryList(WgzQuestionSaveQueryBo bo) {
        return list(buildQueryWrapper(bo));
    }

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

    @Override
    public Boolean insert(WgzQuestionSave bo) {
        WgzQuestionSave add = BeanUtil.toBean(bo, WgzQuestionSave.class);
        validEntityBeforeSave(add);
        return save(add);
    }

    @Override
    public Boolean update(WgzQuestionSave bo) {
        WgzQuestionSave update = BeanUtil.toBean(bo, WgzQuestionSave.class);
        validEntityBeforeSave(update);
        return updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(WgzQuestionSave entity){
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return removeByIds(ids);
    }

	/**
	 * APP相关
	 * =================================================================================================================
	 * =================================================================================================================
	 * =================================================================================================================
	 */

	@Override
	@Transactional
	public WgzAppSubmitATestPaperRes userSubmitATestPaper(WgzAppSubmitATestPaperReq req) {
		// 初始化第一次分数和当前考试的分数
		double scoreOne = 0.00;
		double scoreTwo = 0.00;
		//1、获取上次考试的分数
		Map<String, Object> spMap = baseMapper.getSumScoreAndPassAndSign(req.getUserId());
		if (spMap != null) {
			String pass = (String) spMap.get("pass");
			if (pass != null && !pass.isEmpty()) {
				String[] split = pass.split(",");
				double float1 = Double.parseDouble(split[1]);
				double sumScore = (double) spMap.get("sumScore");
				scoreOne = 100.00 / float1 * sumScore;
			}
		}
		//2、获取配置信息
		WgzQuestionsConfiguration configuration = iWgzQuestionsConfigurationService.appQueryLimitOne();
		//3、计算这次用户提交的试卷信息所得到的分数
		List<WgzQuestionSave> bqs  = new ArrayList<>();
		AtomicReference<Double> fenshu = new AtomicReference<>(0.0);
		AtomicInteger number = new AtomicInteger(0);
		AtomicInteger index = new AtomicInteger(0);
		req.getList().forEach(data -> {
			String correct = "";
			String pass = "";
			// 获取题库的正确答案，然后和用户的答案作对比
			WgzQuestionBank bqb  = iWgzQuestionBankService.selectById(data.getBankId());
			if (bqb == null) {
				throw new RuntimeException("您的试卷被外星人卷走了！");
			} else {
				if (StringUtils.isEmpty(data.getAnswer())) {
					throw new RuntimeException("您还有题未答完！");
				}
				if (bqb.getCorrectAnswer().toLowerCase().contains(data.getAnswer().toLowerCase())) {
					correct = "1";
					fenshu.updateAndGet(v -> v + data.getScore());
					number.incrementAndGet();
				} else {
					correct = "2";
				}
			}
			// 记录这次的及格线和总分
			pass = configuration.getPassingScore().toString() + "," + configuration.getFullMark().toString();
			WgzQuestionSave bqsTwo = new WgzQuestionSave();
			bqsTwo.setUserId(req.getUserId());
			bqsTwo.setBankId(data.getBankId());
			bqsTwo.setAnswer(data.getAnswer());
			bqsTwo.setCorrect(correct);
			bqsTwo.setScore(data.getScore());
			//这几条数据只在每张试卷的第一条数据中存储（重复的没必要每条都存储）
			if (index.get() == 0) {
				bqsTwo.setTakeTime(req.getTakeTime());
				bqsTwo.setTimeOut(configuration.getAnswerTime());
				bqsTwo.setPass(pass);
			}
			bqs.add(bqsTwo);
			index.incrementAndGet();
		});
		Double fullMark = configuration.getFullMark();
		scoreTwo = 100.00 / fullMark * fenshu.get();
		WgzAppSubmitATestPaperRes res = new WgzAppSubmitATestPaperRes();
		res.setAnswerTime(configuration.getAnswerTime());
		res.setTakeTime(req.getTakeTime());
		res.setFullMark(fullMark);
		res.setPassingScore(configuration.getPassingScore());
		res.setScore(fenshu.get());
		res.setNumber(number.get());
		//4、两次卷子的分数对比,第一次的分数比第二次大那么第二次只返回结果；第二次的分数比第一次大那么删除第一次的数据再重新插入
		if (scoreOne > scoreTwo) {
			return res;
		} else {
			// 先查询当前用户是否有答题，有就把之前的删除(真删)
			int deleteResult = baseMapper.delete(new LambdaQueryWrapper<WgzQuestionSave>().eq(WgzQuestionSave::getUserId, req.getUserId()));
			if (deleteResult >0){
				// 插入新数据
				super.saveBatch(bqs);
			}
		}
		return res;
	}
}
