package com.xhpc.evcs.dto;

import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xhpc.evcs.utils.JSONUtil;
import org.apache.commons.lang3.builder.ToStringBuilder;

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

@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE,
        setterVisibility = JsonAutoDetect.Visibility.NONE, creatorVisibility = JsonAutoDetect.Visibility.NONE)
public class CommonResponse {

    public static final int SUCCESS = 0;
    public static final int FAILED = 1;
    @JsonProperty("Ret")
    String ret;
    @JsonProperty("Data")
    @JsonRawValue
    Object data;
    @JsonProperty("Msg")
    String msg = "";
    @JsonProperty("Sig")
    String sig;

    @JsonProperty("Ret")
    public String getRet() {

        return ret;
    }

    @JsonProperty("Ret")
    public void setRet(String ret) {

        this.ret = ret;
    }

    @JsonProperty("Data")
    public Object getData() {

        return data;
    }

    @JsonProperty("Data")
    public void setData(Object data) {

        this.data = data;
    }

    @JsonProperty("Msg")
    public String getMsg() {

        return msg;
    }

    @JsonProperty("Msg")
    public void setMsg(String msg) {

        this.msg = msg;
    }

    @JsonProperty("Sig")
    public String getSig() {

        return sig;
    }

    @JsonProperty("Sig")
    public void setSig(String sig) {

        this.sig = sig;
    }

    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    @JsonAnyGetter
    public Map<String, Object> getAdditionalProperties() {

        return this.additionalProperties;
    }

    @JsonAnySetter
    public void setAdditionalProperty(String name, Object value) {

        this.additionalProperties.put(name, value);
    }

    public Object anyDataTypeList(Class clz, String key) throws IOException {

        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode = mapper.readTree((String) data);
        jsonNode = jsonNode.path(key);
        return JSONUtil.readParamsList(jsonNode.toString(), clz);
    }

    public Object anyDataTypeList(Class clz) throws IOException {

        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode = mapper.readTree((String) data);
        return JSONUtil.readParamsList(jsonNode.toString(), clz);
    }

    public Object anyDataType(Class clz, String key) throws IOException {

        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode = mapper.readTree((String) data);
        jsonNode = jsonNode.path(key);
        return JSONUtil.readParams(jsonNode.toString(), clz);
    }

    @Override
    public String toString() {

        return new ToStringBuilder(this).append("Data", this.data).append("Msg", this.msg).append("Ret", this.ret).toString();
    }

}
