package com.njcn.event.utils;

import net.sf.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author hongawen
 * @version 1.0.0
 * @date 2022年08月23日 19:33
 */
public class EchartsUtil {
    private static final String SUCCESS_CODE = "1";

    public static String generateEchartsBase64(String option, String port) throws IOException {
        String url;
        if (port.equals("8911")) {
            url = "http://192.168.1.13:8911";
        } else {
            url = "http://192.168.1.13:8910";
        }

        String base64 = "";
        if (option == null) {
            return base64;
        }

        option = option.replaceAll("\\s+", "").replaceAll("\"", "'");

        // 将option字符串作为参数发送给echartsConvert服务器
        Map<String, String> params = new HashMap<>();
        params.put("opt", option);
        String response = HttpUtil.post(url, params, "utf-8");

        // 解析echartsConvert响应
        JSONObject responseJson = JSONObject.fromObject(response);
        String code = responseJson.getString("code");

        // 如果echartsConvert正常返回
        if (SUCCESS_CODE.equals(code)) {
            base64 = responseJson.getString("data");
        }
        // 未正常返回
        else {
            String string = responseJson.getString("msg");
            throw new RuntimeException(string);
        }
        return base64;
    }
}
