package com.jeesharp.business.modules.common.bizscene.support;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.Getter;

/**
 * 从 {@code cfg_biz_scene.ext_json.mobile} 解析小程序轮播/跳转路径。
 *
 * @author jeesharp
 * @since 2026-07-03
 */
public final class BizSceneMobileJumpSupport {

    private BizSceneMobileJumpSupport() {
    }

    /**
     * 解析 ext_json 中的 mobile 节点。
     */
    public static MobileJump parse(String extJson) {
        if (StrUtil.isBlank(extJson)) {
            return null;
        }
        JSONObject root = JSONUtil.parseObj(extJson);
        JSONObject mobile = root.getJSONObject("mobile");
        if (mobile == null) {
            return null;
        }
        String detailPath = mobile.getStr("detailPath");
        if (StrUtil.isBlank(detailPath)) {
            return null;
        }
        String detailIdParam = mobile.getStr("detailIdParam");
        if (StrUtil.isBlank(detailIdParam)) {
            detailIdParam = "id";
        }
        String listPath = mobile.getStr("listPath");
        return new MobileJump(detailPath.trim(), detailIdParam.trim(),
                StrUtil.isBlank(listPath) ? null : listPath.trim());
    }

  public static String resolveDetailPath(MobileJump jump, String bizId) {
        if (jump == null || StrUtil.isBlank(bizId)) {
            return null;
        }
        return jump.getDetailPath() + "?" + jump.getDetailIdParam() + "=" + encodeQueryValue(bizId.trim());
    }

    public static String resolveListPath(MobileJump jump) {
        return jump == null ? null : jump.getListPath();
    }

    private static String encodeQueryValue(String value) {
        try {
            return java.net.URLEncoder.encode(value, java.nio.charset.StandardCharsets.UTF_8);
        } catch (Exception ex) {
            return value;
        }
    }

    /**
     * 小程序跳转路径配置。
     */
    @Getter
    public static final class MobileJump {

        private final String detailPath;
        private final String detailIdParam;
        private final String listPath;

        public MobileJump(String detailPath, String detailIdParam, String listPath) {
            this.detailPath = detailPath;
            this.detailIdParam = detailIdParam;
            this.listPath = listPath;
        }
    }
}
