package cn.qg.qaplatform.common;

import cn.qg.qaplatform.common.enums.ErrorType;
import lombok.Data;

/**
 * 统一返回的json格式
 */
@Data
public class JsonResult<T> {
    private Long code = ErrorType.SUCCESS.getCode();
    private String msg = ErrorType.SUCCESS.getMessage();
    private T data;
    private Long timestamp;

    private JsonResult() {
        this.timestamp = System.currentTimeMillis();
    }

    private JsonResult(ErrorType errorType, String msg, T data) {
        this();
        this.code = errorType.getCode();
        this.msg = msg;
        this.data = data;
    }

    /**
     * 成功
     */
    public static <T> JsonResult<T> success() {
        return buildResult(ErrorType.SUCCESS);
    }

    public static <T> JsonResult<T> success(T data) {
        return buildResult(ErrorType.SUCCESS, ErrorType.SUCCESS.getMessage(), data);
    }

    /**
     * 客户端失败
     */
    public static <T> JsonResult<T> clientFailed() {
        return buildResult(ErrorType.CLIENT_FAILED);
    }

    public static <T> JsonResult<T> clientFailed(T data) {
        return buildResult(ErrorType.CLIENT_FAILED, ErrorType.CLIENT_FAILED.getMessage(), data);
    }

    /**
     * 服务器失败
     */
    public static <T> JsonResult<T> serverFailed() {
        return buildResult(ErrorType.SERVER_FAILED);
    }

    public static <T> JsonResult<T> serverFailed(T data) {
        return buildResult(ErrorType.SERVER_FAILED, ErrorType.SERVER_FAILED.getMessage(), data);
    }

    /**
     * 构建data为null的响应结果
     */
    public static <T> JsonResult<T> buildResult(ErrorType errorType) {
        return new JsonResult<T>(errorType, errorType.getMessage(), null);
    }

    /**
     * 构建带data的响应接口
     */
    public static <T> JsonResult<T> buildResult(ErrorType errorType, String msg, T data) {
        return new JsonResult<T>(errorType, msg, data);
    }
}

