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.enums.PaperState;
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.jeecg.common.util.RedisUtil;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Objects;

/**
 * 超时自动交卷任务
 *
 * @author bool
 */
@Slf4j
public class BreakExamJob implements Job {

    @Autowired
    private IExamService examService;

    @Autowired
    private IUserExamService userExamService;

    @Autowired
    public RedisUtil redisUtil;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        JobDetail detail = jobExecutionContext.getJobDetail();
        String key = String.valueOf(detail.getJobDataMap().get("parameter"));

        log.info("{} 定时任务：处理到期的交卷", key);
        UserExam userExam = userExamService.getById(key);
        if (!Objects.isNull(userExam) && !userExam.getState().equals(PaperState.FINISHED)) {
            Object data = redisUtil.get(key);
            // 强制交卷
            if (!Objects.isNull(data)) {
                ExamSubmitDTO dto = JSON.parseObject(String.valueOf(data), ExamSubmitDTO.class);
                examService.submitExam(dto);
                return;
            }
        }
        examService.deleteAutoCommitJob(key);
    }
}
