package com.thinkgem.jeesite.common.filter;

import com.thinkgem.jeesite.common.constant.ComCode;
import com.thinkgem.jeesite.common.utils.MD5;
import org.springframework.context.annotation.ComponentScan;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 验证sign
 */
@WebFilter(filterName = "validationFilter", urlPatterns = "/api/*")
public class ValidationFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        String url = httpRequest.getRequestURL().toString();
        if (url == null || url.trim().length() == 0) {
            return;
        }
        String urls = url.substring(url.lastIndexOf("/")+1);
        List<String> list = new ArrayList<>();
        list.add("openCardCallback");
        list.add("notifyQuickPay");
        list.add("notifyPay");
        list.add("aliPayCallback");
        if(!list.contains(urls)){
            String signCode = ComCode.signCode;
            String subMerchantCode = httpRequest.getParameter("subMerchantCode");
            String timestamp = httpRequest.getParameter("timestamp");
            String sign = httpRequest.getParameter("sign");
            String checkSign = MD5.sign(subMerchantCode + signCode + timestamp, "", "utf-8");
            if (!checkSign.equals(sign)) {
                servletRequest.getRequestDispatcher("/com/filterError/returnError?code=" + 1 + "&subMerchantCode=" + subMerchantCode).forward(servletRequest, servletResponse);
                return;
            }
        }



        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }

    @Override
    public void destroy() {
    }
}
