package com.zjrs.ggfw.rlzysc.bpo.schedule.tasklog;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import com.zjrs.ggfw.rlzysc.blo.TaskLogBLO;
import com.zjrs.ggfw.rlzysc.bpo.schedule.Task;
import com.zjrs.ggfw.rlzysc.po.SpringScheduledCronLogPO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

@Component
@Aspect
public class TaskLog {

    private static final Logger LOG = LoggerFactory.getLogger(TaskLog.class);

    @Autowired
    private TaskLogBLO taskLogBLO;

    private String getdataString() {
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return dateFormat.format(date);
    }

    /**
     * 按照切入点表达式定义的类路径格式，可以在执行定时器的时候自动插入日志
     *
     * @param joinPoint
     */
    @Around(value = "execution(* com.zjrs.ggfw.rlzysc.bpo.schedule.execute.*.excute(..)))")
    public void aroundLog(ProceedingJoinPoint joinPoint) {
        if (Arrays.asList(joinPoint.getTarget().getClass().getInterfaces()).contains(Task.class)){
            Object[] args = joinPoint.getArgs();
            String cronid = (String) args[0];
            SpringScheduledCronLogPO logpo = new SpringScheduledCronLogPO();
            logpo.setCronid(cronid);
            logpo.setKssj(getdataString());
            try {
                joinPoint.proceed(args);
                logpo.setStatus("1");
            } catch (Throwable e) {
                LOG.error(e.getMessage());
                logpo.setStatus("2");
                logpo.setExec(e.getMessage().substring(0,500));
            } finally {
                //最终都要记录日志
                logpo.setJssj(getdataString());
                taskLogBLO.saveLog(logpo);
            }
        }
    }
}

