package com.clx.performance.utils;

import com.msl.common.exception.ServiceSystemException;
import com.msl.common.job.JobLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import java.util.function.Consumer;

/**
 * @Author: aiqingguo
 * @Description:
 * @Date: 2023-10-12 19:38:41
 * @Version: 1.0
 */
@Component
public class JobHandlerService {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    public <T> void handler(String title, Runnable target) {

        handler(title, null, target);
    }

    public <T> void handler(String title, T data, Runnable target) {

        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        logger.info("{}, 主任务开始, data:{}", title, data);

        try {

            target.run();
        }catch (ServiceSystemException e){
            logger.info("{}, 主任务执行失败, data:{}, error:{}, detail:{}", title, data, e.getResultEnum().getMsg(), e.getDetail());
            JobLog.error(title + "定时任务处理失败", e);
        }catch (Exception e){
            logger.error("{}, 主任务执行异常, data:{}, error:{}", title, data, e.getMessage());
            JobLog.error(title + "定时任务处理失败", e);
        }

        stopWatch.stop();
        logger.info("{}, 主任务结束, data:{}, duration:{}", title, data, stopWatch.getTotalTimeMillis());
    }

    public <T> void subHandler(String title, T data, Consumer<T> target) {

        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        logger.info("{}, 子任务开始, data:{}", title, data);

        try {

            target.accept(data);
        }catch (ServiceSystemException e){
            logger.info("{}, 子任务执行失败, data:{}, error:{}, detail:{}", title, data, e.getResultEnum().getMsg(), e.getDetail());
            JobLog.error(title + "定时任务处理失败", e);
        }catch (Exception e){
            logger.error("{}, 子任务执行异常, data:{}, error:{}", title, data, e.getMessage());
            JobLog.error(title + "定时任务处理失败", e);
        }

        stopWatch.stop();
        logger.info("{}, 子任务结束, data:{}, duration:{}", title, data, stopWatch.getTotalTimeMillis());
    }

}
