package com.ynfy.buss.exam.job;

import com.alibaba.fastjson.JSON;
import com.ynfy.buss.exam.exam.dto.ExamSubmitDTO;
import com.ynfy.buss.exam.exam.service.IExamService;
import com.ynfy.buss.exam.userexam.entity.UserExam;
import com.ynfy.buss.exam.userexam.service.IUserExamService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.jeecg.common.util.RedisUtil;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

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

/**
 * 考试交卷补偿任务
 *
 * @author bool
 */
@Slf4j
public class MakeupSubmitExamJob implements Job {

    @Autowired
    private IExamService examService;

    @Autowired
    private IUserExamService userExamService;

    @Autowired
    public RedisUtil redisUtil;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info("考试交卷补偿任务开始执行：处理已经过期了，但是状态还在进行中的考试...");
        List<UserExam> userExamList = userExamService.listExpireExamIn();
        if (!CollectionUtils.isEmpty(userExamList)) {
            userExamList.forEach(userExam -> {
                Object data = redisUtil.get(userExam.getId());
                // 交卷
                ExamSubmitDTO dto = null;
                if (!Objects.isNull(data)) {
                    dto = JSON.parseObject(String.valueOf(data), ExamSubmitDTO.class);
                } else {
                    dto = new ExamSubmitDTO(userExam.getId(), null, null);
                }
                examService.submitExam(dto);
                examService.deleteAutoCommitJob(userExam.getId());
            });
        }
    }
}
