package com.hs.admin.listener;

import com.alibaba.fastjson.JSONObject;
import com.hs.admin.bean.SysTask;
import com.hs.admin.dao.SysTaskDao;
import com.hs.admin.service.SchedulerJobService;
import com.hs.admin.util.JsonUtils;
import com.hs.admin.util.LogUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author xieheng
 */
@Component

public class SchedulerJobListener implements CommandLineRunner {
    private static final Logger LOGGER = LoggerFactory.getLogger(SchedulerJobListener.class);

    @Resource
    SchedulerJobService schedulerJobService;
    @Resource
    SysTaskDao sysTaskDao;

    @Override
    public void run(String... args) {
        try {
            List<SysTask> sysTaskList = sysTaskDao.getAllTaskList();
            if (!CollectionUtils.isEmpty(sysTaskList)) {
                //服务器启动自动启动正常的任务监听
                for (SysTask task : sysTaskList) {
                    String content = task.getContent();
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = JSONObject.parseObject(content);
                        String cronExpression = jsonObject.getString("cronExpression");
                        content = jsonObject.getString("params");
                        task.setContent(content);
                        if (!ObjectUtils.isEmpty(cronExpression)) {
                            task.setCronExpression(cronExpression);
                            task.setBeanClass("com.hs.admin.job.Select");
                            schedulerJobService.initJob(task);
                            LogUtil.info(">>>>>>>定时任务初始化：" + JsonUtils.beanToJson(task));
                        }
                    } catch (Exception e) {
                        LogUtil.error(">>>>>>>定时任务初始化失败"+e);
                    }

                }
            }
        } catch (Exception e) {
            LOGGER.error(">>>SchedulerJobListener error :" + e);
        }
    }
}
