package com.engine.organization.util;

import com.engine.organization.annotation.Log;
import com.engine.organization.entity.LoggerContext;
import com.engine.organization.enums.DeleteTypeEnum;
import com.engine.organization.mapper.sislog.SISLogMapper;
import com.engine.organization.util.db.MapperProxyFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author weaver_cl
 * @description: 日志切面操作
 * @Date 2022/4/27
 * @Version V1.0
 **/
public class LogAspect<T> {

    Class<T> clazz;

    Method method;

    LoggerContext loggerContext;

    private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);


    public LogAspect(Class<T> clazz, Method method, LoggerContext loggerContext) {
        this.clazz = clazz;
        this.method = method;
        this.loggerContext = loggerContext;
    }

    public void start() {
        try {
            //线程池
            ExecutorService taskExecutor = Executors.newCachedThreadPool();
            taskExecutor.execute(() -> {
                boolean f = method.isAnnotationPresent(Log.class);
                if (f) {
                    Log annotation = method.getAnnotation(Log.class);
                    String value = annotation.operateType().getValue();
                    String operateDesc = annotation.operateDesc();
                    String operateModuleName = annotation.operateModule().getName();
                    Integer operateModule = annotation.operateModule().getValue();
                    loggerContext.setOperateDesc(operateDesc);
                    loggerContext.setCreateTime(new Date());
                    loggerContext.setOperateType(value);
                    loggerContext.setMethodName(method.getName());
                    loggerContext.setClassName(clazz.getName());
                    loggerContext.setDeleteType(DeleteTypeEnum.NOT_DELETED.getValue());
                    loggerContext.setOperateModuleName(operateModuleName);
                    loggerContext.setOperateModule(operateModule);
                    MapperProxyFactory.getProxy(SISLogMapper.class).insert(loggerContext);
                }
            });


        } catch (Exception e) {
            // 记录本地异常日志
            logger.error("后置通知异常:异常信息:", e.getMessage());
        }
    }
}
