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

import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.springframework.http.HttpStatus;

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

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


    @Override
    @SuppressWarnings({"unchecked"})
    public boolean isAccessAllowed(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;
        }


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

        //当前subject是roles 中的任意一个，则有权限访问
        for(String role : roles){
            if(subject.hasRole(role)){
                return true;
            }
        }
        return false;
    }
//    @Override
//    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
//        WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
//        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;
    }
//-------
//    /**
//     * 为response设置header，实现跨域
//     */
//    private void setHeader(HttpServletRequest request,HttpServletResponse response){
//        //跨域的header设置
//        response.setHeader("Access-control-Allow-Origin", request.getHeader("Origin"));
//        response.setHeader("Access-Control-Allow-Methods", request.getMethod());
//        response.setHeader("Access-Control-Allow-Credentials", "true");
//        response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));
//        //防止乱码，适用于传输JSON数据
//        //Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild
//        response.setHeader("Content-Type","application/json;charset=UTF-8");
//        response.setStatus(HttpStatus.OK.value());
//    }


//    @Override
//    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
//        HttpServletResponse res = (HttpServletResponse)response;
//        res.setHeader("Access-Control-Allow-Origin", "*");
//        res.setStatus(HttpServletResponse.SC_OK);
//        res.setCharacterEncoding("UTF-8");
//        PrintWriter writer = res.getWriter();
//        Map<String, Object> map= new HashMap<>();
//        map.put("code", 702);
//        map.put("msg", "未登录");
//        writer.write(JSON.toJSONString(map));
//        writer.close();
//        return false;
//    }
  
}
