package com.rrtx.services.common.filter;

import com.alibaba.fastjson.JSON;
import com.rrtx.services.common.constant.ContextParam;
import com.rrtx.services.common.utils.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StreamUtils;

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

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

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        //TODO 待补充其他参数
        clearContextParam();
//        ContextParam.LANGUAGE.set("zh");
        if(!isDebug) {
            try {
                // 解密输入参数 TODO 证书参数化
//                String param = StreamUtils.copyToString(req.getInputStream(), Charset.defaultCharset());
//                Map paraMap = (Map) JSON.parse(param);
//                if(paraMap == null) {
//                    throw new Exception("Param is Error!");
//                }
//                String jiemihou = CipherEnvelopeCBC.deCode(filePath,
//                        "123456", "sec_test", (String)paraMap.get("param"));
//                if(jiemihou == null) {
//                    throw new Exception("Param is Error!");
//                }
//
//                // 重置输入参数
//                Map maps = (Map) JSON.parse(jiemihou);
//                Map head = (Map)maps.get("head");
//                ParameterRequestWrapper wrapRequest = new ParameterRequestWrapper(req, maps);
//                request = wrapRequest;
//                 saveContextParam(req);// 设定当前交易代码
            } catch (Exception ex) {
                ex.printStackTrace();
               return;
            }
        }
        else {
            try {
                HttpServletRequest req = (HttpServletRequest) request;
                String token = req.getParameter("token");
                ContextParam.TOKEN.set(token);
//                String param = StreamUtils.copyToString(req.getInputStream(), Charset.defaultCharset());
                log.info("请求接口：".concat(req.getServletPath()));
//                log.info("APP请求参数：" + param);
//                if(CommonUtil.isNotEmpty(param)) {
//                    Map maps = (Map) JSON.parse(param);
//                    Map head = (Map)maps.get("head");
//                    initHead(head);
//                    ParameterRequestWrapper wrapRequest = new ParameterRequestWrapper(req, maps);
//                    request = wrapRequest;
//                }
//                //TODO 临时注释，需要切换redis服务器 sunbzh
//                saveContextParam(req);// 设定当前交易代码
            }
            catch (Exception ex) {
                ex.printStackTrace();
                return;
            }

        }
        ContextParam.LANGUAGE.set("zh");//设置中文
        chain.doFilter(request, response);
    }

    /**
     * 设定报文头
     * @param head
     */
    private void initHead(Map head) {
        if(head != null) {
            ContextParam.OS.set(CommonUtil.objToString(head.get("OS")));
            ContextParam.OS_NAME.set(CommonUtil.objToString(head.get("osName")));
            ContextParam.OS_VERSION.set(CommonUtil.objToString(head.get("osVersion")));
            ContextParam.DEV_NO.set(CommonUtil.objToString(head.get("deviceNo")));
            ContextParam.DEV_IMSI.set(CommonUtil.objToString(head.get("DEV_IMSI")));
            ContextParam.TOKEN.set(CommonUtil.objToString(head.get("token")));
            String language = CommonUtil.objToString(head.get("language"));
            ContextParam.PRO_LANGUAGE.set(language);
            if("ZH_CN".equals(language)) {
                ContextParam.LANGUAGE.set("zh");
            }
            else {
                ContextParam.LANGUAGE.set("en");
            }
        }
        if(CommonUtil.isEmpty(ContextParam.DEV_NO.get())) {
            ContextParam.DEV_NO.set("0000000000");
        }
    }


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