package com.rrtx.services.common.filter;

import com.alibaba.fastjson.JSON;
import com.min.util.CipherEnvelopeCBC;
import com.rrtx.services.common.utils.TranslateUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * APP&服务端，接口过滤器
 *
 * @author zhangzz@minpay.cc
 *
 */
@Slf4j
@WebFilter(urlPatterns = "/API4HOST/*",filterName = "api4HOSTFilter")
public class API4HOSTFilter extends BaseFilter {
    // 是否是不加密 true: 不加密 false:加密
    private static boolean isDebug = true;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        log.info("API4HOSTFilter doFilter");

        if(!isDebug) {
            try {
                // 解密输入参数
                String param =  request.getParameter("param");
                String privateKeyPath = TranslateUtil.val4Sys("HOST_PRIVATE_CERT_PATH");
                String password = TranslateUtil.val4Sys("HOST_PRIVATE_CERT_PWD");
                String alias = TranslateUtil.val4Sys("HOST_PRIVATE_CERT_ALIAS");
                String jiemihou = CipherEnvelopeCBC.deCode(privateKeyPath,
                        password, alias, param);
                if(jiemihou == null) {
                    throw new Exception("Param is Error!");
                }

                // 重置输入参数
                Map maps = (Map) JSON.parse(jiemihou);
                HttpServletRequest req = (HttpServletRequest) request;
                ParameterRequestWrapper wrapRequest = new ParameterRequestWrapper(req, maps);
                request = wrapRequest;

                //TODO 待补充其他参数
                clearContextParam();
                saveContextParam(wrapRequest);

            } catch (Exception ex) {
               return;
            }
        }

        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        clearContextParam();
    }
}
