package com.sonic.common.rpc;

import com.alibaba.fastjson.annotation.JSONField;

import com.sonic.common.utils.LogUtils;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;

/**
 * @author code
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Result<T> {
    private T content;
    private Status status;
    /** 异常错误码, 7位 */
    private String errorCode;
    private String errorMsg;
    private String traceId;

    @JSONField(serialize = false)
    public boolean isSuccess() {
        return Status.OK == this.status;
    }

    public static Result success() {
        return Result.builder()
                .status(Status.OK)
                .build();
    }

    public static <T> Result success(T content) {
        return Result.builder()
                .status(Status.OK)
                .content(content)
                .build();
    }

    public static Result error(ApiResultCode resultCode) {
        return Result.builder()
                .status(Status.ERROR)
                .traceId(LogUtils.getTraceId())
                .content(resultCode.getErrorCode())
                .errorMsg(resultCode.getErrorMsg())
                .build();
    }

    public static Result error(ApiResultCode resultCode, String customErrorMsg) {
        return Result.builder()
                .status(Status.ERROR)
                .errorCode(resultCode.getErrorCode())
                .errorMsg(customErrorMsg)
                .traceId(LogUtils.getTraceId())
                .build();
    }

    public static Result error(String errorCode, String errorMsg) {
        return Result.builder()
                .status(Status.ERROR)
                .traceId(LogUtils.getTraceId())
                .errorCode(errorCode)
                .errorMsg(errorMsg)
                .build();
    }

    @Override
    public Result clone() {
        return Result.builder()
                .status(status)
                .content(content)
                .errorCode(errorCode)
                .errorMsg(errorMsg)
                .build();
    }

    @Getter
    public static enum Status {
        /** 接口返回状态 */
        OK,
        ERROR,
        ;
    }


}
