package com.jiayue.ssi.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.jiayue.ssi.backenum.ResponseEnum;
import lombok.*;
import lombok.experimental.Accessors;

import java.io.Serializable;

/**
 * 数据格式返回统一
 *
 * @author zzy
 * @version 1.0
 * @since 2019/5/10 16:34
 */
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ResponseVO<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 状态码
     */
    @Getter
    @Setter
    private Integer code;

    /**
     * 描述
     */
    @Getter
    @Setter
    private String message;

    /**
     * 数据
     */
    @Getter
    @Setter
    private T data;

    public static <T> ResponseVO<T> success() {
        return restResult(ResponseEnum.SUCCESS.getCode(), null, null);
    }

    public static <T> ResponseVO<T> success(T data) {
        return restResult(ResponseEnum.SUCCESS.getCode(), data, ResponseEnum.SUCCESS.getMessage());
    }

    public static <T> ResponseVO<T> success(T data, String message) {
        return restResult(ResponseEnum.SUCCESS.getCode(), data, message);
    }

    public static <T> ResponseVO<T> fail() {
        return restResult(ResponseEnum.FAILED.getCode(), null, null);
    }

    public static <T> ResponseVO<T> fail(T data) {
        return restResult(ResponseEnum.FAILED.getCode(), data, ResponseEnum.FAILED.getMessage());
    }

    public static <T> ResponseVO<T> fail(T data, String msg) {
        return restResult(ResponseEnum.FAILED.getCode(), data, msg);
    }

    public static ResponseVO fail(Exception exception) {
        return restResult(ResponseEnum.FAILED.getCode(), null, exception.getMessage());
    }

    public static ResponseVO error(Throwable exception) {
        return restResult(ResponseEnum.ERROR.getCode(), null, exception.getMessage());
    }

    private static <T> ResponseVO<T> restResult(Integer code, T data, String message) {
        ResponseVO<T> apiResult = new ResponseVO<>();
        apiResult.setCode(code);
        apiResult.setData(data);
        apiResult.setMessage(message);
        return apiResult;
    }
}
