package com.zhongzheng.framework.security.filter;

import cn.hutool.core.lang.Validator;
import cn.hutool.http.HttpStatus;
import com.zhongzheng.common.core.domain.AjaxResult;
import com.zhongzheng.common.core.domain.model.TopLoginUser;
import com.zhongzheng.common.exception.CustomException;
import com.zhongzheng.common.utils.ServletUtils;
import com.zhongzheng.common.utils.ip.IpUtils;
import com.zhongzheng.framework.web.service.TopTokenService;
import com.zhongzheng.modules.user.entity.ClientLoginUser;
import com.zhongzheng.common.core.domain.model.LoginUser;
import com.zhongzheng.common.utils.SecurityUtils;
import com.zhongzheng.framework.web.service.TokenService;
import com.zhongzheng.framework.web.service.WxTokenService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

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

/**
 * token过滤器 验证token有效性
 *
 * @author zhongzheng
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter
{
    @Autowired
    private TokenService tokenService;

    @Autowired
    private WxTokenService wxTokenService;

    @Autowired
    private TopTokenService topTokenService;

    @Value("${mybatis-plus.tenant.enabled-tenant:true}")
    private boolean enabledTenant;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException
    {
        try{
            String wxToken = wxTokenService.getToken(request);

            if(StringUtils.isNoneEmpty(wxToken)){
                ClientLoginUser clientLoginUser = wxTokenService.getLoginUser(request);
                if(clientLoginUser!=null){
                    wxTokenService.verifyToken(clientLoginUser);
                    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(clientLoginUser, null,null);
                    authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                }
            }else{
                if(!enabledTenant){
                    //SAAS管理员
                    TopLoginUser top_loginUser = topTokenService.getLoginUser(request);
                    if (Validator.isNotNull(top_loginUser) && Validator.isNull(SecurityUtils.getAuthentication()))
                    {
                        topTokenService.verifyToken(top_loginUser);
                        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(top_loginUser, null, top_loginUser.getAuthorities());
                        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                    }
                }else{
                        //子系统
                    LoginUser loginUser = null;

                       loginUser = tokenService.getLoginUser(request);

                    if (Validator.isNotNull(loginUser) && Validator.isNull(SecurityUtils.getAuthentication()))
                    {
                        tokenService.verifyToken(loginUser);
                        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
                        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                    }
                }

            }
        }catch (Exception e){
            request.getRequestDispatcher("/filter/token_auth_fail").forward(request, response);
        }
        chain.doFilter(request, response);
    }
}
