package com.jisco.ymtappoint.http;

import org.springframework.util.Assert;

import java.util.Objects;

public class HttpResult {

    private long code;
    private String msg;
    private Object data;

    public static HttpResult error() {
        return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知异常，请联系管理员");
    }

    public static HttpResult error(String msg) {
        return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg);
    }

    public static HttpResult error(long code, String msg) {
        HttpResult r = new HttpResult();
        r.setCode(code);
        r.setMsg(msg);
        return r;
    }

    //下方法与返回结果字符串（业务数据）时冲突，易被错误引用
//    public static HttpResult ok(String msg) {
//        HttpResult r = new HttpResult();
//        r.setCode(0L);
//        r.setMsg(msg);
//        return r;
//    }

    public static HttpResult ok(Object data) {
        HttpResult r = new HttpResult();
        r.setCode(0L);
        r.setData(data);
        return r;
    }

    public static HttpResult okAndMsg(String msg) {
        HttpResult r = new HttpResult();
        r.setCode(0L);
        r.setMsg(msg);
        return r;
    }

    public static HttpResult ok(String msg, Object data) {
        HttpResult r = new HttpResult();
        r.setCode(0L);
        r.setMsg(msg);
        r.setData(data);
        return r;
    }

//    public static HttpResult ok() {
//        return new HttpResult();
//    }

    /*
   获取httpresult返回的结果，出错时报错，结果为空的不报错，由后续处理代码自行处理
   needCreateNullMsg:true,为空时报错，适用于获取结果不为空时直接转换，否则报错; false 为空时不报错，返回-适用于查询或自定义处理类场景
   customMsg：需报错时使用的自定义消息，如：查询XX、反馈XX
    */
    public static Object getHttpResultInfo(boolean needCreateNullMsg, String customMsg, HttpResult httpResult) {
        if (org.apache.commons.lang3.StringUtils.isBlank(customMsg)) customMsg = "接口调用";

        if (Objects.isNull(httpResult)) {
            if (needCreateNullMsg) {
                Assert.isTrue(false, customMsg + "未返回结果");
            } else return null;
        }

        Object data = null;
        if (httpResult.getCode() == 0L) {
            data = httpResult.getData();
        } else//远程报错时，必须报错
            Assert.isTrue(false, httpResult.getMsg());

        if (Objects.isNull(data)) {
            if (needCreateNullMsg) {
                Assert.isTrue(false, customMsg + "返回结果中的数据为空");
            } else return null;
        }

        //正常结果返回
        return data;
    }

    public long getCode() {
        return code;
    }

    public void setCode(long code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

}