package org.jeecg.config.mybatis.interceptor;

import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.system.vo.ApiCountModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;

import static org.jeecg.common.util.IpUtils.getIpAddr;
@Component
public class ApiAccessCounterInterceptor implements HandlerInterceptor {
//    private static final String USER_AGENT = "user-agent";
//    private int requestCount = 0;
    @Autowired
    private CommonAPI commonAPI;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws UnknownHostException {
//        String uri = request.getRequestURI();
//        String header = request.getHeader(USER_AGENT);
//        System.out.println("请求方法路径:" + uri);
//        System.out.println("来路的设备信息: {}"+ header);
        // 请求计数器增加
//        requestCount++;
        String ipAddr = getIpAddr(request);
        InetAddress inetAddress = InetAddress.getLocalHost();
        String ip = inetAddress.getHostAddress();
//        if(!ipAddr.equals(ip) && !ipAddr.equals("127.0.0.1")){
        if(!ipAddr.equals(ip)){
            ApiCountModel apiCountModel = new ApiCountModel();
            if (handler instanceof HandlerMethod) {
                HandlerMethod handlerMethod = (HandlerMethod) handler;
                String method_url = handlerMethod.getBeanType().getName();
                String method_name = handlerMethod.getMethod().getName();
                apiCountModel.setMethodUrl(method_url);
                apiCountModel.setMethodName(method_name);
                apiCountModel.setVisitIp(ipAddr);
                apiCountModel.setVisitTime(new Date());
                commonAPI.addApiCountModel(apiCountModel);
            }
            return true;
        }
        return true;
    }
//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        //访问目标资源后执行
//        System.out.println("postHandle方法执行了~~~~~~~~~~~~~~~~~~~");
//    }
//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        //前端视图渲染完毕后,执行(是三个方法中最后执行的)
//        System.out.println("afterCompletion方法执行了~~~~~~~~~~~~~~");
//    }
}
