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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ynfy.buss.exam.exam.enums.PaperState;
import com.ynfy.buss.exam.userexam.entity.UserExam;
import com.ynfy.buss.exam.userexam.mapper.UserExamMapper;
import com.ynfy.buss.exam.userexam.service.IUserExamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * @Description: 用户考试表
 * @Author: jeecg-boot
 * @Date: 2023-03-05
 * @Version: V1.0
 */
@Service
public class UserExamServiceImpl extends ServiceImpl<UserExamMapper, UserExam> implements IUserExamService {
    @Autowired
    private UserExamMapper userExamMapper;

    /**
     * 检查是否有正在进行中的考试
     *
     * @param userId
     * @return
     */
    @Override
    public boolean checkExamIn(String userId) {
        LambdaQueryWrapper<UserExam> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserExam::getUserId, userId).eq(UserExam::getState, PaperState.ING);
        return this.count(wrapper) > 0 ? true : false;
    }


    /**
     * 获取正在进行中的考试
     *
     * @param userId
     * @return
     */
    @Override
    public UserExam listExamIn(String userId) {
        LambdaQueryWrapper<UserExam> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserExam::getUserId, userId).eq(UserExam::getState, PaperState.ING);
        List<UserExam> list = this.list(wrapper);
        return !CollectionUtils.isEmpty(list) ? list.get(0) : null;
    }

    /**
     * 统计用户某次考试参加的次数
     *
     * @param userId
     * @return
     */
    @Override
    public long countUserExam(String userId, String examId) {
        LambdaQueryWrapper<UserExam> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserExam::getUserId, userId).eq(UserExam::getExamId, examId);
        return this.count(wrapper);
    }

    /**
     * 查询用户考试信息及试题
     *
     * @param id
     * @return
     */
    @Override
    public UserExam listUserExam(String id) {
        return userExamMapper.listUserExam(id);
    }


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

    /**
     * 获取过期了，并且正在进行中的考试
     *
     * @return
     */
    @Override
    public List<UserExam> listExpireExamIn() {
        LambdaQueryWrapper<UserExam> wrapper = new LambdaQueryWrapper<>();
        wrapper.le(UserExam::getLimitTime, new Date()).eq(UserExam::getState, PaperState.ING);
        return this.list(wrapper);
    }
}
