package org.example.Utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import jakarta.annotation.PostConstruct;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.File;
import java.nio.file.Paths;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
@Lazy(false)
public class WebConfigUtil_web implements ApplicationContextAware {
    private static final Logger log = LoggerFactory.getLogger(WebConfigUtil_web.class);

    private static Environment environment;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        log.debug(String.valueOf("【WebConfigUtil_web】setApplicationContext 执行 → applicationContext是否为空：" + (applicationContext != null ? "非空" : "空")));
        if (applicationContext != null) {
            WebConfigUtil_web.environment = applicationContext.getEnvironment();
            log.debug(String.valueOf("【WebConfigUtil_web】environment 赋值完成 → 是否为空：" + (WebConfigUtil_web.environment != null ? "非空" : "空")));
            // 顺便打印 SingleUser 配置（验证是否能读到）
            if (WebConfigUtil_web.environment != null) {
                log.debug(String.valueOf("【WebConfigUtil_web】读到的 SingleUser 配置：" + WebConfigUtil_web.environment.getProperty("SingleUser")));
            }
        }
    }

    public static String language;

    // 从application.properties读取配置
    @Value("${language:zh-CN}")
    private String languageInstance;

    // 初始化方法：在实例创建后将配置值赋值给静态字段
    @PostConstruct
    public void init() {
        // 将实例字段的值同步到静态字段
        WebConfigUtil_web.language = this.languageInstance;
    }

    @Value("${appname:WebERP}")
    private String appName;

    @Value("${jpappkey:}")
    private String jpAppKey;

    @Value("${jpsecret:}")
    private String jpSecret;

    @Value("${updImgPath:WebUpload/Image/{0}/{1}/}")
    private String pubModelImgPath;

    @Value("${updFilePath:WebUpload/{0}/{1}/{2}/}")
    private static String pubModelFilePath;

//    @Value("${fileVPath:fileRoot}")
//    private static String fileVPath;

    public static String fileVPath;

    @Value("${fileVPath:fileRoot}") // 兜底语法在此处生效
    public void setFileVPath(String fileVPath) {
        WebConfigUtil_web.fileVPath = fileVPath; // 给静态变量赋值
    }

    @Value("${filePath:}")
    private static String cfgFilePath = "/home/Lserp";

    @Value("${fileDomain:}")
    private static String fileDomain;

    // 静态常量
    public static final String SysTabAppCacheName = "SysTabAppCache";
    public static final String Session_Purview = "Session_Purview";
    public static final String Session_Users = "Session_Users";
    public static final String Session_LoginUser = "Session_LoginUsers";
    public static final String Session_LoginUsersSessionName = "Session_LoginUsersSessionName";
    public static final String Session_ConStr = "Session_ConStr";
    public static final String Session_Request = "Session_Request";
    public static final String weburl_bs_web = "";

    // 缓存路径变量
    private static String filePath;
    private static String serverPath;
    private static String fileDomian;

    // 获取当前请求
    private static HttpServletRequest getRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attributes != null ? attributes.getRequest() : null;
    }

    // 网站根路径（对应ServerPath）
    public static String getServerPath() {
        if (serverPath == null) {
            HttpServletRequest request = getRequest();
            if (request != null) {
                serverPath = request.getServletContext().getRealPath("/");
            } else {
                serverPath = new File("").getAbsolutePath() + File.separator;
            }
        }
        return serverPath;
    }

    // 文件上传物理路径（对应FilePath）
    public static String getFilePath() {
//        if (filePath == null) {
//            if (StringUtils.hasText(cfgFilePath)) {
//                filePath = cfgFilePath;
//            } else {
//                HttpServletRequest request = getRequest();
//                if (request != null) {
//                    // 映射虚拟路径到物理路径
//                    filePath = request.getServletContext().getRealPath(
//                            fileVPath.startsWith("/") ? fileVPath : "/" + fileVPath
//                    );
//                } else {
//                    // 非Web环境下的默认路径
//                    filePath = Paths.get(getServerPath(), fileVPath).toString();
//                }
//            }
//            // 确保路径包含fileVPath
//            if (!filePath.contains(fileVPath)) {
//                filePath = Paths.get(filePath, fileVPath).toString();
//            }
//        }
        filePath = "/home/Lserp/fileRoot";
        return filePath;
    }

    // 网站基础URL（对应WebUrl）
    public static String getWebUrl() {
//        HttpServletRequest request = getRequest();
//        if (request != null) {
//            return String.format("%s://%s:%d",
//                    request.getScheme(),
//                    request.getServerName(),
//                    request.getServerPort()
//            );
//        }
//        return "";
        HttpServletRequest request = getRequest();
        if (request != null) {
            // 获取Referer头（前端页面地址）
            String referer = request.getHeader("Origin");
            if (referer != null && !referer.isEmpty()) {
                return referer;
            }

            // 兼容原有逻辑
            return String.format("%s://%s:%d",
                    request.getScheme(),
                    request.getServerName(),
                    request.getServerPort()
            );
        }
        return "";
    }

    // 文件域名（对应FileDomian）
    public static String getFileDomain() {
        if (fileDomian == null) {
            if (StringUtils.hasText(fileDomain)) {
                fileDomian = fileDomain;
            } else {
                fileDomian = getWebUrl();
            }
        }
        return fileDomian;
    }

    // 处理文档HTML路径（对应GetViewDocHtmlPath）
    public static String getViewDocHtmlPath(String filePath, StringBuilder vHtmlPath) {
        Pattern pattern = Pattern.compile(fileVPath, Pattern.CASE_INSENSITIVE);
//        System.out.println("123");
        Matcher matcher = pattern.matcher(filePath);
//        System.out.println("1324");
        String docHtmlPath = matcher.replaceAll("DocHtml");

        String[] parts = docHtmlPath.split("\\\\");
        String fileName = parts[parts.length - 1];
        String newName = fileName.replace(".", "");
        docHtmlPath = docHtmlPath.replace(fileName, newName) + ".pdf";
        int index = docHtmlPath.indexOf("DocHtml");
        if (index > 0) {
            vHtmlPath.append(docHtmlPath.substring(index - 1).replace("\\", "/"));
        } else {
            vHtmlPath.append(docHtmlPath.replace("\\", "/"));
        }

//        HttpServletRequest request = getRequest();
//        if (request != null) {
//            String referer = request.getHeader("Referer");
//            if (referer != null && !referer.isEmpty()) {
//                return referer.substring(0,referer.length()-1) +  vHtmlPath.toString();
//            }
//            return request.getServletContext().getRealPath(vHtmlPath.toString());
//            return String.format("%s://%s:%d/%s",
//                    request.getScheme(),
//                    request.getServerName(),
//                    request.getServerPort(),
//                    vHtmlPath.toString());
//        } else {
//            return Paths.get(getServerPath(), vHtmlPath.toString()).toString();
//        }
        return cfgFilePath + vHtmlPath.toString();
    }

    /**
     * 获取配置值，当配置不存在时返回默认值
     *
     * @param key        配置键名
     * @param defaultVal 默认值
     * @return 配置值或默认值
     */
    public static String get(String key, String defaultVal) {
        if (environment == null) {
            return defaultVal;
        }
        // 获取配置，不存在则返回默认值
        return environment.getProperty(key, defaultVal);
    }

    /**
     * 重载方法，默认值为空字符串
     */
    public static String get(String key) {
        return get(key, "");
    }

    // Getter方法（省略部分，按需添加）
    public String getLanguage() {
        return language;
    }

    public String getAppName() {
        return appName;
    }

    public String getJpAppKey() {
        return jpAppKey;
    }

    public String getJpSecret() {
        return jpSecret;
    }

    public String getPubModelImgPath() {
        return pubModelImgPath;
    }

    public static String getPubModelFilePath() {
        return pubModelFilePath;
    }

    public static String getFileVPath() {
        return fileVPath;
    }
}

