package com.agri.system.util;

import com.agri.system.domain.SysAgriInfo;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import java.net.URLEncoder;

/**
 * 对应前端 JS：
 * JSON.stringify() + encodeURIComponent()
 */
public class UrlEncodeUtil {

    /**
     * 【和你 JS 完全等价】生成跳转URL
     */
    public static String buildControlPageUrl(SysAgriInfo agriInfo, String linkUrl) {
        try {
            // 1. 构建和JS一模一样的JSON对象
            JSONObject agriObj = new JSONObject();
            agriObj.put("imei", agriInfo.getImei());
            agriObj.put("agriName", agriInfo.getAgriName());
            agriObj.put("agriId", agriInfo.getId());
            agriObj.put("workMode", agriInfo.getWorkMode());

            // 2. JSON.stringify
            String agriJson = JSON.toJSONString(agriObj);

            // 3. encodeURIComponent
            String agriInfoEncoded = URLEncoder.encode(agriJson, "UTF-8");

            // 4. 最终URL（和你JS跳转一模一样）
            return linkUrl + agriInfoEncoded;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // 通用版：任意对象转 encodeURIComponent 字符串
    public static String encodeUriComponent(Object obj) {
        try {
            String json = JSON.toJSONString(obj);
            return URLEncoder.encode(json, "UTF-8");
        } catch (Exception e) {
            return null;
        }
    }
}
