package com.rehome.mqttclienttemperature.response;


import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

//统一返回数据结构
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result<T> {
    private Integer code;
    private String message;
    private T data;

    public static <T> Result<T> success(T data) {
        return new Result<>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMessage(), data);
    }

    public static <T> Result<T> success(String message, T data) {
        return new Result<>(ResultEnum.SUCCESS.getCode(), message, data);
    }

    public static Result<?> failed() {
        return new Result<>(ResultEnum.COMMON_FAILED.getCode(), ResultEnum.COMMON_FAILED.getMessage(), null);
    }

    public static Result<?> failedByParamValidated() {
        return new Result<>(ResultEnum.REQUEST_PARAM_VALIDATED_FAILED.getCode(), ResultEnum.REQUEST_PARAM_VALIDATED_FAILED.getMessage(), null);
    }

    public static Result<?> failedByParamValidated(BindingResult bindingResult) {
        Result result = new Result<>(ResultEnum.REQUEST_PARAM_VALIDATED_FAILED.getCode(), ResultEnum.REQUEST_PARAM_VALIDATED_FAILED.getMessage(), null);
        // 处理错误信息
        for (FieldError error : bindingResult.getFieldErrors()) {
            String baseErrorMessage = result.getMessage();
            if(error.getField()!=null){
                baseErrorMessage=baseErrorMessage+","+error.getField();
                result.setMessage(baseErrorMessage);
            }
            if(error.getDefaultMessage()!=null){
                baseErrorMessage=baseErrorMessage+":"+error.getDefaultMessage();
                result.setMessage(baseErrorMessage);
            }
        }
        return result;
    }

    public static Result<?> failed(String message) {
        return new Result<>(ResultEnum.COMMON_FAILED.getCode(), message, null);
    }

    public static Result<?> failed(IResult errorResult) {
        return new Result<>(errorResult.getCode(), errorResult.getMessage(), null);
    }

    public static <T> Result<T> instance(Integer code, String message, T data) {
        Result<T> result = new Result<>();
        result.setCode(code);
        result.setMessage(message);
        result.setData(data);
        return result;
    }
}

