package cn.com.ctop.job.kuaishou.config.interceptors;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.DateUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by JQ.bi on 2020.5.8
 */
@Component
@Slf4j
public class BrowseLogHandelInterceptor extends HandlerInterceptorAdapter {

    private static final String REQUEST_METHOD = "GET_POST_PUT_DELETE_OPTIONS";

    private final static ExecutorService executorServicePool;

    //加载一次
    static {
        int threadCount = Runtime.getRuntime().availableProcessors();
        ThreadFactoryBuilder builder = new ThreadFactoryBuilder();
        builder.setNameFormat("BrowseLogHandlerFactory");
        builder.setDaemon(true);
        builder.setUncaughtExceptionHandler((t, e) -> {
        });//忽略异常
        builder.setPriority(Thread.MIN_PRIORITY);
        executorServicePool = new ThreadPoolExecutor(threadCount, threadCount,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(100000), builder.build(), new ThreadPoolExecutor.DiscardPolicy());
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        if (REQUEST_METHOD.contains(request.getMethod())) {
            if (request.getRequestURI().endsWith("/sys/permission/getUserPermissionByToken")||request.getRequestURI().endsWith("/getEncryptedString")||request.getRequestURI().endsWith("/login")||request.getRequestURI().endsWith("/sys/annountCement/listByUser")) {
                return;
            }
            boolean isSuccess = true;
            if (response.getStatus() != 200) {
                isSuccess = false;
            }
            String userName = JwtUtil.getUserNameByToken(request);
            if (StringUtils.isEmpty(userName)) {
                log.warn("登陆账号用户名为空");
            }
            String token = request.getHeader("X-Access-Token");
            String uri = request.getRequestURI();
            String currentDate = DateUtils.now();
            BrowseLogRunnable runnable = new BrowseLogRunnable(userName, isSuccess,token, uri, currentDate);
            executorServicePool.submit(runnable);
        }
    }


    private static class BrowseLogRunnable implements Runnable {
        String userName;
        Boolean isSuccess;
        String token;
        String uri;
        String currentDate;
        BrowseLogRunnable(String userName, boolean isSuccess, String token, String uri, String currentDate) {
            this.userName = userName;
            this.isSuccess = isSuccess;
            this.token = token;
            this.uri = uri;
            this.currentDate = currentDate;
        }

        @Override
        public void run() {
            try {
                if (!StringUtils.isEmpty(token)) {
                    if(isSuccess){
                        log.info("-SUCCESS " + currentDate + " 用户：" + userName + " 访问了[" + uri + "]?token=\"" + token + "\"");
                    }else {
                        log.info("-FALSE " + currentDate + " 用户：" + userName + "” 访问了[" + uri + "]?token=\"" + token + "\"");
                    }
                }
            } catch (Exception e) {
                log.error(e.toString());
            }
        }
    }
}

