package cn.edu.whu.boot.common.domain;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.io.Serializable;

/**
 * 返回给前端的通用类
 */
public class ResultMessage<T> implements Serializable{

    private static final long serialVersionUID = -5295491166625639702L;

    /**
     * 是否成功标志
     */
    private boolean success;

    /**
     * 提示信息
     */
    private String message;

    /**
     * 封装数据
     */
    private T data;

    /**
     * 状态码
     */
    private int status;

    public ResultMessage(boolean success, String message){
        this.success = success;
        this.message = message;
    }

    public ResultMessage(boolean success, String message, T data){
        this(success, message, data, StatusCode.SUCCESS.getStatus());
    }

    public ResultMessage(boolean success, String message, int status){
        this(success, message, null, status);
    }

    public ResultMessage(boolean success, String message, T data, int status){
        this.success = success;
        this.message = message;
        this.data = data;
        this.status = status;
    }

    /**
     * 成功返回结果
     */
    public static <T> ResultMessage<T> success(T data) {
        return new ResultMessage<>(true, StatusCode.SUCCESS.getMessage(), data, StatusCode.SUCCESS.getStatus());
    }

    /**
     * 失败返回结果
     */
    public static <T> ResultMessage<T> failed(int status, String message) {
        return new ResultMessage<>(false, message, status);
    }

    /**
     * 失败返回结果
     */
    public static <T> ResultMessage<T> failed( String message) {
        return new ResultMessage<>(false, message, StatusCode.FAILED.getStatus());
    }

    public boolean isSuccess(){
        return success;
    }

    public void setSuccess(boolean success){
        this.success = success;
    }

    public String getMessage(){
        return message;
    }

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

    public T getData(){
        return data;
    }

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

    public int getStatus(){
        return status;
    }

    public void setStatus(int status){
        this.status = status;
    }

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

    /**
     * 关闭 fastJson 的循环引用
     */
    public String toStringByDisableCircularReference(){
        return JSON.toJSONString(this, SerializerFeature.DisableCircularReferenceDetect);
    }


}


