package xtools.boot.elasticsearch.monitor;

import com.alibaba.fastjson2.JSONObject;
import org.springframework.stereotype.Component;
import xtools.base.config.BaseParams;
import xtools.boot.api.exection.BizError;
import xtools.boot.elasticsearch.enums.ElasticsearchMonitorEnums;
import xtools.boot.elasticsearch.utils.EsUtils;
import xtools.core.ArrUtils;
import xtools.core.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>Title : ElasticsearchMonitor</p>
 * <p>Description : ElasticsearchMonitor</p>
 * <p>DevelopTools : Idea_x64_v2026.1</p>
 * <p>DevelopSystem : macOS Sequoia 15.7.5</p>
 * <p>Company : org.xujun</p>
 *
 * @author : XuJun
 * @version : 5.0.0
 * @date : 2026/2/14 17:58
 */
@Component
public class ElasticsearchMonitor implements BaseParams {

    /**
     * 获取Elasticsearch监控信息
     *
     * @param type 枚举
     * @return Elasticsearch监控信息
     */
    public JSONObject info(ElasticsearchMonitorEnums type) {
        if (Objects.isNull(type)) {
            throw new BizError("类型参数不能为空");
        }
        // 查询
        String result;
        try {
            result = EsUtils.exec(type.cmd(), null, String.class, true);
        } catch (Exception e) {
            throw new BizError("查询异常");
        }
        // 处理数据
        result = result.replaceAll("\n", "###").replaceAll("\\s+", " ");
        List<String> arr = ArrUtils.toStringList(result, "###");
        if (CollectionUtils.isEmpty(arr)) {
            throw new BizError("类型参数不能为空");
        }
        // 封装表头
        List<String> titleList = ArrUtils.toStringList(arr.getFirst(), " ");
        // 处理主体数据
        List<JSONObject> dataList = new ArrayList<>();
        for (int i = CP_NUM1; i < arr.size(); i++) {
            String line = arr.get(i);
            List<String> data = ArrUtils.toStringList(line, " ");
            JSONObject lineData = new JSONObject();
            for (int j = CP_NUM0; j < data.size(); j++) {
                lineData.put(titleList.get(j), data.get(j));
            }
            dataList.add(lineData);
        }
        return JSONObject.of("title", titleList, "dataList", dataList);
    }

}
