package com.yaoyicloud.utils;


import cn.hutool.core.date.DatePattern;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yaoyicloud.constant.CommonConstants;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 响应信息主体
 *
 * @author jimmy
 * @version 1.0.0
 * @date 2023-12-11 13:26
 */
@SuppressWarnings("checkstyle:JavadocType")
@Getter
@Builder
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class RespResult<T> implements Serializable {

    private static final long serialVersionUID = -2762015630844641571L;

    @Setter
    private String code;

    @Setter
    private String msg;

    @Getter
    @JsonFormat(pattern = DatePattern.NORM_DATETIME_PATTERN)
    private final LocalDateTime timestamp = LocalDateTime.now();

    @Setter
    private T data;

    public static <T> RespResult<T> ok() {
        return restResult(null, CommonConstants.SUCCESS, CommonConstants.SUCCESS_MSG);
    }

    public static <T> RespResult<T> ok(T data) {
        return restResult(data, CommonConstants.SUCCESS, CommonConstants.SUCCESS_MSG);
    }

    public static <T> RespResult<T> ok(T data, String msg) {
        return restResult(data, CommonConstants.SUCCESS, msg);
    }

    public static <T> RespResult<T> failed() {
        return restResult(null, CommonConstants.FAIL, CommonConstants.FAIL_MSG);
    }

    public static <T> RespResult<T> failed(String msg) {
        return restResult(null, CommonConstants.FAIL, msg);
    }

    public static <T> RespResult<T> failed(T data) {
        return restResult(data, CommonConstants.FAIL, CommonConstants.FAIL_MSG);
    }

    public static <T> RespResult<T> failed(T data, String msg) {
        return restResult(data, CommonConstants.FAIL, msg);
    }

    public static <T> RespResult<T> failed(String code, String msg) {
        return restResult(null, code, msg);
    }

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

    public boolean isOk() {
        return Objects.equals(this.code, CommonConstants.SUCCESS);
    }

}
