package com.fr.plugin;

import com.fr.decision.authority.data.User;
import com.fr.decision.fun.impl.AbstractGlobalRequestFilterProvider;
import com.fr.decision.webservice.utils.DecisionServiceConstants;
import com.fr.decision.webservice.v10.login.LoginService;
import com.fr.decision.webservice.v10.user.UserService;
import com.fr.log.FineLoggerFactory;
import com.fr.report.core.utils.WebUnit;
import com.fr.stable.StringUtils;
import com.fr.web.utils.WebUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Base64;

public class MyGlobalRequestFilter extends AbstractGlobalRequestFilterProvider {

    @Override
    public String filterName() {
        return "everyThing";
    }

    @Override
    public String[] urlPatterns() {
        return new String[]{
                "/decision/*"
        };
    }

    @Override
    public void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain filterChain) {
        try {
           if (!isLogin(req)){
              String my_token = req.getParameter("my_token");
              if (StringUtils.isNotBlank(my_token)){
                  try {
                      String userName = new String(Base64.getUrlDecoder().decode(my_token));
                      User user = UserService.getInstance().getUserByUserName(userName);
                      if (user!=null){
                          String token = LoginService.getInstance().login(req,res,userName);
                          req.setAttribute(DecisionServiceConstants.FINE_AUTH_TOKEN_NAME,token);
                      }else {
                          FineLoggerFactory.getLogger().error("用户不存在。。。", userName);
                          WebUtils.printAsString(res,"登录用户"+userName+"不存在！");
                          return;
                      }
                  } catch (Exception e) {
                   //登录过程中出现异常
                   FineLoggerFactory.getLogger().error("登录过程发生异常。。。", e);
               }
              }
           }
           //filterChain含义：交给下一个拦截器去处理，若没有下一个拦截器，则交给真正的servlet或接口去处理
           filterChain.doFilter(req,res);
        } catch (IOException e) {
           e.printStackTrace();
        } catch (ServletException e){
            e.printStackTrace();
        }
    }

    private  boolean isLogin(HttpServletRequest request){
        return LoginService.getInstance().isLogged(request);
    }
}
