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 com.cm.common.wechat.config.pojo.WechatOfficialAccountProperties;
import com.cm.common.wechat.manager.officialaccount.WechatOfficialAccountManager;
import org.apache.shiro.crypto.hash.SimpleHash;
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;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: WechatFilter
 * @Description: 微信过滤器
 * @Author: WangGeng
 * @Date: 2020/3/1 11:25 上午
 * @Version: 1.0
 **/
public class WechatFilter implements Filter {

    private static final Logger LOG = LoggerFactory.getLogger(WechatFilter.class);
    private WechatOfficialAccountProperties wechatOfficialAccountProperties;
    private AntPathMatcher antPathMatcher;

    private static final String WECHAT_LOGIN_URL = String.format("/**%s/sign/login**", ISystemConstant.WECHAT_PREFIX);
    /**
     * 微信类放行
     */
    private static final String WECHAT_RELEASE_URL = String.format("/**%s%s/**", ISystemConstant.WECHAT_PREFIX, ISystemConstant.RELEASE_SUFFIX);
    /**
     * 微信放行
     */
    private static final String WECHAT_API_RELEASE_URL = String.format("/**%s/**/**%s/**", ISystemConstant.WECHAT_PREFIX, ISystemConstant.RELEASE_SUFFIX);
    /**
     * 微信路由放行
     */
    private static final String WECHAT_ROUTE_RELEASE_URL = String.format("/**%s/**/**%s/**", ISystemConstant.WECHAT_ROUTE_PREFIX, ISystemConstant.RELEASE_SUFFIX);
    /**
     * 微信路由静态资源
     */
    private static final String WECHAT_ROUTE_STATIC_URL = String.format("/**%s/static/**", ISystemConstant.WECHAT_ROUTE_PREFIX);
    private static final String WECHAT_ROUTE_CSS_URL = String.format("/**%s/css/**", ISystemConstant.WECHAT_ROUTE_PREFIX);
    private static final String WECHAT_ROUTE_JS_URL = String.format("/**%s/js/**", ISystemConstant.WECHAT_ROUTE_PREFIX);
    private static final String WECHAT_ROUTE_IMAGES_URL = String.format("/**%s/images/**", ISystemConstant.WECHAT_ROUTE_PREFIX);
    /**
     * 上传文件
     */
    private static final String WECHAT_ROUTE_HYBRID_URL = "/**/wechatroute/hybrid/**";

    @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;

        if (wechatOfficialAccountProperties.getApiCrossOrigin() != null && wechatOfficialAccountProperties.getApiCrossOrigin()) {
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Credentials", "true");
        }

        String requestUri = request.getRequestURI();
        boolean isRelease = antPathMatcher.match(WECHAT_LOGIN_URL, requestUri)
                || antPathMatcher.match(WECHAT_RELEASE_URL, requestUri)
                || antPathMatcher.match(WECHAT_API_RELEASE_URL, requestUri)
                || antPathMatcher.match(WECHAT_ROUTE_RELEASE_URL, requestUri)
                || antPathMatcher.match(WECHAT_ROUTE_STATIC_URL, requestUri)
                || antPathMatcher.match(WECHAT_ROUTE_HYBRID_URL, requestUri)
                || antPathMatcher.match(WECHAT_ROUTE_CSS_URL, requestUri)
                || antPathMatcher.match(WECHAT_ROUTE_JS_URL, requestUri)
                || antPathMatcher.match(WECHAT_ROUTE_IMAGES_URL, requestUri);
        if (isRelease) {
            filterChain.doFilter(request, response);
            return;
        }

        // 如果header存在token则校验token，如果没有就校验session
        String token = request.getHeader("token");
        if (!StringUtils.isEmpty(token)) {
            tokenFilter(token, request, response, filterChain);
            return;
        }

        // 公众号激活有效
        if (wechatOfficialAccountProperties.getActivate() != null && wechatOfficialAccountProperties.getActivate()) {
            wechatOfficialAccountFilter(request, response, filterChain);
            return;
        }

        errorResponse(response, "token不能为空");
    }

    @Override
    public void destroy() {

    }

    private void tokenFilter(String token, HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        try {
            checkToken(token);
        } catch (TokenException e) {
            errorResponse(response, e.getMessage());
            return;
        }
        filterChain.doFilter(request, response);
    }

    /**
     * 微信公众号自动授权
     *
     * @param request
     * @param response
     */
    private void wechatOfficialAccountFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        // 判断是不是微信配置校验
        String signatureParameter = request.getParameter("signature");
        String timestampParameter = request.getParameter("timestamp");
        String nonceParameter = request.getParameter("nonce");
        String echostrParameter = request.getParameter("echostr");
        boolean isWechatConfig = !StringUtils.isEmpty(signatureParameter)
                && !StringUtils.isEmpty(timestampParameter)
                && !StringUtils.isEmpty(nonceParameter)
                && !StringUtils.isEmpty(echostrParameter);
        if (isWechatConfig && isWechatOfficialAccountConfigRequest(signatureParameter, timestampParameter, nonceParameter, echostrParameter)) {
            Writer writer = response.getWriter();
            writer.write(echostrParameter);
            writer.flush();
            writer.close();
            return;
        }

        // 判断session是否存在
        Object accessToken = request.getSession().getAttribute(ISystemConstant.SESSION_WECHAT_ACCESS_TOKEN);
        if (!StringUtils.isEmpty(accessToken)) {
            filterChain.doFilter(request, response);
            return;
        }
        // session不存在
        // 绑定校验
        // 如果参数都存在，标识从服务器重定向回页面，获取AccessToken后放行
        String codeParameter = request.getParameter("code");
        String stateParameter = request.getParameter("state");
        if (!StringUtils.isEmpty(codeParameter) && !StringUtils.isEmpty(stateParameter)) {
            try {
                WechatOfficialAccountManager.getInstance().setUserAccessToken(codeParameter, stateParameter, request.getSession());
            } catch (Exception e) {
                LOG.error(e.getMessage(), e);
                response.setStatus(404);
            }
            filterChain.doFilter(request, response);
            return;
        }
        // session 不存在重定向登录
        response.sendRedirect(WechatOfficialAccountManager.getInstance().getAuthorizeUrl(request.getRequestURL().toString()));
    }

    /**
     * 校验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.WECHAT, appTokenUser);
    }

    /**
     * 是来自微信的配置请求
     *
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @return
     */
    private boolean isWechatOfficialAccountConfigRequest(String signature, String timestamp, String nonce, String echostr) {
        List<String> sortList = new ArrayList<>();
        sortList.add(wechatOfficialAccountProperties.getConfigToken());
        sortList.add(timestamp);
        sortList.add(nonce);
        Collections.sort(sortList);
        StringBuilder newSignature = new StringBuilder();
        sortList.forEach(str -> {
            newSignature.append(str);
        });
        if (!StringUtils.pathEquals(signature, new SimpleHash("SHA-1", newSignature.toString()).toString())) {
            return false;
        }
        return true;
    }

    public void setWechatOfficialAccountProperties(WechatOfficialAccountProperties wechatOfficialAccountProperties) {
        this.wechatOfficialAccountProperties = wechatOfficialAccountProperties;
    }

    /**
     * 错误返回
     *
     * @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));
    }

}