package com.sundot.airport.framework.config;

import javax.servlet.http.HttpServletRequest;

import cn.hutool.core.util.StrUtil;
import org.springframework.stereotype.Component;
import com.sundot.airport.common.utils.ServletUtils;

/**
 * 服务相关配置
 *
 * @author ruoyi
 */
@Component
public class ServerConfig {
    /**
     * 获取完整的请求路径，包括：域名，端口，上下文访问路径
     *
     * @return 服务地址
     */
    public String getUrl() {
        HttpServletRequest request = ServletUtils.getRequest();
        return getDomain(request);
    }

    public static String getDomain(HttpServletRequest request) {
        StringBuffer url = request.getRequestURL();
        String contextPath = request.getServletContext().getContextPath();
        url.delete(url.length() - request.getRequestURI().length(), url.length());

        // 如果 URL 以 / 结尾，去掉它（避免出现 http://example.com/:9011）
        if (url.charAt(url.length() - 1) == '/') {
            url.deleteCharAt(url.length() - 1);
        }
        // 获取当前请求的端口
        int currentPort = request.getServerPort();
        // 如果是80或443端口（HTTP/HTTPS默认端口），则强制使用9011端口
        if (!StrUtil.equals("http://192.168.3.221", url) && (currentPort == 80 || currentPort == 443)) {
            int protocolEnd = url.indexOf("://") + 3;
            int portStart = url.indexOf(":", protocolEnd);
            if (portStart < 0) {
                // 没有端口，添加端口
                url.insert(url.length(), ":9021");
            }
        }
        return url.append(contextPath).toString();
    }
}
