package com.cm.common.filter;

import com.alibaba.fastjson.JSON;
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.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.util.AntPathMatcher;

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: AppFilter
 * @Description: app过滤器
 * @Author: WangGeng
 * @Date: 2019-08-01 13:59
 * @Version: 1.0
 **/
public class AppFilter implements Filter {

    private static final Logger LOG = LoggerFactory.getLogger(AppFilter.class);
    private AntPathMatcher antPathMatcher;
    /**
     * APP登录（用户名密码）
     */
    private static final String URL_LOGIN_DEFAULT = "/**/app/sign/login";
    /**
     * APP登录（手机验证码）
     */
    private static final String URL_LOGIN_PHONE = "/**/app/sign/loginphone";
    /**
     * APP注册
     */
    private static final String URL_REGISTER = "/**/app/register/saveregisteruser";
    /**
     * APP注册简单
     */
    private static final String URL_REGISTER_SIMPLE = "/**/app/register/saveregisterusersimple";
    /**
     * APP忘记密码
     */
    private static final String URL_FORGET_PASSWORD = "/**/app/user/forgetpassword";
    /**
     * 下载头像
     */
    private static final String URL_DOWNLOAD_AVATAR = "/**/app/user/downloadavatar/**";
    /**
     * APP下载
     */
    private static final String URL_DOWNLOAD_APP = "/**/app/appversion/downloadapp/**";
    /**
     * APP版本号
     */
    private static final String URL_APP_VERSION_NUM = "/**/app/appversion/getappversionnumber/**";
    /**
     * APP放行
     */
    private static final String URL_RELEASE_APP = "/**/app/**/**release/**";
    /**
     * APP路由放行
     */
    private static final String URL_RELEASE_APP_ROUTE = "/**/approute/**/**release/**";


    @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 matcher = antPathMatcher.match(URL_LOGIN_DEFAULT, requestUri)
                || antPathMatcher.match(URL_LOGIN_PHONE, requestUri)
                || antPathMatcher.match(URL_REGISTER, requestUri)
                || antPathMatcher.match(URL_REGISTER_SIMPLE, requestUri)
                || antPathMatcher.match(URL_FORGET_PASSWORD, requestUri)
                || antPathMatcher.match(URL_DOWNLOAD_AVATAR, requestUri)
                || antPathMatcher.match(URL_DOWNLOAD_APP, requestUri)
                || antPathMatcher.match(URL_APP_VERSION_NUM, requestUri)
                || antPathMatcher.match(URL_RELEASE_APP, requestUri)
                || antPathMatcher.match(URL_RELEASE_APP_ROUTE, requestUri);
        if (matcher) {
            filterChain.doFilter(request, response);
            return;
        }
        String token = request.getHeader("token");
        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);
    }

    @Override
    public void destroy() {

    }

    /**
     * 校验token
     *
     * @param token
     * @return
     * @throws TokenException
     */
    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.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));
    }

}
