package org.example.Api;


import org.example.Enums.SystemTypeEnums;
import org.example.Utils.AESUtil;
import org.example.Utils.GZipUtil;
import org.example.Impl.BaseImpl;
import jakarta.servlet.http.HttpServletRequest;
import org.example.Utils.JSON;
import org.example.Utils.WebConfigUtil_web;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.Hashtable;


/**
 * ==============================================================================
 * 功能描述：RequestHandler
 * ==============================================================================
 */
public class RequestHandler {
    protected Hashtable<String, Object> requestPms;
    protected Hashtable<String, Object> zipedPms;

    public RequestHandler() {
        requestPms = new Hashtable<>();
        initPms();
    }


    /**
     * 重置form表单参数
     */
    protected void initPms() {
        zipedPms = null;
        try {
            String pms = request("pms");
//            out.println(pms + "   1pms");
            if (pms != null && !pms.isEmpty()) {
                try {
                    if (pms.contains("%")) {
                        pms = java.net.URLDecoder.decode(pms, StandardCharsets.UTF_8);
                    }
                    requestPms = (Hashtable<String, Object>) JSON.Decode(AESUtil.mobileDecrypt(pms), Hashtable.class);

                    if (requestPms != null && !requestPms.isEmpty()) {
                        Hashtable<String, Object> temp = new Hashtable<>();
                        for (String key : requestPms.keySet()) {
                            String lkey = key.toLowerCase();
                            temp.put(lkey, requestPms.get(key));
                        }
                        requestPms = temp;
                    }
                } catch (Exception e) {
                    // 异常处理，可根据需要添加日志
                }
            }

            if (requestPms == null) {
                requestPms = new Hashtable<>();
            }
        } catch (Exception e) {
            // 异常处理，可根据需要添加日志
        }
    }

    public void clearPms() {
        BaseImpl.setSessionVal(WebConfigUtil_web.Session_Request, "");
    }

    /**
     * 经过压缩后的参数
     */
    protected Hashtable<String, Object> getZipedPms() {
        if (zipedPms != null) {
            return zipedPms;
        }

        if (isContentZiped()) {
            HttpServletRequest request = getHttpServletRequest();
            try (Reader reader = new InputStreamReader(request.getInputStream(), request.getCharacterEncoding())) {
                StringBuilder contentBuilder = new StringBuilder();
                char[] buffer = new char[1024];
                int bytesRead;
                while ((bytesRead = reader.read(buffer)) != -1) {
                    contentBuilder.append(buffer, 0, bytesRead);
                }
                String content = contentBuilder.toString();

                if (content != null && !content.isEmpty()) {
                    BaseImpl.setSessionVal(WebConfigUtil_web.Session_Request, content);
                } else {
                    Object sessionContent = BaseImpl.getSessionVal(WebConfigUtil_web.Session_Request);
                    content = sessionContent != null ? sessionContent.toString() : "";
                }

                byte[] buf = java.util.Base64.getDecoder().decode(content);
                content = java.net.URLDecoder.decode(GZipUtil.unZip(buf), StandardCharsets.UTF_8);

                if (content != null && !content.isEmpty()) {
                    zipedPms = (Hashtable<String, Object>) JSON.Decode(content, Hashtable.class);
                    if (zipedPms != null && !zipedPms.isEmpty()) {
                        Hashtable<String, Object> temp = new Hashtable<>();
                        for (String key : zipedPms.keySet()) {
                            temp.put(key.toLowerCase(), zipedPms.get(key));
                        }
                        zipedPms = temp;
                        return temp;
                    }
                }
            } catch (IOException e) {
                // 异常处理，可根据需要添加日志
            }
        }
        return null;
    }

    protected void setRequestPms(String key, String val) {
        requestPms.put(key, val);
    }

    /**
     * 客户端类型
     */
    private int clinetType;

    public int getClinetType() {
        return SystemTypeEnums.LoginType.Web.getValue();
    }

    public void setClinetType(int clinetType) {
        this.clinetType = clinetType;
    }

    public SystemTypeEnums.LoginType getLgType() {
        try {
            return SystemTypeEnums.LoginType.valueOf(String.valueOf(getClinetType()));
        } catch (IllegalArgumentException e) {
            return SystemTypeEnums.LoginType.Web;
        }
    }

    /**
     * 内容编码类型
     */
    private String getContentEncoding() {
        HttpServletRequest request = getHttpServletRequest();
        return request != null ? request.getHeader("Content-Encoding") : null;
    }

    /**
     * webrequest的内容是否是压缩过的
     */
    private boolean isContentZiped() {
        String contentEncoding = getContentEncoding();
        return contentEncoding != null &&
                (contentEncoding.contains("gzip") || contentEncoding.contains("deflate"));
    }

    /**
     * 获取表单参数
     *
     * @param key        表单键
     * @param defaultVal 默认值
     * @return 参数值
     */
    public String request(String key, String defaultVal) {
        key = key.toLowerCase(); // 参数不区分大小写
        String val = null;

        try {
            HttpServletRequest request = getHttpServletRequest();
            if (request == null) {
                return defaultVal;
            }
        } catch (Exception e) {
            // 在程序未初始化完成时访问会报错
            return defaultVal;
        }

        Hashtable<String, Object> ziped = getZipedPms();
        if (ziped != null && ziped.containsKey(key)) {
            val = String.valueOf(ziped.get(key));
        }

        if ((val == null || val.isEmpty()) && requestPms.containsKey(key)) {
            val = String.valueOf(requestPms.get(key));
        }

        if (val == null || val.isEmpty()) {
            HttpServletRequest request = getHttpServletRequest();
            val = request != null ? request.getParameter(key) : null;
            if ((val == null || val.isEmpty()) && !key.isEmpty()) {
                Enumeration<String> paramNames = null;
                if (request != null) {
                    paramNames = request.getParameterNames();
                }
                if (paramNames != null) {
                    while (paramNames.hasMoreElements()) {
                        String paramName = paramNames.nextElement();
                        if (paramName.equalsIgnoreCase(key)) {
                            val = request.getParameter(paramName);
                            break;
                        }
                    }
                }
            }
            if (val == null || val.isEmpty()) {
                val = defaultVal;
            }
        }

        return val;
    }

    public String request(String key) {
        return request(key, "");
    }

    public String pmsRequest(String key, String defaultVal) {
        String val = null;
        if (requestPms.containsKey(key)) {
            val = String.valueOf(requestPms.get(key));
        }
        return val != null ? val : defaultVal;
    }

    public String pmsRequest(String key) {
        return pmsRequest(key, "");
    }

    public Hashtable<String, Object> getAllRequest() {
        Hashtable<String, Object> req = new Hashtable<>();
        HttpServletRequest request = getHttpServletRequest();
        if (request == null) {
            return req;
        }

        // 添加查询参数
        Enumeration<String> queryParams = request.getParameterNames();
        while (queryParams.hasMoreElements()) {
            String key = queryParams.nextElement();
            if (key != null && !key.isEmpty()) {
                req.put(key, request.getParameter(key));
            }
        }

        return req;
    }

    /**
     * 获取当前请求对象
     */
    protected HttpServletRequest getHttpServletRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

}