package cn.ibizlab.core.data.dto;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.springframework.lang.Nullable;

public class ResponseData<T> extends BaseData
{
	public ResponseData set(String key, Object value)
	{
		this.put(key,value);
		return this;
	}

	public Integer getCode() {
		return this.getIntegerValue("code",1);
	}

	public String getMessage() {
		return this.getStringValue("message",this.getStringValue("info",""));
	}

	public Boolean isSuccess() {
		return this.get("success")!=null&&this.get("success").equals(true);
	}


	@JsonIgnore
	@JSONField(serialize = false)
	public boolean isOk()
	{
		if(isSuccess()||getCode().equals("0"))
			return true;
		return false;
	}

	public ResponseData ok()
	{
		return this.set("success",true).set("code",0);
	}


	public ResponseData body(T data)
	{
		return this.set("data",data);
	}

	public T getBody()
	{
		if(this.get("data")!=null)
			return (T)this.get("data");
		else
			return null;
	}

	public ResponseData error(Integer code)
	{
		return this.set("success",false).set("code",code);
	}


	public ResponseData error(String info)
	{
		return this.set("success",false).set("code",this.getCode()).set("message",info);
	}

	public static <T> ResponseData<T> ok(@Nullable T body)
	{
		ResponseData<T> responseBody = new ResponseData<T>();
		return responseBody.ok().body(body);
	}

	public static ResponseData error(int code,String info)
	{
		ResponseData responseBody = new ResponseData();
		return responseBody.error(code).error(info);
	}

}
