package com.usky.system.service.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import javax.servlet.http.HttpServletRequest;
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(HttpServletRequest request, Integer tenantId, final String username, final String status, final String message, final Integer deptId) {
        executorEvent.execute(() -> {
            try {
                // 直接使用传入的request参数
                AsyncFactory.recordLoginInfo(request, tenantId, username, status, message, deptId);
            } catch (Exception e) {
                logger.error("记录登录信息异常", e);
            }
        });
    }
}

