package com.usoftchina.bi.auth.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.usoftchina.bi.auth.annotation.Auth;
import com.usoftchina.bi.core.base.RepCode;
import com.usoftchina.bi.core.base.RepEntity;
import com.usoftchina.bi.core.base.RoleConstant;
import com.usoftchina.bi.core.utils.GetTokenDataUtil;
import com.usoftchina.bi.core.utils.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
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.io.PrintWriter;
import java.util.Map;

@Component
public class SecurityInterceptor implements HandlerInterceptor {

    @Autowired
    ObjectMapper objectMapper;

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

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            logger.error("can't cast handler to HandlerMethod.class");
            return true;
        }
        // 获取注解
        Auth auth = ((HandlerMethod) handler).getMethod().getAnnotation(Auth.class);
        if (auth == null) {
            logger.error("can't find @Auth in this uri:{}", request.getRequestURI());
            return true;
        }
        // 从参数中取出用户身份并验证
        String admin = auth.user();
        String token = request.getHeader("token");
        Map<String, String> resultMap = GetTokenDataUtil.getTokenData(token);
        logger.info("authRole={},userRole={}", admin, resultMap.get("role"));
        //超级管理员跳过认证
        if (RoleConstant.SUPER_ADMIN.getRole().equals(resultMap.get("role"))) {
            return true;
        }
        if (!admin.equals(resultMap.get("role"))) {
            returnErrorMessage(request, response, RepCode.NoAuthority);
            return false;
        }
        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 {

    }

    /**
     * 错误信息处理
     * @param request
     * @param response
     * @param repCode
     * @throws IOException
     */
    private void returnErrorMessage(HttpServletRequest request, HttpServletResponse response, RepCode repCode) throws IOException {
        //跨域处理
        response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET");
        response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "POST");
        response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "OPTIONS");
        response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
        response.setHeader(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "3600");

        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();
        writer.print(JsonUtils.toJsonString(new RepEntity(repCode)));
        writer.flush();
        writer.close();
    }
}
