package com.happy.filter;

import com.alibaba.fastjson.JSONObject;
import com.happy.Model.Filter.Manage_map;
import com.happy.common.JwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@Component
public class TokenFilter implements Filter {

    Enumeration param;

    public TokenFilter() {
    }

    public void init(FilterConfig filterConfig) throws ServletException {
        this.param = filterConfig.getInitParameterNames();
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-type","text/html;charset=UTF-8");//向浏览器发送一个响应头，设置浏览器的解码方式为UTF-8
        // apipost中参数名Cookie，值_COOKIE_NAME=11111111
        String token = getRequestToken(request);
        String path = request.getRequestURI();
        //管理端需要拦截的路径
        if (Manage_map.isInterpreter(path)){
            if (token != null) {
                //验证token是否正确
                boolean result = JwtUtil.verify(token);
                if (result) {
                    chain.doFilter(request,response);
                } else {
                    JSONObject resultJson = new JSONObject();
                    resultJson.put("code", 402);
                    resultJson.put("message", "token错误");
                    OutputStream stream = servletResponse.getOutputStream();
                    stream.write(resultJson.toString().getBytes());
                }
            } else { //如果没有登录，则跳转到登录界面
                JSONObject resultJson = new JSONObject();
                resultJson.put("code", 401);
                resultJson.put("message", "token为空");
                OutputStream stream = servletResponse.getOutputStream();
                stream.write(resultJson.toString().getBytes());
                //chain.doFilter(request,response);
                /**
                 * 以下是为了登录成功后返回到刚刚的操作，不跳到主界面
                 * 实现：通过将请求URL保存到session的beforePath中，然后在登录时判断beforePath是否为空
                 */
            }
        } else {
            chain.doFilter(request,response);
        }
    }

    public void destroy() {
    }

    /**
     * 根据名字获取cookie
     *
     * @param request
     * @param name    cookie名字
     * @return
     */
    public static Cookie getCookieByName(HttpServletRequest request, String name) {
        Map<String, Cookie> cookieMap = ReadCookieMap(request);
        if (cookieMap.containsKey(name)) {
            Cookie cookie =  cookieMap.get(name);
            return cookie;
        } else {
            return null;
        }
    }
    /**
     * 将cookie封装到Map里面
     *
     * @param request
     * @return
     */
    private static Map<String, Cookie> ReadCookieMap(HttpServletRequest request) {
        Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                cookieMap.put(cookie.getName(), cookie);
            }
        }
        return cookieMap;
    }

    public static String getRequestToken(HttpServletRequest httpRequest){
        //从header中获取token
        String token = httpRequest.getHeader("token");
        //如果header中不存在token，则从参数中获取token
        if(StringUtils.isBlank(token)){
            token = httpRequest.getParameter("token");
        }
        return token;
    }

    /**
     * 返回信息给客户端
     *
     * @param response
     * @param out
     * @param apiResponse
     */
    private void responseMessage(HttpServletRequest request, HttpServletResponse response, PrintWriter out, String apiResponse) throws IOException {
        response.setContentType("application/json; charset=utf-8");
        out.print(JSONObject.toJSONString(apiResponse));
        out.flush();
        out.close();
    }

}
