package com.ruoyi.framework.shiro.web.filter.embed;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import com.ruoyi.common.utils.StringUtils;

/**
 * HIS iframe 嵌入模式识别（embed=1 / Referer / 自定义头）
 */
public final class EmbedRequestUtils
{
    public static final String EMBED_PARAM = "embed";
    public static final String EMBED_HEADER = "X-HIS-IPCC-Embed";

    private EmbedRequestUtils()
    {
    }

    public static boolean isEmbed(ServletRequest request)
    {
        if (request == null)
        {
            return false;
        }
        if ("1".equals(request.getParameter(EMBED_PARAM)))
        {
            return true;
        }
        if (!(request instanceof HttpServletRequest))
        {
            return false;
        }
        HttpServletRequest req = (HttpServletRequest) request;
        if ("1".equals(req.getHeader(EMBED_HEADER)))
        {
            return true;
        }
        String referer = req.getHeader("Referer");
        if (StringUtils.isNotEmpty(referer) && referer.contains("embed=1"))
        {
            return true;
        }
        return false;
    }

    /** 登录 URL 补齐 embed=1&lang=zh_CN，避免踢回登录后丢失嵌入态 */
    public static String withEmbedParams(String loginUrl)
    {
        String url = StringUtils.isEmpty(loginUrl) ? "/login" : loginUrl;
        if (url.contains("embed=1"))
        {
            return url;
        }
        StringBuilder sb = new StringBuilder(url);
        sb.append(url.contains("?") ? "&" : "?");
        sb.append("embed=1");
        if (!url.contains("lang="))
        {
            sb.append("&lang=zh_CN");
        }
        return sb.toString();
    }
}
