package com.neusoft.smart.pos.gateway.filters;

import com.google.gson.Gson;
import com.netflix.zuul.context.RequestContext;
import com.neusoft.smart.pos.framework.dto.ResponseData;
import com.neusoft.smart.pos.gateway.constants.SecurityConstant;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

// import com.neusoft.smart.pos.dto.user.Permission;
// import org.springframework.security.access.AccessDeniedException;

@Component
public class JwtFilter extends OncePerRequestFilter {

//    @Autowired
//    RemoteUserService remoteUserService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String authorizationHeader = request.getHeader(SecurityConstant.AUTHORIZATION_HEADER);
        if (!org.springframework.util.StringUtils.isEmpty(authorizationHeader)) {
            if (org.springframework.util.StringUtils.startsWithIgnoreCase(authorizationHeader, SecurityConstant.BEARER_PREFIX)) {
                String token = org.springframework.util.StringUtils.delete(authorizationHeader, SecurityConstant.BEARER_PREFIX);
                final RequestContext ctx = RequestContext.getCurrentContext();
                try {
                    Claims claims = Jwts.parser()
                            .setSigningKey(SecurityConstant.SECRET_KEY)
                            .parseClaimsJws(token)
                            .getBody();
                    final String username = claims.getSubject();
                    final HttpSession session = request.getSession();
                    session.setAttribute("x-auth-username", username);
                    ctx.addZuulRequestHeader("x-auth-username", username);

                    // boolean permissionNoneMatch = remoteUserService.getPermissions(username).stream().map(Permission::getUrl)
                    //         .noneMatch(permission -> permission.equals(request.getMethod() + "::" + request.getRequestURI()));
                    // if (permissionNoneMatch) {
                    //     throw new AccessDeniedException("无权访问该接口");
                    // }
                } catch (ExpiredJwtException e) {
                    final String json = new Gson().toJson(new ResponseData("500", "令牌已过期"));
                    final PrintWriter writer = response.getWriter();
                    writer.write(json);
                    writer.close();
                    return;
                }
            }
        } else {
            final Map<String, String> zuulRequestHeaders = RequestContext.getCurrentContext().getZuulRequestHeaders();
            if (zuulRequestHeaders.containsKey("x-auth-username")) {
                zuulRequestHeaders.remove("x-auth-username");
            }
        } // else if ((request.getRequestURI().equals("/service-user/login") && request.getMethod().equals("POST")) ||
        //         (request.getRequestURI().equals("/service-user/login/captcha") && request.getMethod().equals("GET")) ||
        //         (request.getRequestURI().equals("/unionService/register") && request.getMethod().equals("POST"))) {
        //     filterChain.doFilter(request, response);
        //     return;
        // } else {
        //     throw new AccessDeniedException("无权访问该接口");
        // }
        filterChain.doFilter(request, response);
    }
}
