package com.saye.hospitalgd.commons;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.Serializable;

/**
 * 用于封装AJAX调用以后的JSON返回值
 * 其中正确返回值:
 *  {state:0, data:返回数据, message:错误消息}
 * 错误返回值:
 *  {state:1, data:null, message:错误消息}
 **/
public class JsonResult implements Serializable {

    private static final long serialVersionUID = -3644950655568598241L;
    //定义jackson对象
    private static final ObjectMapper MAPPER = new ObjectMapper();


    /**
     * 返回是否成功的状态, 0表示成功,
     * 1或其他值 表示失败
     */
    private boolean state;
    /**
     * 成功时候,返回的JSON数据
     */
    private Object data;
    /**
     * 是错误时候的错误消息
     */
    private String message;


    public JsonResult() {
    }

    public JsonResult(boolean state, Object data, String message) {
        this.state = state;
        this.data = data;
        this.message = message;
    }

    public JsonResult(Throwable e){
        state = false;
        data=null;
        message=e.getMessage();
    }

    public JsonResult(Object data){
        state = true;
        this.data=data;
        message="";
    }

    public boolean isState() {
        return state;
    }

    public void setState(boolean state) {
        this.state = state;
    }

    public Object getData() {
        return data;
    }


    public void setData(Object data) {
        this.data = data;
    }


    public String getMessage() {
        return message;
    }


    public void setMessage(String message) {
        this.message = message;
    }

    public static String jsonResultSuccess(Object data, String message){
        JsonResult jsonResult=new JsonResult();
        jsonResult.setState(true);
        jsonResult.setMessage(message);
        jsonResult.setData(data);
        return ObjectToJson(jsonResult);
    }


    public static String jsonResultFalse(String message){
        JsonResult jsonResult=new JsonResult();
        jsonResult.setState(false);
        jsonResult.setMessage(message);
        return ObjectToJson(jsonResult);
    }

    /**
     * 将对象转化为json字符串
     * @param data
     * @return
     */
    public static String ObjectToJson(Object data){
        try{
            String string = MAPPER.writeValueAsString(data);
            return string;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String toString() {
        return "JsonResult [state=" + state + ", data=" + data + ", message=" + message + "]";
    }
}