package com.nokia.common;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import org.slf4j.MDC;

/**
 * 返回值的统一包装
 */
@Data
public class R<T> {
    @Schema(description = "是否成功")
    private Boolean success;
    @Schema(description = "业务码")
    private Integer code;
    @Schema(description = "提示信息", example = "成功")
    private String message;
    @Schema(description = "数据")
    private T data = null;

    /**
     * 私有化构造方法,不允许在外部实例化
     */
    private R() {
    }

    /**
     * 成功的静态方法
     *
     * @return R实例
     */
    public static <T> R<T> ok() {
        R<T> r = new R<>();
        r.setSuccess(true);
        r.setCode(1);
        r.setMessage("成功");
        return r;
    }

    public static <T> R<T> ok(T data) {
        R<T> r = new R<>();
        r.setSuccess(true);
        r.setCode(1);
        r.setMessage("成功");
        r.setData(data);
        return r;
    }

    /**
     * 失败的静态方法
     *
     * @return R实例
     */
    public static <T> R<T> error() {
        R<T> r = new R<>();
        r.setSuccess(false);
        r.setCode(0);
        r.setMessage("失败" + MDC.get("traceId"));
        return r;
    }

    public static <T> R<T> error(String message) {
        R<T> r = new R<>();
        r.setSuccess(false);
        r.setCode(0);
        r.setMessage(message);
        return r;
    }

    public R<T> success(Boolean success) {
        this.setSuccess(success);
        return this;
    }


    public R<T> code(Integer code) {
        this.setCode(code);
        return this;
    }

    public R<T> data(T object) {
        this.setData(object);
        return this;
    }

    public R<T> message(String message) {
        this.setMessage(message);
        return this;
    }
}
