package com.smppw.modaq.domain.service;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.smppw.modaq.domain.entity.TaskRecordDO;
import com.smppw.modaq.domain.mapper.TaskRecordMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

@Service
public class TaskRecordService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private final TaskRecordMapper mapper;

    public TaskRecordService(TaskRecordMapper mapper) {
        this.mapper = mapper;
    }

    /**
     * 获取任务的记录
     *
     * @param taskKey 任务标识
     * @param timeout 执行中的任务超时等待时间，单位秒
     * @return /
     */
    public TaskRecordDO getTaskRecord(String taskKey, int timeout) {
        if (timeout <= 0) {
            throw new RuntimeException("任务超时时间设置错误");
        }
        TaskRecordDO temp = this.getTaskRecordDO(taskKey);
        if (temp != null && Objects.equals(0, temp.getStatus())) {
            Date timeoutDate = DateUtil.offsetSecond(new Date(), -1 * timeout);
            if (temp.getStartTime() != null && temp.getStartTime().compareTo(timeoutDate) < 0) {
                this.logger.info("{} 任务执行超时限制时间{}s，重新执行任务！", taskKey, timeout);
            } else {
                this.logger.warn("{} 任务正在执行中，不能重复执行！", taskKey);
                return null;
            }
        }
        if (temp == null) {
            temp = new TaskRecordDO();
            temp.setTaskKey(taskKey);
            temp.setStartTime(DateUtil.offsetDay(new Date(), -1));
        } else {
            temp.setId(null);
            temp.setErrMsg(null);
            temp.setUpdateTime(null);
            if (Objects.equals(1, temp.getStatus())) {
                temp.setStartTime(temp.getEndTime());
            }
            temp.setEndTime(null);
        }
        temp.setStatus(0);
        temp.setCreateTime(new Date());
        this.mapper.insert(temp);
        return temp;
    }

    public void updateStatus(TaskRecordDO taskRecordDO) {
        if (taskRecordDO == null) {
            return;
        }
        Long id = taskRecordDO.getId();
        if (id != null) {
            taskRecordDO.setUpdateTime(new Date());
            this.mapper.updateById(taskRecordDO);
        } else {
            this.mapper.insert(taskRecordDO);
        }
    }

    /**
     * 获取最近一次执行的记录
     *
     * @param taskKey 任务标识
     * @return /
     */
    private TaskRecordDO getTaskRecordDO(String taskKey) {
        LambdaUpdateWrapper<TaskRecordDO> wrapper = Wrappers.lambdaUpdate(TaskRecordDO.class)
                .eq(TaskRecordDO::getTaskKey, taskKey)
                .orderByDesc(TaskRecordDO::getCreateTime)
                .last("limit 1");
        return this.mapper.selectOne(wrapper);
    }
}
