package com.persagy.dmp.common.handler;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.persagy.dmp.common.context.AppContext;
import com.persagy.dmp.common.helper.SpringHelper;
import com.persagy.dmp.common.constant.CommonConstant;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

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

/**
 * 上下文 拦截器
 * @author Charlie Yu
 * @date 2021-06-25
 */
public class AppContextHandler extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 运维平台token认证
        if(StrUtil.isNotBlank(request.getHeader("token"))) {
            accessTokenInfo(request.getHeader("token"));
        } else if(StrUtil.isNotBlank(request.getParameter("groupCode"))) {
            // 请求参数中包含groupCode，由于没有标识位，暂时用这种方式判断吧
            accessRequestInfo(request);
        } else {
            // 其他情况，按现有系统默认不验证的逻辑，其他情况就是默认放行，不必处理。最好是抛401
        }
        return true;
    }

    /**
     * 根据token获取上下文信息
     * @param token
     */
    private void accessTokenInfo(String token){
        // 是否启用token拦截
        boolean enabled = SpringHelper.getBoolean("persagy.common.token.enabled", true);
        if(!enabled) {
            return;
        }
        // 从token中解析数据
//        SecureAES aes = new SecureAES("63499E35378AE1B0733E3FED7F780B68", "C0E7BD39B52A15C7");
        JSONObject tokenObj = new JSONObject();
//        try {
//            tokenObj = aes.decryptToken(token);
//        } catch (UnsupportedEncodingException e) {
//            throw new AESDecryptException("token解析异常");
//        }
        // 获取值
        String groupCode = tokenObj.getStr("groupCode");
        String appId = tokenObj.getStr("appId");
        String accountId = tokenObj.getStr("accountId");
        AppContext.getContext().setGroupCode(groupCode);
        AppContext.getContext().setAppId(appId);
        AppContext.getContext().setAccountId(accountId);
    }

    /**
     * 从请求参数中获取上下文
     * @param request
     */
    private void accessRequestInfo(HttpServletRequest request) {
        AppContext.getContext().setGroupCode(request.getParameter("groupCode"));
        AppContext.getContext().setProjectId(request.getParameter("projectId"));
        AppContext.getContext().setAppId(request.getParameter("appId"));
        String userId = request.getParameter("userId");
        // 无用户时，默认为默认系统用户
        if(StrUtil.isBlank(userId)) {
            userId = CommonConstant.DEFAULT_ID;
        }
        AppContext.getContext().setAccountId(userId);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        AppContext.unload();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AppContext.unload();
    }
}
