package com.usky.system.service.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PreDestroy;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @description: 异步任务管理器
 * @author: XiaoYu
 * @date: 2024/08/20 13:58
 */
@Component
public class AsyncManager {

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

    private static final ThreadPoolExecutor executorEvent = new ThreadPoolExecutor(
            20, 30, 0L, TimeUnit.MILLISECONDS,
            new ArrayBlockingQueue<>(1024),
            new ThreadPoolExecutor.AbortPolicy()
    );

    @PreDestroy
    public void shutdown() {
        executorEvent.shutdown();
        try {
            if (!executorEvent.awaitTermination(60, TimeUnit.SECONDS)) {
                executorEvent.shutdownNow();
            }
        } catch (InterruptedException ex) {
            executorEvent.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }

    public void insertLog(Integer tenantId, final String username, final String status, final String message, final Integer deptId) {
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (sra != null) {
            executorEvent.execute(() -> {
                try {
                    RequestContextHolder.setRequestAttributes(sra, true);
                    logger.info("new Log is {} , {}", username, message);
                    AsyncFactory.recordLoginInfo(tenantId, username, status, message, deptId);
                } catch (Exception e) {
                    logger.error("记录登录信息异常", e);
                } finally {
                    RequestContextHolder.resetRequestAttributes();
                }
            });
        } else {
            logger.warn("当前线程没有RequestContext，无法记录登录信息");
        }
    }
}

