package com.cm.common.wechat.filter;

import com.alibaba.fastjson.JSON;
import com.cm.common.constants.ISystemConstant;
import com.cm.common.enums.AppTokenTypeEnum;
import com.cm.common.enums.ErrorResultCodeEnum;
import com.cm.common.exception.TokenException;
import com.cm.common.result.ErrorResult;
import com.cm.common.token.app.AppTokenManager;
import com.cm.common.token.app.entity.AppToken;
import com.cm.common.token.app.entity.AppTokenUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: MiniProgramFilter
 * @Description: 小程序过滤器
 * @Author: WangGeng
 * @Date: 2020/5/9 16:06
 * @Version: 1.0
 **/
public class WechatMiniAppFilter implements Filter {

    private static final Logger LOG = LoggerFactory.getLogger(WechatMiniAppFilter.class);
    private AntPathMatcher antPathMatcher;
    /**
     * 授权登录
     */
    private static final String WECHAT_MINI_APP_AUTH_LOGIN_URL = String.format("/**%s/auth/login**", ISystemConstant.WECHAT_MINI_APP_PREFIX);
    /**
     * 认证登录
     */
    private static final String WECHAT_MINI_APP_SIGN_LOGIN_URL = String.format("/**%s/sign/login**", ISystemConstant.WECHAT_MINI_APP_PREFIX);
    /**
     * 微信类放行
     */
    private static final String WECHAT_MINI_APP_RELEASE_URL = String.format("/**%s%s/**", ISystemConstant.WECHAT_MINI_APP_PREFIX, ISystemConstant.APP_RELEASE_SUFFIX);
    /**
     * 微信放行
     */
    private static final String WECHAT_API_MINI_APP_RELEASE_URL = String.format("/**%s/**/**%s/**", ISystemConstant.WECHAT_MINI_APP_PREFIX, ISystemConstant.APP_RELEASE_SUFFIX);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        antPathMatcher = new AntPathMatcher();
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestUri = request.getRequestURI();
        boolean isLogin = antPathMatcher.match(WECHAT_MINI_APP_AUTH_LOGIN_URL, requestUri) ||
                antPathMatcher.match(WECHAT_MINI_APP_SIGN_LOGIN_URL, requestUri);
        if (isLogin) {
            filterChain.doFilter(request, response);
            return;
        }

        boolean isRelease = antPathMatcher.match(WECHAT_MINI_APP_RELEASE_URL, requestUri) ||
                antPathMatcher.match(WECHAT_API_MINI_APP_RELEASE_URL, requestUri);
        if (isRelease) {
            filterChain.doFilter(request, response);
            return;
        }

        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            errorResponse(response, "token不能为空");
            return;
        }
        LOG.debug("校验token");
        try {
            checkToken(token);
        } catch (TokenException e) {
            errorResponse(response, e.getMessage());
            return;
        }
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }

    private void checkToken(String token) throws TokenException {
        AppTokenManager appTokenManager = AppTokenManager.getInstance();
        LOG.debug("检查token是否存在");
        AppToken appToken = appTokenManager.getToken(token);
        if (appToken != null) {
            return;
        }
        LOG.debug("解析token是否合法");
        AppTokenUser appTokenUser = appTokenManager.parseToAppTokenUser(token);
        appTokenManager.addToken(token, AppTokenTypeEnum.WECHAT_MINI_APP, appTokenUser);
    }

    /**
     * 错误返回
     *
     * @param response
     * @param errorInfo
     * @throws IOException
     */
    private void errorResponse(HttpServletResponse response, String errorInfo) throws IOException {
        response.setStatus(HttpStatus.BAD_REQUEST.value());
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        ErrorResult result = new ErrorResult(ErrorResultCodeEnum.PARAMS_ERROR.getValue(), errorInfo);
        response.getWriter().write(JSON.toJSONString(result));
    }

}
