package weaver.filter;

import com.weaver.file.Prop;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.StringUtil;
import weaver.general.Util;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class LoginEMFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {
        // String isopen = Prop.getPropValue("emloginFilter", "isopen");
        Boolean isopen = false;
        RecordSet rs = new RecordSet();
        rs.executeQuery("select count(id) cnt from uf_emloginFilter where isOpen = 0");
        try {
            if (rs.next()){
                int cnt = Util.getIntValue(rs.getString("cnt"));
                isopen = cnt  >  0 ;
            }
        }catch (Exception e){

        }

        if (isopen){
            try {
                HttpServletRequest request = (HttpServletRequest) servletRequest;
                StringBuffer url = request.getRequestURL();
                new BaseBean().writeLog("请求地址====>getRequestURL" + url);
                //内网请求
                if(url.indexOf("14.1.") == -1){
                    // String currentDateTime = request.getHeader("currentDateTime");
                    // String MdToken = request.getHeader("MdToken");
                    String currentDateTime = getCookie(request,"currentDateTime");
                    String MdToken = getCookie(request,"MdToken");
                    new BaseBean().writeLog("请求地址====>currentDateTime" + currentDateTime);
                    new BaseBean().writeLog("请求地址====>MdToken" + MdToken);
                    if (StringUtil.isEmpty(currentDateTime)||StringUtil.isEmpty(MdToken)){
                        // 如果条件满足，发送HTTP 500错误
                        ((HttpServletResponse) servletResponse).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error");
                        return;
                    }
                    //大于十分钟返回报错
                    boolean b = DateExample(currentDateTime);
                    if (b){
                        new BaseBean().writeLog("请求地址====>时间异常" + b);
                        ((HttpServletResponse) servletResponse).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error");
                        return;
                    }
                    String password = "ecologytq33q#LzDw$98HwEA@"+currentDateTime;
                    new BaseBean().writeLog("请求地址====>toMD5(password)" + toMD5(password));

                    if (!(toMD5(password).toLowerCase().equals(MdToken))){
                         new BaseBean().writeLog("请求地址====>签名错误" +MdToken);
                        ((HttpServletResponse) servletResponse).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error");
                        return;
                    }else {
                        filterChain.doFilter(servletRequest, servletResponse);
                    }

                }else {
                    filterChain.doFilter(servletRequest, servletResponse);
                }
            } catch (Exception e) {
                new BaseBean().writeLog("请求地址====>error" + e.getMessage());
            }
        }else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {

    }

    public static String toMD5(String input) {
        try {
            // 创建MessageDigest实例，指定MD5算法
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 更新MessageDigest对象以包含要加密的字节
            md.update(input.getBytes());
            // 完成哈希计算
            byte[] digest = md.digest();

            // 将哈希值转换为十六进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : digest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {hexString.append('0');}
                hexString.append(hex);
            }

            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }


    }

    public static boolean DateExample (String dateTimeStr) {
        try {

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            Date parsedDate = sdf.parse(dateTimeStr);

            Date currentDate = new Date();
            long difference = currentDate.getTime() - parsedDate.getTime();
            // System.out.println(difference);
            // 10分钟 = 10 * 60 * 1000 毫秒
            if ( Math.abs(difference) > 5 * 60 * 1000) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            //报错也返回大于10分钟
            e.printStackTrace();
            return true;
        }
    }



    private String getCookie(HttpServletRequest request,String name){
        try {
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if(name.equals(cookie.getName())){
                        return Util.null2String(cookie.getValue());
                    }
                }
            }
        }catch (Exception e){
            new BaseBean().writeLog("getCookieError:"+e.getMessage());
            e.printStackTrace();
        }
        return "";
    }


    public static void main(String[] args) {
        // String originalString = "tq33q#LzDw$98HwEA@";
        // String md5String = toMD5(originalString);
        // System.out.println("Original: " + originalString);
        // System.out.println("MD5 Hash: " + md5String);
        System.out.println(DateExample("20240613071112"));
        ;
    }
}


