package com.ynfy.buss.exam.userexamresult.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ynfy.buss.exam.userexamresult.entity.UserExamResult;
import com.ynfy.buss.exam.userexamresult.entity.vo.UserExamScoreVO;
import com.ynfy.buss.exam.userexamresult.mapper.UserExamResultMapper;
import com.ynfy.buss.exam.userexamresult.service.IUserExamResultService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @Description: 用户考试成绩
 * @Author: jeecg-boot
 * @Date: 2023-03-09
 * @Version: V1.0
 */
@Service
public class UserExamResultServiceImpl extends ServiceImpl<UserExamResultMapper, UserExamResult> implements IUserExamResultService {

    @Autowired
    private UserExamResultMapper userExamResultMapper;

    /**
     * 考试完成后加入成绩
     *
     * @param userId
     * @param examId
     * @param score
     * @param passed
     */
    @Override
    public void joinResult(String userId, String examId, Integer score, int passed) {
        LambdaQueryWrapper<UserExamResult> wrapper = new LambdaQueryWrapper();
        wrapper.eq(UserExamResult::getUserId, userId).eq(UserExamResult::getExamId, examId);
        UserExamResult record = this.getOne(wrapper);
        if (Objects.isNull(record)) {
            record = new UserExamResult();
            record.setUserId(userId);
            record.setExamId(examId);
            record.setMaxScore(score);
            record.setPassed(passed);
            record.setTryCount(1);
            this.save(record);
            return;
        }
        record.setTryCount(record.getTryCount() + 1);
        if (record.getPassed().intValue() != 1) {//原来的考试没有通过才做更新
            record.setPassed(passed);
        }
        if (record.getMaxScore() < score) {
            record.setMaxScore(score);
        }
        this.updateById(record);
    }

    /**
     * 根据条件分页查询
     */
    @Override
    public IPage<UserExamResult> selectPageList(IPage<UserExamResult> page, UserExamResult userExamResult) {
        return userExamResultMapper.selectPageList(page, userExamResult);
    }

    @Override
    public List<UserExamResult> listByExamId(String examId) {
        QueryWrapper<UserExamResult> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(UserExamResult::getExamId, examId);
        return this.list(wrapper);
    }

    /**
     * 获取考试成绩
     *
     * @param examId
     * @return
     */
    @Override
    public UserExamScoreVO examScore(String userId, String examId) {
        return userExamResultMapper.getUserExamScore(userId, examId);
    }
}
