package com.brilliance.isc.esb.model;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class ComposeRes extends AbsRes {
    /**
     * 正常报文体
     */
    public List<Object> CONTENT;
    /**
     * 错误报文体
     */
    public ErrorData DATA;

    @JsonIgnore
    @JSONField(serialize = false)
    private Set<Object> used = new HashSet<>();

    @JsonIgnore
    @JSONField(serialize = false)
    public Object getData(String name) {
        for (int i = 0; i < CONTENT.size(); i++) {
            Object item = CONTENT.get(i);
            if (used.add(item)) {
                JSONObject itemJsonObject;
                if (item instanceof Map) {
                    itemJsonObject = JSONObject.parseObject(JSON.toJSONString(item));
                } else {
                    itemJsonObject = (JSONObject) item;
                }

                JSONObject datajson = (JSONObject) itemJsonObject.get("DATA");
                try {
                    return datajson.to(Class.forName(name));
                } catch (ClassNotFoundException e) {
                    used.remove(item);
                }
            }
        }
        return null;
    }

    public void reset() {
        used = new HashSet<>();
    }

    @JsonIgnore
    @JSONField(serialize = false)
    public String getErrorCode() {
        if (DATA != null) {
            if (DATA.ERR000 != null && DATA.ERR000.ERRORCODE != null && !"".equals(DATA.ERR000.ERRORCODE)) {
                return DATA.ERR000.ERRORCODE;
            }
        }
        return RETPUBLICHEADER.PTCWDH;
    }

    @JsonIgnore
    @JSONField(serialize = false)
    public String getErrorMsg() {
        if (DATA != null) {
            if (DATA.ERR000 != null && DATA.ERR000.ERRORMSG != null) {
                return DATA.ERR000.ERRORMSG;
            }
        }
        return "";
    }
}
