package beilv.framework.shiro.web.filter.wxMiniAppAccessControlFilter;

import beilv.common.utils.rsa.RsaUtil;
import beilv.system.domain.SysMember;
import beilv.system.mapper.SysMemberMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class WxMiniAppAccessControlFilter extends AccessControlFilter {

    @Value("${rsa.privateKey}")
    private String privateKey;
    private final SysMemberMapper sysMemberMapper;

    public WxMiniAppAccessControlFilter(SysMemberMapper sysMemberMapper) {
        this.sysMemberMapper = sysMemberMapper;
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        response.setContentType("application/json; charset=UTF-8"); // 设置内容类型和字符编码
        response.setCharacterEncoding("UTF-8"); // 设置字符编码
        // 这里可以添加你的自定义验证逻辑
        String token = httpRequest.getHeader("accessToken");
        // 验证 token，返回 true 表示允许访问
        if (null == token || isValidToken(token)) {
            response.getWriter().write("{\"message\": \"用户不存在!\"}");
            return false;
        } else {
            return true;
        }
    }


    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        // 设置未授权的响应状态
        httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return false; // 拒绝访问
    }

    private boolean isValidToken(String token) {
        // 在这里实现你的 token 验证逻辑
        String str;
        try {
            str = RsaUtil.decrypt(token, privateKey);
            //根据userId从数据库中查询用户信息，判断用户是否存在，如果不存在，则返回false，表示拒绝访问；如果存在，则返回true，表示放行访问
            SysMember sysMember = sysMemberMapper.selectSysMemberById(Long.parseLong(str));
            return ObjectUtils.isEmpty(sysMember);
        } catch (Exception e) {
            e.printStackTrace();
            return true;
        }
    }

}
