/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights reserved.
 * <a>http://www.crunii.com</a>
 */
package com.crunii.micro.ds.aop;

import com.crunii.micro.common.constants.DSConstants;
import com.crunii.micro.domain.common.hibernate.action.OperLogHolder;
import com.crunii.micro.domain.entitysql.main.TOperLogS;
import com.crunii.micro.platform.log.OperLogHandler;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 田平 create 2021/5/14 10:23
 */
@Aspect
@Slf4j
public class OperLogAspect implements TransactionSynchronization {

	public static ThreadLocal<Boolean> registerCallBack = ThreadLocal.withInitial(() -> false);

	@Autowired
	private OperLogHandler operLogHandler;

	@Before(value = DSConstants.AOP_POINTCUT_EXPRESSION)
	public void before(JoinPoint point) {
//		String className = point.getTarget().getClass().getName();
//		String methodName = point.getSignature().getName();
		//当前事务激活注册提交回调
		if (TransactionSynchronizationManager.isActualTransactionActive()) {
			if (!registerCallBack.get()) {
				TransactionSynchronizationManager.registerSynchronization(this);
				registerCallBack.set(true);
			}
		}
	}

	@After(value = DSConstants.AOP_POINTCUT_EXPRESSION)
	public void after(JoinPoint point) {
		registerCallBack.set(false);
	}

	@Override
	public void afterCommit() {
		//创建一个新的list，因为是异步调用，防止clear的时候影响
		List<TOperLogS> operLogs = new ArrayList<>(OperLogHolder.getCurrOperLogs());
		int size = operLogs.size();
		if (size > 0) {
			operLogHandler.doOperLogs(operLogs);
			OperLogHolder.clearCurrOperLogs();
			log.info("async save operLogs!size:{}", size);
		}
	}
}
