package com.fdkankan.web.jwt;

import com.alibaba.fastjson.JSON;
import com.fdkankan.common.exception.BusinessException;
import com.fdkankan.web.response.ResultData;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

public class JwtFilter extends BasicHttpAuthenticationFilter {
    private static Logger log = LoggerFactory.getLogger("programLog");

    private String loginType;

    public JwtFilter(String loginType){
        this.loginType = loginType;
    }

    /**
     * 执行登录认证
     *
     * @param request
     * @param response
     * @param mappedValue
     * @return
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        try {
            log.info("Step 1: 接口拦截shiro认证权限");
            executeLogin(request, response);
            String url = ((HttpServletRequest) request).getRequestURI();
//            getSubject(request, response).checkPermission(url);
            return true;
        } catch (Exception e) {
            // 认证出现异常，传递错误信息msg
            String msg = e.getMessage();
            // 获取应用异常(该Cause是导致抛出此throwable(异常)的throwable(异常))
            Throwable throwable = e.getCause();
            ResultData resultData = ResultData.error(3002, msg);
            if (throwable instanceof BusinessException) {
                resultData.setCode(((BusinessException) throwable).getCode());
                resultData.setMessage(((BusinessException)throwable).getMessage());
            }
            // 直接返回Response信息
            this.response(response, resultData);
            return false;
        }
    }

    /**
     *
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = httpServletRequest.getHeader("token");

        JwtToken jwtToken = new JwtToken(token, loginType);
        // 提交给realm进行登入，如果错误他会抛出异常并被捕获
        getSubject(request, response).login(jwtToken);
        // 如果没有抛出异常则代表登入成功，返回true
        return true;
    }

    /**
     * 对跨域提供支持
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    /**
     * 无需转发，直接返回Response信息
     */
    private void response(ServletResponse response, ResultData resultData) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.append(JSON.toJSONString(resultData));
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null){
                out.close();
            }
        }
    }

}
