package com.ycwl.basic.watchdog;

import com.ycwl.basic.mapper.TaskMapper;
import com.ycwl.basic.model.pc.task.entity.TaskEntity;
import com.ycwl.basic.notify.NotifyFactory;
import com.ycwl.basic.notify.entity.NotifyContent;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Profile("prod")
public class TaskWatchDog {

    @Autowired
    private TaskMapper taskMapper;

    @Scheduled(fixedDelay = 1000 * 60L)
    public void scanTaskStatus() {
        List<TaskEntity> allNotRunningTaskList = taskMapper.selectAllNotRunning();
        String title = "任务堆积警告！";
        StringBuilder content = new StringBuilder();
        if (allNotRunningTaskList.size() > 10) {
            content.append("当前任务队列中存在超过10个未运行任务，请及时处理！");
        }
        List<TaskEntity> allRunningTaskList = taskMapper.selectAllRunning();
        for (TaskEntity taskEntity : allRunningTaskList) {
            if (taskEntity.getStartTime() == null) {
                continue;
            }
            // startTime已经过去3分钟了
            if (System.currentTimeMillis() - taskEntity.getStartTime().getTime() > 1000 * 60 * 3) {
                content.append("当前【").append(taskEntity.getWorkerId()).append("】渲染机的【").append(taskEntity.getId()).append("】任务已超过3分钟未完成！");
            }
        }
        if (StringUtils.isNotBlank(content)) {
            NotifyFactory.via().sendTo(
                    new NotifyContent(title, content.toString()),
                    "default_user"
            );
        }
    }
}
