package com.ywt.mg.web.interceptors;

import com.ywt.mg.core.utils.WebHelper;
import com.ywt.mg.web.BaseResponse;
import com.ywt.mg.web.CookiesHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 全局拦截
 * 采集访问日志
 * Created by huangguoping.
 */
@Service("accessBehaviorInterceptor")
public class AccessBehaviorInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplateSupper;

    private void toResponse(BaseResponse response, HttpServletResponse httpServletResponse) throws IOException {

//        String responseData = JsonSerializer.toJson(response);
//        httpServletResponse.setStatus(200);
//        byte[] responseDataBytes = responseData.getBytes("utf-8");
//        httpServletResponse.setContentLength(responseDataBytes.length);
//        httpServletResponse.getOutputStream().write(responseDataBytes);
    }

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        try {
            WebAppContext.current().init();
            WebAppContext.current().setRequestStartTime(System.currentTimeMillis())
                    .setRequestID(UUID.randomUUID().toString())
                    .setIP(WebHelper.getIP(httpServletRequest))
                    .setCookies(CookiesHelper.getCookiesDict(httpServletRequest));
            WebAppContext.current().setHost(httpServletRequest.getServerName()).setSession(httpServletRequest.getSession())
                    .setToken(httpServletRequest.getHeader("at"));

        } catch (Exception e) {
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        try {
            Map<String, Object> logData = new HashMap<>();
            logData.put("url", httpServletRequest.getRequestURI());
            //logData.put("ip", WebHelper.getIP(httpServletRequest));
            logData.put("method", httpServletRequest.getMethod());
            logData.put("referer", httpServletRequest.getHeader("referer"));
            logData.put("reqid", WebAppContext.current().getRequestID());
            logData.put("starttime", WebAppContext.current().getRequestStartTime() / 1000);
            logData.put("endtime", System.currentTimeMillis() / 1000);
            logData.put("comsumtime", System.currentTimeMillis() - WebAppContext.current().getRequestStartTime());
            logData.put("capchecked", WebAppContext.current().capChecked());
            logData.put("host", WebAppContext.current().getHost());


            //System.out.println("AccessBehavior completion: " + JsonSerializer.toJson(logData));
            //behaviorLogService.addAccessLog(logData);
        } catch (Exception e_s) {
        }
    }
}
