package com.yunniu.farming.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.List;

public class ReturnResult {
	
	private int code;
	private String msg;
	private Object data;
	
	public ReturnResult() {
		super();
	}
	
	public ReturnResult(int code) {
		super();
		this.code = code;
	}

	public ReturnResult(int code, String msg) {
		super();
		this.code = code;
		this.msg = msg;
	}

	public ReturnResult(int code, String msg, Object data) {
		super();
		this.code = code;
		this.msg = msg;
		this.data = data;

	}
	
	public static ReturnResult get(){
		return getSuccessResult();
	}
	
	public static ReturnResult getSuccessResult(){
		return new ReturnResult(StatusCode.SUCCESS_CODE, StatusCode.SUCCESS_DESC);
	}

	public static ReturnResult getSuccessResult(Object data){
        return new ReturnResult(StatusCode.SUCCESS_CODE, StatusCode.SUCCESS_DESC, data);
    }
	
	public static ReturnResult getErrorResult(){
		return new ReturnResult(StatusCode.ERROR_CODE, StatusCode.ERROR_DESC);
	}

    public static ReturnResult getErrorResult(int errorcode){
        return new ReturnResult(StatusCode.ERROR_CODE, StatusCode.ERROR_DESC);
    }

	public static ReturnResult getErrorResult(String errordesc){
		return new ReturnResult(StatusCode.ERROR_CODE, errordesc);
	}
	
	public static ReturnResult getEmptyResult(){
		return new ReturnResult(StatusCode.EMPTY_CODE, StatusCode.EMPTY_DESC);
	}
	

	public int getCode() {
		return code;
	}
	public void setCode(int code) {
		this.code = code;
	}
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
	public Object getData() {
		return data;
	}
	public void setData(Object data) {
		this.data = data;
	}
	
    public <T> List<T> getList(Class<T> clazz) {
        String json = JSONObject.toJSONString(data);
        if(json==null || json=="") return null;
        return JSONArray.parseArray(json, clazz);
    }

    public <T> T getData(Class<T> clazz) {
        String json = JSONObject.toJSONString(data);
        if(json==null || json=="") return null;
        return (T) JSON.parseObject(json, clazz);
    }

    @Override
    public String toString(){
        return JSONObject.toJSONString(this);
    }
}
