package com.zzwtec.third.utils;

import com.alibaba.fastjson.JSONObject;
import com.zzwtec.third.common.RequestIdContext;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * create by Jomchen on 2018/11/30
 */
public class ResultObject<T> {

    private static Logger LOGGER = LoggerFactory.getLogger(ResultObject.class);

    public static final String SUCCESS_CODE = "0";
    public static final String SUCCESS_MSG = "success";
    public static final String ERROR_CODE = "1";
    public static final String ERROR_MSG = "error";

    private String requestId;

    private String code;

    private String msg;

    private T data;

    private ResultObject() {}

    public static ResultObject buildError() {
        return ResultObject.buildError(null, null);
    }

    public static ResultObject buildError(BizException e) {
        return ResultObject.buildError(String.valueOf(e.getCode()), e.getMessage());
    }

    public static ResultObject buildError(String code, String msg) {
        ResultObject result = new ResultObject();
        code = StringUtils.isEmpty(code) ? ERROR_CODE : code;
        msg = StringUtils.isEmpty(msg) ? ERROR_MSG : msg;
        result.setRequestId(RequestIdContext.getRequestId());
        result.setCode(code);
        result.setMsg(msg);
        return result;
    }

    public static boolean isOk(ResultObject<?> result) throws BizException {
        if (null == result) {
            LOGGER.warn("远程请求结果为空");
            throw new BizException(ErrorCode.ERROR_A_NEGATIVE);
        }
        if ( !result.getCode().equals(ResultObject.SUCCESS_CODE) ) {
            LOGGER.warn("远程请求业务错误：" + JSONObject.toJSONString(result));
            throw new BizException(Integer.parseInt(result.getCode()), result.getMsg());
        }
        return true;
    }

    public String getRequestId() {
        return requestId;
    }

    public void setRequestId(String requestId) {
        this.requestId = requestId;
    }

    public T getData() {
        return data;
    }

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

    public String getCode() {
        return code;
    }

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

    public String getMsg() {
        return msg;
    }

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

}
