package com.yutou.tools.utils;

import com.alibaba.fastjson.JSONArray;
import com.yutou.tools.mybatis.dao.PermissionDao;
import com.yutou.tools.mybatis.dao.UKeyDao;
import com.yutou.tools.mybatis.model.Permission;
import com.yutou.tools.mybatis.model.PermissionExample;
import com.yutou.tools.mybatis.model.UKey;
import com.yutou.tools.mybatis.model.UKeyExample;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
import java.util.List;

/*@Component
@WebFilter*/
public class APIFilter implements Filter {
    public static boolean isDebug = false;
    @Resource
    UKeyDao keyDao;
    @Resource
    PermissionDao permissionDao;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if(ConfigTools.load(ConfigTools.CONFIG, "model").equals("dev")){
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String token = request.getParameter("token");
        Cookie cookie = Tools.getCookie(request, "user");
        if(StringUtils.isEmpty(token)){
            token="PlVodzYhvxRQbOHKakpKs2dvnoc43Cnk";
        }
        System.out.println("接收到请求：" + request.getRequestURI() + " " + token);
        boolean isToken = false;
        boolean isCookie = false;
        if (!StringUtils.isEmpty(token)) {
            UKeyExample example = new UKeyExample();
            example.createCriteria().andKeyEqualTo(token);
            List<UKey> list = keyDao.selectByExample(example);
            if (list.size() > 0) {
                String url = null;
                String tmp = request.getRequestURI();
                try {
                    url = tmp.split(tmp.split("/")[tmp.split("/").length - 1])[0];
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("无权限请求:"+tmp);
                    return;
                }

                UKey key = list.get(0);
                JSONArray powers = JSONArray.parseArray(key.getPower());
                if(powers.toJavaList(String.class).contains("-1")){
                    isToken=true;
                }else {
                    PermissionExample pExample = new PermissionExample();
                    pExample.createCriteria().andUrlEqualTo(url);
                    List<Permission> permissions = permissionDao.selectByExample(pExample);
                    if (permissions != null && permissions.size() > 0) {
                        if (powers.toJavaList(String.class).contains(permissions.get(0).getId()+"")) {
                            isToken = true;
                        }
                    }
                }
            }
        }
        if (cookie != null) {
            if ("ok".equals(RedisTools.get(cookie.getValue()))) {
                isCookie = true;
            }
        }

        if (!isCookie && !isToken) {
            //response.sendRedirect("/");
            System.out.println("请求无令牌，拦截");
            if (!request.getRequestURI().contains("/login/") && !request.getRequestURI().equals("/favicon.ico")) {
                response.sendRedirect("/");
                return;
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
