package cn.com.qmth.examcloud.tool.service;

import cn.com.qmth.examcloud.tool.dao.TaskRepository;
import cn.com.qmth.examcloud.tool.entity.TaskEntity;
import cn.com.qmth.examcloud.tool.enums.TaskStatus;
import cn.com.qmth.examcloud.tool.enums.TaskType;
import cn.com.qmth.examcloud.tool.service.config_exam_paper.ConfigExamPaperTask;
import cn.com.qmth.examcloud.tool.service.create_random_paper_template.CreateRandomPaperTemplateTask;
import cn.com.qmth.examcloud.tool.service.export_student_answer_and_score_detail.ExportStudentAnswerAndScoreDetailTask;
import cn.com.qmth.examcloud.tool.service.update_correct_answer_and_re_fix_score.UpdateCorrectAnswerAndReFixScoreTask;
import cn.com.qmth.examcloud.tool.utils.StatusException;
import cn.com.qmth.examcloud.tool.vo.task.TaskAdd;
import cn.com.qmth.examcloud.tool.vo.task.TaskQuery;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Component
public class TaskService {

    private final static Logger log = LoggerFactory.getLogger(TaskService.class);

    @Autowired
    private TaskRepository taskRepository;

    @Autowired
    private ExportStudentAnswerAndScoreDetailTask exportStudentAnswerAndScoreDetailTask;

    @Autowired
    private UpdateCorrectAnswerAndReFixScoreTask updateCorrectAnswerAndReFixScoreTask;

    @Autowired
    private ConfigExamPaperTask configExamPaperTask;

    @Autowired
    private CreateRandomPaperTemplateTask createRandomPaperTemplate;

    public Page<TaskEntity> getTaskList(TaskQuery req) {
        if (req.getPageNo() == null || req.getPageNo() < 1) {
            req.setPageNo(1);
        }

        if (req.getPageSize() == null || req.getPageSize() < 1) {
            req.setPageSize(10);
        }

        Specification<TaskEntity> spec = (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();

            if (req.getType() != null) {
                predicates.add(cb.equal(root.get("type"), req.getType()));
            }

            if (req.getStatus() != null) {
                predicates.add(cb.equal(root.get("status"), req.getStatus()));
            }

            if (req.getExamId() != null) {
                predicates.add(cb.equal(root.get("examId"), req.getExamId()));
            }

            if (req.getOperatorId() != null) {
                predicates.add(cb.equal(root.get("operatorId"), req.getOperatorId()));
            }

            return cb.and(predicates.toArray(new Predicate[predicates.size()]));
        };

        Sort sort = Sort.by(Sort.Order.desc("id"));
        Pageable pageable = PageRequest.of(req.getPageNo() - 1, req.getPageSize(), sort);
        return taskRepository.findAll(spec, pageable);
    }

    public TaskEntity getTaskById(Long taskId) {
        Optional<TaskEntity> entity = taskRepository.findById(taskId);
        return entity.orElse(null);
    }

    public Long getFirstWaitingTaskId() {
        return taskRepository.getFirstWaitingTaskId();
    }

    public int clearExpiredTaskStatus() {
        return taskRepository.clearExpiredTaskStatus();
    }

    @Transactional
    public Long addTask(TaskAdd req) {
        if (req.getType() == null) {
            throw new StatusException("任务类型不能为空！");
        }

        if (StringUtils.isEmpty(req.getParams())) {
            throw new StatusException("任务参数不能为空！");
        }

        if (StringUtils.length(req.getParams()) > 2000) {
            throw new StatusException("任务参数内容超长！");
        }

        TaskEntity entity = new TaskEntity();
        entity.setCreationTime(new Date());
        entity.setUpdateTime(new Date());
        entity.setStatus(TaskStatus.WAITING);
        entity.setType(req.getType());
        entity.setOperatorId(req.getOperatorId());
        entity.setOperatorName(req.getOperatorName());
        entity.setUserToken(req.getUserToken());
        entity.setExamId(req.getExamId());
        entity.setParams(req.getParams());

        taskRepository.save(entity);
        return entity.getId();
    }

    // @Transactional
    public void executeTask(Long taskId) {
        long start = System.currentTimeMillis();

        TaskEntity task = this.getTaskById(taskId);
        task.setStartTime(new Date());
        task.setStatus(TaskStatus.RUNNING);
        taskRepository.save(task);

        try {
            if (TaskType.EXPORT_STUDENT_ANSWER_AND_SCORE_DETAIL == task.getType()) {
                exportStudentAnswerAndScoreDetailTask.start(task);
            } else if (TaskType.UPDATE_CORRECT_ANSWER_AND_RE_FIX_SCORE == task.getType()) {
                updateCorrectAnswerAndReFixScoreTask.start(task);
            } else if (TaskType.CONFIG_EXAM_PAPER == task.getType()) {
                configExamPaperTask.start(task);
            } else if (TaskType.CREATE_RANDOM_PAPER_TEMPLATE == task.getType()) {
                createRandomPaperTemplate.start(task);
            } else {
                throw new StatusException("功能暂未实现!");
            }

            task.setStatus(TaskStatus.SUCCESS);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            task.setDescription(e.getMessage());
            task.setStatus(TaskStatus.ERROR);
        } finally {
            task.setEndTime(new Date());
            taskRepository.save(task);
        }

        log.info("TASK_{} cost {}s", taskId, (System.currentTimeMillis() - start) / 1000);
    }

}
