package com.ywt.outpatient.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.outpatient.core.utils.WebHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 {
    private static 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 unionId = Checker.getStringValue(httpServletRequest.getHeader("wx-unionid"));
            String userId = Checker.getStringValue(httpServletRequest.getHeader("wx-userid"));
            String openId = Checker.getStringValue(httpServletRequest.getHeader("wx-openid"));
            String doctorId = Checker.getStringValue(httpServletRequest.getHeader("uid"));
            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().setUserId(Checker.parseInt(userId));
            WebAppContext.current().setUnionId(unionId);
            WebAppContext.current().setOpenId(openId);
            WebAppContext.current().setDoctorId(Checker.parseInt(doctorId));
            WebAppContext.current().setTerminal(Checker.parseInt(terminalStr));
            WebAppContext.current().setGWProtocol(gwProtocol);
            WebAppContext.current().setGWAuthAppid(gwAuthAppid);

            String authData = httpServletRequest.getHeader("auth-data");
            String authData1 = httpServletRequest.getHeader("Auth-Data");
            String authData2 = httpServletRequest.getHeader("authdata");
            if (Checker.isNone(authData) && !Checker.isNone(authData1)){
                authData = authData1;
            }
            if (!Checker.isNone(authData2)){
                authData = authData2;
            }
            System.out.println("------------------------ AccessBehaviorInterceptor: ");
            System.out.println(String.format("authData: " + authData));
            logger.info("authData: " + authData);
            if (!Checker.isNone(authData)) {
                try {
                    JsonNode jsonNode = JsonSerializer.readToNode(authData);
                    if (jsonNode.get("userId") != null){
                        WebAppContext.current().setUserId(Checker.parseInt(jsonNode.get("userId").asText("0")));
                    }
                    if (jsonNode.get("openId") != null){
                        WebAppContext.current().setOpenId(Checker.getStringValue(jsonNode.get("openId").asText("")));
                    }
                    if (jsonNode.get("unionId") != null){
                        WebAppContext.current().setUnionId(Checker.getStringValue(jsonNode.get("unionId").asText("")));
                    }
                } catch (Exception e) {
                    logger.error("preHandle(authData): {}", e.getMessage(), e);
                    e.printStackTrace();
                }
            }

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

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