package ink.wgink.app.filter;

import com.alibaba.fastjson.JSON;
import ink.wgink.app.AppTokenManager;
import ink.wgink.exceptions.TokenException;
import ink.wgink.pojo.app.AppToken;
import ink.wgink.pojo.app.AppTokenUser;
import ink.wgink.pojo.result.ErrorResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
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: AppTokenFilter
 * @Description: App过滤器
 * @Author: wanggeng
 * @Date: 2021/3/1 4:43 下午
 * @Version: 1.0
 */
@Component
public class AppTokenFilter extends GenericFilterBean implements InitializingBean {

    private static final Logger LOG = LoggerFactory.getLogger(AppTokenFilter.class);
    private AntPathMatcher antPathMatcher = new AntPathMatcher();
    /**
     * APP登录（用户名密码）
     */
    private static final String URL_LOGIN_DEFAULT = "/**/app/sign/default";
    /**
     * APP登录（手机验证码）
     */
    private static final String URL_LOGIN_PHONE = "/**/app/sign/phone";
    /**
     * APP注册
     */
    private static final String URL_REGISTER = "/**/app/register/**";
    /**
     * APP获取验证码
     */
    private static final String URL_VERIFY_CODE = "/**/app/sms/verify-code/**";
    /**
     * APP忘记密码
     */
    private static final String URL_FORGET_PASSWORD = "/**/app/user/forget-phone-password";
    /**
     * 下载头像
     */
    private static final String URL_DOWNLOAD_AVATAR = "/**/app/user/downloadavatar/**";
    /**
     * APP版本号
     */
    private static final String URL_APP_VERSION = "/**/app/appversion/**";
    /**
     * APP放行
     */
    private static final String URL_RELEASE_APP = "/**/app/**/**release/**";
    /**
     * APP路由放行
     */
    private static final String URL_RELEASE_APP_ROUTE = "/**/approute/**/**release/**";
    /**
     * APP回调
     */
    private static final String URL_CALLBACK_APP = "/**/app/**/**callback/**";
    private static final String URP_FILE_CENTER = "/**/app/file-center/**";

    @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();
        // 非app 放行
        boolean appMatcher = antPathMatcher.match("/**/app/**", requestUri);
        boolean appRouteMatcher = antPathMatcher.match("/**/approute/**", requestUri);
        if (!appMatcher && !appRouteMatcher) {
            filterChain.doFilter(request, response);
            return;
        }
        boolean matcher = antPathMatcher.match(URL_LOGIN_DEFAULT, requestUri)
                || antPathMatcher.match(URL_LOGIN_PHONE, requestUri)
                || antPathMatcher.match(URL_REGISTER, requestUri)
                || antPathMatcher.match(URL_VERIFY_CODE, requestUri)
                || antPathMatcher.match(URL_FORGET_PASSWORD, requestUri)
                || antPathMatcher.match(URL_DOWNLOAD_AVATAR, requestUri)
                || antPathMatcher.match(URL_APP_VERSION, requestUri)
                || antPathMatcher.match(URL_RELEASE_APP, requestUri)
                || antPathMatcher.match(URL_RELEASE_APP_ROUTE, requestUri)
                || antPathMatcher.match(URL_CALLBACK_APP, requestUri)
                || antPathMatcher.match(URP_FILE_CENTER, requestUri);
        if (matcher) {
            filterChain.doFilter(request, response);
            return;
        }
        // 判断header中的token
        String token = getToken(request);
        if (StringUtils.isBlank(token)) {
            errorResponse(response, "token不能为空");
            return;
        }
        LOG.debug("校验token");
        try {
            checkToken(token);
        } catch (TokenException e) {
            errorResponse(response, e.getMessage());
            return;
        }
        filterChain.doFilter(request, response);
    }

    /**
     * 获取token，先校验 header 中的 token, 没有校验参数中是否有token
     *
     * @param request
     * @return
     */
    private String getToken(HttpServletRequest request) {
        String headerToken = request.getHeader("token");
        if (!StringUtils.isBlank(headerToken)) {
            return headerToken;
        }
        String queryToken = request.getParameter("token");
        if (!StringUtils.isBlank(queryToken)) {
            return queryToken;
        }
        return null;
    }

    /**
     * 校验token
     *
     * @param token
     * @return
     * @throws TokenException
     */
    private void checkToken(String token) throws TokenException {
        AppTokenManager appTokenManager = AppTokenManager.getInstance();
        AppToken appToken = appTokenManager.getToken(token);
        if (appToken != null) {
            return;
        }
        AppTokenUser appTokenUser = appTokenManager.parseToAppTokenUser(token);
        appTokenManager.addToken(token, AppToken.AppTokenTypeEnum.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(ErrorResult.ErrorResultCodeEnum.PARAMS_ERROR.getValue(), errorInfo);
        response.getWriter().write(JSON.toJSONString(result));
    }

}
