package org.springblade.core.config;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

import org.springblade.core.boot.properties.SpringBootProperties;
import org.springblade.core.boot.properties.ThreadPoolProperties;
import org.springblade.core.log.config.EventConstant;
import org.springblade.core.log.entity.LogError;
import org.springblade.core.log.event.ErrorLogEvent;
import org.springblade.core.log.utils.LogTraceUtil;
import org.springblade.core.tool.utils.ObjectUtil;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.task.TaskExecutorCustomizer;
import org.springframework.boot.task.TaskSchedulerCustomizer;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNull;
import org.springframework.scheduling.annotation.AsyncConfigurerSupport;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.ErrorHandler;

import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

/**
 * @Async 注解的线程池配置 以及 自定义线程池配置
 *
 * @author wookvn
 */
@Slf4j
@Configuration
@EnableAsync
@EnableScheduling
@AllArgsConstructor
@EnableConfigurationProperties(ThreadPoolProperties.class)
public class GmetryExecutorConfiguration extends AsyncConfigurerSupport {

	private final SpringBootProperties springBootProperties;
	private final ApplicationEventPublisher publisher;
	private final ThreadPoolProperties threadPoolProperties;
	public class ContextAwareCallable<T> implements Callable<T> {
		private Callable<T> task;
		private RequestAttributes context;

		public ContextAwareCallable(Callable<T> task, RequestAttributes context) {
			this.task = task;
			this.context = context;
		}

		@Override
		public T call() throws Exception {
			if (context != null) {
				RequestContextHolder.setRequestAttributes(context);
			}
			try {
				return task.call();
			} finally {
				RequestContextHolder.resetRequestAttributes();
			}
		}
	}

	public class ContextAwarePoolExecutor extends ThreadPoolTaskExecutor {
		@Override
		public <T> Future<T> submit(Callable<T> task) {
			return super.submit(new ContextAwareCallable(task, RequestContextHolder.currentRequestAttributes()));
		}

		@Override
		public <T> ListenableFuture<T> submitListenable(Callable<T> task) {
			return super.submitListenable(new ContextAwareCallable(task, RequestContextHolder.currentRequestAttributes()));
		}
	}

	@Override
	@Bean
	public Executor getAsyncExecutor() {
		return new ContextAwarePoolExecutor();
	}

	@Bean
	public TaskExecutorCustomizer taskExecutorCustomizer() {
		return taskExecutor -> {
			taskExecutor.setThreadNamePrefix("platomix-async-task-");
			taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
		};
	}

	@Bean
	public TaskSchedulerCustomizer taskSchedulerCustomizer() {
		return taskExecutor -> {
			taskExecutor.setThreadNamePrefix("platomix-async-scheduler");
			taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
			taskExecutor.setErrorHandler(new PlatomixErrorHandler(springBootProperties, publisher));
		};
	}

	@Bean
	public ThreadPoolTaskExecutor taskExecutor() {
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		// 核心线程数
		executor.setCorePoolSize(threadPoolProperties.getCorePoolSize());
		// 最大线程数
		executor.setMaxPoolSize(threadPoolProperties.getMaxPoolSize());
		// 队列容量
		executor.setQueueCapacity(threadPoolProperties.getQueueCapacity());
		// 线程名称前缀
		executor.setThreadNamePrefix("platomix-customExecutor-");
		// 存活时间
		executor.setKeepAliveSeconds(threadPoolProperties.getKeepAliveSeconds());
		executor.setAllowCoreThreadTimeOut(threadPoolProperties.isAllowCoreThreadTimeOut());
		executor.initialize(); // 初始化
		return executor;
	}

	@Override
	public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
		return new PlatomixAsyncUncaughtExceptionHandler(springBootProperties, publisher);
	}

	@RequiredArgsConstructor
	private static class PlatomixAsyncUncaughtExceptionHandler implements AsyncUncaughtExceptionHandler {
		private final SpringBootProperties springBootProperties;
		private final ApplicationEventPublisher eventPublisher;

		@Override
		public void handleUncaughtException(@NonNull Throwable error, @NonNull Method method, @NonNull Object... params) {
			log.error("Unexpected exception occurred invoking async method: {}", method, error);
			LogError logError = new LogError();
			// 服务信息、环境、异常类型
			logError.setParams("async");
			logError.setEnv(springBootProperties.getEnv());
			logError.setServiceId(springBootProperties.getServiceId());
//			logError.setRequestUri(bladeContext.getRequestId());
			// 堆栈信息
			initErrorInfo(error, logError);
			Map<String, Object> event = new HashMap<>(16);
			event.put(EventConstant.EVENT_LOG, logError);
			eventPublisher.publishEvent(new ErrorLogEvent(event));
		}
	}

	@RequiredArgsConstructor
	private static class PlatomixErrorHandler implements ErrorHandler {
		private final SpringBootProperties springBootProperties;
		private final ApplicationEventPublisher eventPublisher;

		@Override
		public void handleError(@NonNull Throwable error) {
			log.error("Unexpected scheduler exception", error);
			LogError logError = new LogError();
			// 服务信息、环境、异常类型
			logError.setParams("scheduler");
			logError.setServiceId(springBootProperties.getServiceId());
			logError.setEnv(springBootProperties.getEnv());
//			logError.setRequestUri(bladeContext.getRequestId());
			// 堆栈信息
			initErrorInfo(error, logError);
			Map<String, Object> event = new HashMap<>(16);
			event.put(EventConstant.EVENT_LOG, logError);
			eventPublisher.publishEvent(new ErrorLogEvent(event));
		}
	}
	
	static void initErrorInfo(Throwable error, LogError event) {
		// 堆栈信息
		event.setStackTrace(LogTraceUtil.getStackTraceAsString(error));
		event.setExceptionName(error.getClass().getName());
		event.setMessage(error.getMessage());
		event.setCreateTime(new Date());
		StackTraceElement[] elements = error.getStackTrace();
		if (ObjectUtil.isNotEmpty(elements)) {
			// 报错的类信息
			StackTraceElement element = elements[0];
			event.setMethodClass(element.getClassName());
			event.setFileName(element.getFileName());
			event.setMethodName(element.getMethodName());
			event.setLineNumber(element.getLineNumber());
		}
	}

}
