package com.nmgs.config;

/**
 * 允许跨域请求
 *
 * @author Administrator
 */

import com.alibaba.fastjson.JSONObject;
import com.nmgs.util.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

@Component
@Slf4j
public class FilterConfig implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(request.getHeader("Origin")==null){
            System.out.println("request.getHeader(\"Origin\")=======>为空");
            response.setHeader("Access-Control-Allow-Origin", "*");//支持跨域请求
        }else{
            System.out.println("request.getHeader(\"Origin\")=======>" + request.getHeader("Origin"));
            response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));//支持跨域请求
        }
        response.setHeader("Access-Control-Allow-Credentials", "true");//是否支持cookie跨域
        response.setHeader("Access-Control-Allow-Methods", "*");//X-forwared-port,X-forwarded-host,
        response.setHeader("Access-Control-Allow-Headers", "Authorization,Origin, X-Requested-With, Content-Type, Accept,Access-Token");//Origin, X-Requested-With, Content-Type, Accept,Access-Token
        response.setHeader("Set-Cookie", "SameSite=None");
        Map<String, String[]> parameterMap = request.getParameterMap();
        String token = request.getHeader("token");
        if(token == null){
            return true;
        }
        if (token.equals("test")) {
            return true;
        }
        if (token != null) {
            boolean result = TokenUtil.verify(token,request);
            //判断绑定
            if (result) {
                log.info("通过拦截器");
                return true;
            }
        }

        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        JSONObject res = new JSONObject();
        res.put("status", "-1");
        res.put("msg", "鉴权失败");
        PrintWriter out = null;
        out = response.getWriter();
        out.write(res.toString());
        out.flush();
        out.close();
        return false;

    }
}