package com.shkj.common.core.domain;

import cn.hutool.core.util.StrUtil;
import com.shkj.common.enums.HttpStatus;
import com.shkj.common.exception.base.BaseException;
import com.shkj.common.utils.MessageUtils;
import com.shkj.common.utils.StringUtils;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * 通用请求响应结构体
 *
 * @Author Jun
 * @date 2020年11月18日 下午6:31:48
 */
@Data
@NoArgsConstructor
public class Result<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 状态码
     */
    private int code;

    /**
     * 返回信息
     */
    private String msg = "";



    private Boolean result=false;


    /**
     * 数据对象
     */
    private T data;

    public Result(int code) {
        super();
        this.code = code;
    }
    public Result(int code,Boolean result) {
        super();
        this.code = code;
        this.result=result;
    }

    public Result i18n(String key, Object... args) {
        this.msg = MessageUtils.message(key, args);
        return this;
    }

    public Result msg(String msg) {
        this.msg = MessageUtils.message(msg);
        return this;
    }

    public Result msg(String msg, Object... params) {
        this.msg = MessageUtils.message(msg, params);
        return this;
    }

    public Result data(T data) {
        this.data = data;
        return this;
    }
    public Boolean getResult() {
        return result;
    }

    public void setResult(Boolean result) {
        this.result = result;
    }

    public static Result ok() {
        return new Result(HttpStatus.SUCCESS.getCode());
    }

    public static Result err(int code) {
        return new Result(code);
    }
    public static Result err(int code,Boolean result) {
        return new Result(code,result);
    }

    public static Result err() {
        return err(HttpStatus.ERROR.getCode());
    }

    public static Result err(BaseException e) {
        Integer code = HttpStatus.ERROR.getCode();
        if (StringUtils.isNoneBlank(e.getCode())) {
            code = Integer.parseInt(e.getCode());
        }
        return err(code).msg(e.getMessage());
    }

    public static Result err(Exception e) {
        return err().msg(e.getMessage());
    }

    public static Result err(HttpStatus httpStatus) {
        return err(httpStatus.getCode()).msg(httpStatus.getMessage());
    }

    public static Boolean isOk(Result result) {
        if (result.getCode() == Result.ok().getCode()) {
            return true;
        }
        return false;
    }

}
