package com.cool.store.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cool.store.constants.CommonConstants;
import com.cool.store.context.PartnerUserHolder;
import com.cool.store.enums.ErrorCodeEnum;
import com.cool.store.response.ResponseResult;
import com.cool.store.service.WechatMiniAppService;
import com.cool.store.utils.*;
import com.cool.store.vo.PartnerUserInfoVO;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ydw
 * @Description 权限校验
 * @date 2020/1/15
 */
@Component
@Order(3)
@Slf4j
public class SignValidateFilter implements Filter {

    @Resource
    private WechatMiniAppService wechatMiniAppService;

    @Value("${signKey}")
    private String signKey;

    private static AntPathMatcher matcher = new AntPathMatcher();

    private static List<String> patternList =
            Lists.newArrayList("/web/check/ok","/check/ok",
                    "/partner/mini/program/doc.html","/partner/mini/program/v2/api-docs","/**/test/**",
                    "/partner/mini/program/oss/getUploadFileConfig",
                    "/partner/mini/program/v1/partnerManage/partner/getIdentityCardInfo",
                    "/**/swagger*/**", "/**/webjars/**","/partner/mini/program/v1/partnerManage/openArea/areaApplyQuery");


    /**
     * @param uri
     * @return boolean
     * @throws
     * @Title excludePath
     * @Description 是否是放行的请求
     */
    private boolean excludePath(String uri) {
        for (String pattern : patternList) {
            if (matcher.match(pattern, uri)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        MDC.put(CommonConstants.REQUEST_ID, UUIDUtils.get32UUID());
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        CustomHttpServletRequestWrapper wrapper = (CustomHttpServletRequestWrapper) request;
        String uri = request.getRequestURI();
        String method = request.getMethod();
        String userStr = "";
        boolean isInWhiteList = excludePath(uri);
        log.info("url:{}", uri);
        if ( !isInWhiteList && !method.equals("OPTIONS")) {
            String params = "";
            if("GET".equalsIgnoreCase(method)){
                params  =  request.getQueryString();
            }else if("POST".equalsIgnoreCase(method)){
                params = wrapper.getBody();
                // params = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
            }
            log.info("params:{}", params);
            String sign = request.getHeader("SIGN");
            String nonce = request.getHeader("NONCE");
            String timestamp = request.getHeader("TIMESTAMP");
            String aesPhone = request.getHeader("PHONE");
            String openid = request.getHeader("OPENID");
            log.info("aesPhone:{}, signKey:{}", aesPhone, signKey);
            String phone = AESDecryptor.decrypt(aesPhone, signKey);
            String plaintextOpenid = AESDecryptor.decrypt(openid, signKey);
            String md5Value = phone + Md5Utils.md5(Md5Utils.md5(plaintextOpenid));
            log.info("sign:{}, nonce:{}, timestamp:{},aesPhone:{}, openid:{}, 解密后的手机号:{}, md5Value:{}, 明文plaintextOpenid:{}",
                    sign, nonce, timestamp, aesPhone, openid, phone, md5Value, plaintextOpenid);
            String signStr = timestamp + nonce + params + signKey + md5Value;
            String newSign = Sha1Utils.getSha1(signStr.getBytes());
            log.info("signStr: {}, newSign: {}", signStr, newSign);
            // 前后端验签不等
            if (!newSign.equals(sign)) {
                response.setStatus(HttpStatus.OK.value());
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write(JSON.toJSONString(ResponseResult.fail(ErrorCodeEnum.SIGN_FAIL)));
                return;
            }
            PartnerUserInfoVO partnerUserInfoVO = wechatMiniAppService.getUserInfo(phone, plaintextOpenid);
            if(partnerUserInfoVO != null){
                userStr = JSONObject.toJSONString(partnerUserInfoVO);
                log.info("url:{}, userStr:{}", uri, userStr);
            }
        }
        try {
            PartnerUserHolder.setUser(userStr);
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            PartnerUserHolder.removeUser();
            MDC.clear();
        }
    }

    @Override
    public void destroy() {

    }
}
