package com.icloud.server.web.shiro.config;

import com.alibaba.fastjson.JSONObject;
import com.icloud.server.utils.CodeDefs;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Set;

/**
 * 自定义filter
 */
public class CustomRolesOrAuthorizationFilter extends AuthorizationFilter {


    @SuppressWarnings({"unchecked"})
    public boolean isAccessAllowed1(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {
//
        Subject subject = getSubject(request, response);

        //获取当前访问路径所需要的角色集合
        String[] rolesArray = (String[]) mappedValue;
//        if ((((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name()))){
//            setHeader((HttpServletRequest) request, (HttpServletResponse) response);
//            return true;
//        }
//        if (((HttpServletRequest) request).getMethod().toUpperCase().equals("OPTIONS")) {
//            return true;
//        }
//        if ("OPTIONS".equals(((HttpServletRequest)request).getMethod())){
//            ((HttpServletResponse)response).setStatus(org.apache.http.HttpStatus.SC_NO_CONTENT);;
//            setHeader((HttpServletRequest)request,(HttpServletResponse)response);
//            System.out.println("OPTIONS 放行");
//            return true;
//        }

        //没有角色限制，可以直接访问
        if (rolesArray == null || rolesArray.length == 0) {
            //no roles specified, so nothing to check - allow access.
            return true;
        }else {

        }


        Set<String> roles = CollectionUtils.asSet(rolesArray);

        //当前subject是roles 中的任意一个，则有权限访问
        for(String role : roles){
            if(subject.hasRole(role)){
                return true;
            }
        }
        return false;
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws UnauthorizedException {
        //判断请求的请求头是否带上 "Token"
        if (isLoginAttempt(request, response)) {
            return true;
        }else{
            return checkToken(request, response);
        }
        //如果请求头不存在 Token，则可能是执行登陆操作或者是游客状态访问，无需检查 token，直接返回 true
    }
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        HttpServletRequest req = (HttpServletRequest) request;
        String token = req.getHeader("token");
        return token != null;
    }











    private boolean checkToken(ServletRequest request, ServletResponse response) {
        // 没有携带Token
        HttpServletRequest httpRequest = (HttpServletRequest)request;
        String httpMethod = httpRequest.getMethod();
        String requestURI = httpRequest.getRequestURI();
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try  {
            out = httpServletResponse.getWriter();
            JSONObject object = new JSONObject();
            object.put("code", CodeDefs.ERROR_REQUEST);
            object.put("message","您无权限");
            out.print(object.toJSONString());
            out.flush();;
        } catch (IOException e) {
            //logger.error("直接返回Response信息出现IOException异常", e);
        }finally {
            if(out!=null){
                out.close();
            }
        }
        return false;
    }

//-------
    private void setHeader(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("===========setHeader=========");
        //request.getHeader("Origin")
        response.setHeader("Access-Control-Allow-Origin","*" );
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods","POST,PUT,GET,OPTIONS,DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "content-type,x-requested-with,token,Authorization,authorization");
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        response.setStatus(HttpStatus.OK.value());
    }

//    @Override
//    protected boolean onAccessDenied(ServletRequest request, ServletResponse response)  {
//        // 错误异常提示
//        HttpServletResponse httpResponse = (HttpServletResponse) response;
//        HttpServletRequest httpRequest = (HttpServletRequest) request;
//        setHeader(httpRequest,httpResponse);
//        httpResponse.setCharacterEncoding("UTF-8");
//        httpResponse.setContentType("application/json");
//        return false;
//    }







  
}
