package com.ruoyi.framework.security.filter;

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

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.ruoyi.buyerapi.domain.BuyerCompanyInfo;
import com.ruoyi.buyerapi.service.IBuyerCompanyInfoService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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 com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;

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

    @Autowired
    private IBuyerCompanyInfoService buyerCompanyInfoService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication()))
        {
            tokenService.verifyToken(loginUser);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);

            // 平台用户跟据company_id判断当前会员是否有效
            String uri = request.getRequestURI();
            if(null != loginUser
                    && StrUtil.isNotEmpty(loginUser.getUser().getCompanyId())
                    && !uri.startsWith("/buyer/member")
                    && !uri.startsWith("/buyer/profile")
                    && !uri.startsWith("/system/dict")
                    && !uri.startsWith("/home")
                    && !uri.startsWith("/quick")
                    && !uri.startsWith("/buyer/record")
                    && !uri.startsWith("/buyer/goods")
                    && !uri.startsWith("/buyer/policy")
                    && !uri.startsWith("/buyer/help")
                    && !uri.startsWith("/logout")){
                // 获取企业信息是否过期或者被停用
                BuyerCompanyInfo companyInfo = buyerCompanyInfoService.selectBuyerCompanyInfoById(loginUser.getUser().getCompanyId());
                if(null != companyInfo && null != companyInfo.getIsExpire() &&
                        ("1".equals(companyInfo.getIsExpire()) || "1".equals(companyInfo.getAccountStatus()))){
                    ServletOutputStream outputStream = response.getOutputStream();
                    //自定义返回对象，可自行设置
                    R result = null;
                    if("1".equals(companyInfo.getIsExpire())){
                        result = R.fail(500, "会员过期或者未购买会员，请购买后重新登录再试！");
                    }else if("1".equals(companyInfo.getAccountStatus())){
                        result = R.fail(500, "当前会员已被停用请联系管理员！");
                    }
                    JSON parse = JSONUtil.parse(result);
                    outputStream.write(parse.toString().getBytes());
                    outputStream.flush();
                    return;
                }
            }
        }
        chain.doFilter(request, response);
    }
}
