package yem.base.common.module.iscb.helper;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.ILocaleString;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import yem.base.common.utils.YEM;

import java.util.Map;
import java.util.stream.Collectors;

/**
 * 接口信息获取
 *
 * @author longh
 * @description
 * @date 2023年9月7日
 */
public class ApiHelper {
    private static final String KEY_APIAPP = "yem_base_app";
    private static final String KEY_API = "yem_base_api";
    private boolean exist;
    private String thirdKey;
    private ILocaleString thirdName;
    private Map<String, String> params;
    private Map<String, Api> apis;

    public ApiHelper(String thirdKey) {
        DynamicObject app = BusinessDataServiceHelper.loadSingleFromCache(KEY_APIAPP, new QFilter("number", QCP.equals, thirdKey).toArray());
        if (app != null) {
            this.params = app.getDynamicObjectCollection("yem_params").stream().collect(Collectors.toMap(x -> x.getString("yem_paramkey"), y -> y.getString("yem_paramvalue")));

            QFilter qFilter = new QFilter("group", QCP.equals, app.getPkValue());
            qFilter.and(new QFilter("enable", QCP.equals, "1"));
            Map<Object, DynamicObject> datas = BusinessDataServiceHelper.loadFromCache(KEY_API, qFilter.toArray());
            apis = datas.values().stream().filter(x -> YEM.isNotEmpty(x.getString("number"))).collect(Collectors.toMap(x -> x.getString("number"), Api::new));
            this.thirdName = app.getLocaleString("name");
            this.exist = true;
        }
        this.thirdKey = thirdKey;
    }

    public boolean isExist() {
        return exist;
    }

    public String getThirdKey() {
        return thirdKey;
    }

    public ILocaleString getThirdName() {
        return thirdName;
    }

    public Map<String, String> getParams() {
        return params;
    }

    public String getParam(String paramKey) {
        return params.getOrDefault(paramKey, "");
    }

    public Map<String, Api> getApis() {
        return apis;
    }

    public Api getApi(String apiKey) {
        return apis.getOrDefault(apiKey, new Api(null));
    }

    public ApiLog log(Api api) {
        return new ApiLog(api);
    }

}
