package com.zzwtec.wechat.rpc;

import com.alibaba.fastjson.JSONObject;
import com.zzwtec.wechat.common.ErrorMsg;

/**
 * ${DESCRIPTION}
 *
 * @author dengliaoyan
 * @create 2017/9/18
 */
public class APIResponse {
    private int code;
    private String msg;
    private String data;

    public APIResponse(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public APIResponse(int code, String msg, String data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public int getCode() {
        return code;
    }

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

    public String getMsg() {
        return msg;
    }

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

    public String getData() {
        return data;
    }

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

    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer("APIResponse{");
        sb.append("code=").append(code);
        sb.append(", msg='").append(msg).append('\'');
        sb.append(", data='").append(data).append('\'');
        sb.append('}');
        return sb.toString();
    }

    public boolean isSuccess() {
        return isSuccess(this);
    }

    public boolean isFail() {
        return isFail(this);
    }

    public static JSONObject toJSONObject(APIResponse response) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("error", response == null ? "1" : response.getCode());
        jsonObject.put("errormsg", response == null ? ErrorMsg._1 : response.getMsg());
        return jsonObject;
    }

    public static JSONObject toJSONObject(String code, String msg) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("error", code);
        jsonObject.put("errormsg", msg);
        return jsonObject;
    }

    public static boolean isSuccess(APIResponse response) {
        return response != null && response.getCode() == 0;
    }

    public static boolean isFail(APIResponse response) {
        return !isSuccess(response);
    }
}
