package com.ywt.alipaympapi.web.interceptors;

import com.fasterxml.jackson.databind.JsonNode;
import com.ywt.alipaympapi.core.utils.Checker;
import com.ywt.alipaympapi.core.utils.JsonSerializer;
import com.ywt.alipaympapi.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.Map;
import java.util.UUID;

/**
 * 自定义拦截器
 * 由于支付宝 ab 模式下，web-mini 透传不支持请求头转发，所以无法从网关获取 userId 等信息。
 * 所以改成由前端在登录授权成功后，所有业务接口统一携带请求参数 userId, terminal & alipayUid 等，
 * 拦截器从请求参数获取这些值并全局存储。
 */
@Service("accessBehaviorInterceptor")
public class AccessBehaviorInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(AccessBehaviorInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) {
        try {
            int userId = 0;
            int terminal = 0;
            String alipayUid = "";
            Map<String, String[]> paramMap = httpServletRequest.getParameterMap();
            if (paramMap != null) {
                String[] sUid = paramMap.getOrDefault("userId", new String[]{"0"});
                String[] sTerminal = paramMap.getOrDefault("terminal", new String[]{"0"});
                String[] sAlipayUid = paramMap.getOrDefault("alipayUid", new String[]{""});
                if (sUid != null && sUid.length > 0) {
                    userId = Checker.parseInt(sUid[0]);
                }
                if (sTerminal != null && sTerminal.length > 0) {
                    terminal = Checker.parseInt(sTerminal[0]);
                }
                if (sAlipayUid != null && sAlipayUid.length > 0) {
                    alipayUid = Checker.getStringValue(sAlipayUid[0]);
                }
            }

            if (userId <= 0) {
                httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                httpServletResponse.getWriter().write("please login");
                return false;
            }

            WebAppContext.current().init();
            WebAppContext.current().setRequestStartTime(System.currentTimeMillis());
            WebAppContext.current().setRequestID(UUID.randomUUID().toString());
            WebAppContext.current().setTerminal(terminal);
            WebAppContext.current().setUserId(userId);
            WebAppContext.current().setAlipayUid(alipayUid);

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