package com.backendsys.utils.response;

import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.*;

import java.io.Serial;
import java.io.Serializable;

/**
 * 定义正常响应的API统一返回体
 * @param <T>
 */
//@Data
@NoArgsConstructor
@Getter
@Setter
@ToString
@SuppressWarnings("unchecked")
public class Result<T> implements Serializable {

    @Serial
    private static final long serialVersionUID = 4860612789969314413L;

    private int code;
    private String message;

    @JsonInclude(JsonInclude.Include.NON_NULL)
    private T data;

    //public Result() {}
    public Result(int code, String message) {
        this.code = code;
        this.message = message;
    }
    public Result(int code, String message, T data) {
        this.code = code;
        this.message = message;
        if (data != null) this.data = data;
    }

    /**
     * 成功
     */
    public static <T> Result<T> success(T data) {
        Result<T> result = new Result<T>();
        result.setCode(ResultEnum.SUCCESS.getCode());
        result.setMessage(ResultEnum.SUCCESS.getMessage());
        result.setData(data);
        return result;
    }
    public static <T> Result<T> success(T data, String message) {
        Result<T> result = new Result<T>();
        result.setCode(ResultEnum.SUCCESS.getCode());
        result.setMessage(message != null ? message : ResultEnum.SUCCESS.getMessage());
        result.setData(data);
        return result;
    }

    /**
     * 失败
     */
    public static <T> Result<T> error(int code, String message) {
        return new Result(code, message);
    }
    public static <T> Result<T> error(int code, String message, T data) {
        return data == null ? new Result(code, message) : new Result(code, message, data);
    }
}
