package com.ywt.glasses.controllers.mg.interceptors;

import com.fasterxml.jackson.databind.JsonNode;


import com.ywt.biz.common.util.Checker;
import com.ywt.biz.common.util.serializers.JsonSerializer;
import com.ywt.glasses.controllers.mg.core.WebAppContext;
import com.ywt.glasses.utils.WebHelper;
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.util.UUID;

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

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

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        try {
            WebAppContext.current().init();
            WebAppContext.current().setRequestStartTime(System.currentTimeMillis());
            WebAppContext.current().setRequestID(UUID.randomUUID().toString());
            WebAppContext.current().setIP(WebHelper.getIP(httpServletRequest));

            String terminalStr = Checker.getStringValue(httpServletRequest.getHeader("pl-terminal"));
            String gwProtocol = Checker.getStringValue(httpServletRequest.getHeader("gw-protocol"));
            String gwAuthAppid = Checker.getStringValue(httpServletRequest.getHeader("auth-appid"));

            WebAppContext.current().setTerminal(Checker.parseInt(terminalStr));
            WebAppContext.current().setGWProtocol(gwProtocol);
            WebAppContext.current().setGWAuthAppid(gwAuthAppid);

            String authData = httpServletRequest.getHeader("auth-data");
            logger.info("------------------------ AccessBehaviorInterceptor: ");
            logger.info("authData: " + authData);
            if (!Checker.isNone(authData)) {
                try {
                    JsonNode jsonNode = JsonSerializer.readToNode(authData);
                    if (jsonNode != null && jsonNode.get("userId") != null) {
                        WebAppContext.current().setUserId(Checker.parseInt(jsonNode.get("userId").asText("0")));
                    }
                    if (jsonNode != null && jsonNode.get("openId") != null) {
                        WebAppContext.current().setOpenId(Checker.getStringValue(jsonNode.get("openId").asText("")));
                    }
                    if (jsonNode != null && jsonNode.get("unionId") != null) {
                        WebAppContext.current().setUnionId(Checker.getStringValue(jsonNode.get("unionId").asText("")));
                    }
                    if (jsonNode != null && jsonNode.get("shopId") != null) {
                        WebAppContext.current().setShopId(Checker.parseInt(jsonNode.get("shopId").asText("0")));
                    }
                    if (jsonNode != null && jsonNode.get("hospitalId") != null) {
                        WebAppContext.current().setHospitalId(Checker.parseInt(jsonNode.get("hospitalId").asText("0")));
                    }
                } catch (Exception e) {
                    logger.error("AccessBehaviorInterceptor#preHandle(authData={}):\n {}", authData, e.getMessage(), e);
                }
            }

            String authParam = httpServletRequest.getHeader("auth-param");
            System.out.println("------------------------ AccessBehaviorInterceptor: ");
            System.out.println("authParam: " + authParam);
            if (!Checker.isNone(authParam)) {
                try {
                    JsonNode jsonNode = JsonSerializer.readToNode(authParam);
                    //从网关的授权附属参数中获取终端标识
                    if (jsonNode != null && jsonNode.get("terminal") != null) {
                        WebAppContext.current().setTerminal(Checker.parseInt(jsonNode.get("terminal").asText("0")));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("preHandle---:{},{}", e, e.getMessage());
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("preHandle---:{},{}", e, e.getMessage());
        }
        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 {

    }
}
