package org.eco.common.core.core.domain;

import org.eco.common.core.constant.HttpStatus;
import lombok.Data;
import lombok.NoArgsConstructor;

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

/**
 * 通用响应信息
 *
 * @author wgk
 * @Date 2024/01.25
 */
@Data
@NoArgsConstructor
public class CommonResult<T> implements Serializable {
    /**
     * 成功
     */
    public static final int SUCCESS = HttpStatus.SUCCESS;

    /**
     * 成功
     */
    public static final String SUCCESS_MSG = HttpStatus.SUCCESS_MSG;

    /**
     * 失败
     */
    public static final int FAIL = HttpStatus.ERROR;
    /**
     * 失败
     */
    public static final String FAIL_MSG = HttpStatus.ERROR_MSG;


    @Serial
    private static final long serialVersionUID = 1L;
    private int code;

    private String msg;

    private T data;

    public static <T> CommonResult<T> success() {
        return restResult(null, SUCCESS, SUCCESS_MSG);
    }

    public static <T> CommonResult<T> success(T data) {
        return restResult(data, SUCCESS, SUCCESS_MSG);
    }

    public static <T> CommonResult<T> success(String msg) {
        return restResult(null, SUCCESS, msg);
    }

    public static <T> CommonResult<T> success(T data, String msg) {
        return restResult(data, SUCCESS, msg);
    }

    public static <T> CommonResult<T> fail() {
        return restResult(null, FAIL, FAIL_MSG);
    }

    public static <T> CommonResult<T> fail(String msg) {
        return restResult(null, FAIL, msg);
    }

    public static <T> CommonResult<T> fail(T data) {
        return restResult(data, FAIL, FAIL_MSG);
    }

    public static <T> CommonResult<T> fail(String msg, T data) {
        return restResult(data, FAIL, msg);
    }

    public static <T> CommonResult<T> fail(int code, String msg) {
        return restResult(null, code, msg);
    }

    /**
     * 返回警告消息
     *
     * @param msg 返回内容
     * @return 警告消息
     */
    public static <T> CommonResult<T> warn(String msg) {
        return restResult(null, HttpStatus.WARN, msg);
    }

    /**
     * 返回警告消息
     *
     * @param msg  返回内容
     * @param data 数据对象
     * @return 警告消息
     */
    public static <T> CommonResult<T> warn(String msg, T data) {
        return restResult(data, HttpStatus.WARN, msg);
    }

    private static <T> CommonResult<T> restResult(T data, int code, String msg) {
        CommonResult<T> apiResult = new CommonResult<>();
        apiResult.setCode(code);
        apiResult.setData(data);
        apiResult.setMsg(msg);
        return apiResult;
    }

    public static <T> Boolean isError(CommonResult<T> ret) {
        return !isSuccess(ret);
    }

    public static <T> Boolean isSuccess(CommonResult<T> ret) {
        return CommonResult.SUCCESS == ret.getCode();
    }
}
