package com.steerinfo.filter;

import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.steerinfo.framework.controller.RESTfulResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
@WebFilter("/*")
public class SecurityFilter implements Filter {

    /** TODO[TEMP-AUTH-OFF] 默认 false 便于联调；测试完改配置为 true */
    @Value("${security.verification.enabled:true}")
    private boolean verificationEnabled;

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

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //获取请求
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String path = request.getRequestURI();
        String method = request.getMethod();
        StringBuffer url = request.getRequestURL();
        // TODO[TEMP-AUTH-OFF] 临时关闭 verificationCode 校验
        if (!verificationEnabled) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        //不拦截
        ///apifox导入请求路径：v2/api-docs
        if (path.contains("/v1/meterbasecars/appregister")
                ||path.contains("/v1/meterbasecars/applogin")
                ||path.contains("/v1/MeterWorkZnlc")
                ||path.contains("/v1/authority/getVerification")
                ||path.contains("/v1/meterworkcaractuals/ApplikeByDesc")
                ||path.contains("/v1/meterworkcaractualfirsts/ApplikeByDesc")
                ||"/v2/api-docs".equals(path)){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        //邓义晶：10.104.4.105  app：10.1.201.188
        //app:https://app.jiugang.com/jgjl/v1/meterbasecars/applogin
        //网页代理ip：https://jgwzjl.jiugang.com/icore.icp.web/pass/systemBase/v1/meterbasecars/applogin
        //本地：http://10.104.4.105:9004/v1/meterbasecars/applogin
        if(request.getRemoteAddr().equals("10.1.201.188")
                ||request.getRemoteAddr().equals("10.104.4.105")
                //||request.getRemoteAddr().equals("127.0.0.1")
                ||request.getRemoteAddr().equals("0:0:0:0:0:0:0:1")
                ||request.getRemoteAddr().equals("10.104.0.1")
            ) {
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        // 1. 先尝试拿vCode
        String vCode = request.getParameter("verificationCode");
        // 获取json字符串
        if(vCode == null || StringUtils.isEmpty(vCode)) {
            vCode = request.getHeader("verificationCode");
        }
//        vCode = "3d7a923b0cb1f35d56901a289877e1de";
        //取出验证码
        if(vCode == null || StringUtils.isEmpty(vCode)) {
            response.setContentType("application/json;charset=UTF-8");
            RESTfulResult result = new RESTfulResult("500", "验证参数为空，不能请求！！");
            result.setData(null);
            JSONObject object = new JSONObject(result);
            response.getWriter().print(object);
            return;
        }
        String verificationCode1 = vCode;
        verificationCode1 = verificationCode1.toLowerCase(Locale.ROOT);
        //生成原数据
        SimpleDateFormat df = new SimpleDateFormat("MM-yyyy-dd");
        Date date = new Date();
        Date date1 = this.dateAdd(date, -1);
        Date date2 = this.dateAdd(date, 1);

        StringBuffer dateStr = new StringBuffer(df.format(date));
        StringBuffer dateStr1 = new StringBuffer(df.format(date1));
        StringBuffer dateStr2 = new StringBuffer(df.format(date2));

        dateStr = dateStr.insert(2,"jisco");
        dateStr1 = dateStr1.insert(2,"jisco");
        dateStr2 = dateStr2.insert(2,"jisco");

        //原数据MD5加密
        String verCode = DigestUtils.md5DigestAsHex(dateStr.toString().getBytes(StandardCharsets.UTF_8)).toLowerCase(Locale.ROOT);
        String verCode1 = DigestUtils.md5DigestAsHex(dateStr1.toString().getBytes(StandardCharsets.UTF_8)).toLowerCase(Locale.ROOT);
        String verCode2 = DigestUtils.md5DigestAsHex(dateStr2.toString().getBytes(StandardCharsets.UTF_8)).toLowerCase(Locale.ROOT);

        //比对
        //if (1 == 2){//比对成功
        if (verCode.equals(verificationCode1) || verCode1.equals(verificationCode1) || verCode2.equals(verificationCode1)){//比对成功
            filterChain.doFilter(servletRequest,servletResponse);
        }else {//比对失败
            response.setContentType("application/json;charset=UTF-8");
            RESTfulResult result = new RESTfulResult("500", "访问未授权");
            result.setData(null);
            JSONObject object = new JSONObject(result);
            response.getWriter().print(object);
        }
        return;
    }

    @Override
    public void destroy() {

    }

    /*日期加+n天*/
    public static Date dateAdd(Date date, Integer addnum) {
        Calendar   calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE, addnum); //把日期往后增加一天,整数  往后推,负数往前移动
        date=calendar.getTime(); //这个时间就是日期往后推一天的结果
        return date;
    }

    /**
     * 获取Json数据
     *
     * @param request
     * @return
     */
//    private String getJsonParam(HttpServletRequest request) {
//
//        String jsonParam = "";
//        ServletInputStream inputStream = null;
//        try {
//            int contentLength = request.getContentLength();
//            if (!(contentLength < 0)) {
//                byte[] buffer = new byte[contentLength];
//                inputStream = request.getInputStream();
//                for (int i = 0; i < contentLength; ) {
//                    int len = inputStream.read(buffer, i, contentLength);
//                    if (len == -1) {
//                        break;
//                    }
//                    i += len;
//                }
//                jsonParam = new String(buffer, "utf-8");
//            }
//        } catch (IOException e) {
//        } finally {
//            if (inputStream != null) {
//                try {
//                    inputStream.close();
//                } catch (IOException e) {
//                }
//            }
//        }
//        return jsonParam;
//    }



//
//    public static String getRequestJson(HttpServletRequest request) {
//        boolean isGetRequest = request.getMethod().toLowerCase().equals("get");
//        try {
////            if (isGetRequest) {
////                return new String(request.getQueryString().getBytes(
////                        "ISO-8859-1"), "UTF-8").replaceAll("%22", "\"");
////            }
//            int contentLength = request.getContentLength();
//            if (contentLength < 0) {
//                return null;
//            }
//            byte buffer[] = new byte[contentLength];
//            for (int i = 0; i < contentLength;) {
//
//                int readlen = request.getInputStream().read(buffer, i,
//                        contentLength - i);
//                if (readlen == -1) {
//                    break;
//                }
//                i += readlen;
//            }
//            return new String(buffer, "UTF-8");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
//    }
}
