package com.liquidnet.common.third.xuper.dto;

import com.liquidnet.commons.lang.util.JsonUtils;

import java.io.Serializable;

/**
 * REDIRECT(-1),
 * SUCCESS(0),
 * FAIL(1),
 * UNAUTH(2),
 */
public class XuperResponseDto<T> implements Serializable, Cloneable {
    private static final long serialVersionUID = 8377276776600901982L;
    private String code;
    private String message;
    private T data;

    public boolean isSuccess() {
        return this.code.equals("0");
    }


    private XuperResponseDto() {
    }

    private XuperResponseDto(String code) {
        this.code = code;
    }

    private XuperResponseDto(String code, T data) {
        this.code = code;
        this.data = data;
    }

    private XuperResponseDto(String code, String message) {
        this.code = code;
        this.message = message;
    }

    private XuperResponseDto(String code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }
    public String getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }

    /**
     * <p>Getter for the field <code>data</code>.</p>
     *
     * @return a T object.
     */
    public T getData() {
        return data;
    }

    public static <Object> XuperResponseDto<Object> success() {
        return new XuperResponseDto<>("0");
    }

    public static <Object> XuperResponseDto<Object> success(Object data) {
        return new XuperResponseDto<>("0", data);
    }

    public static <Object> XuperResponseDto<Object> failure() {
        return new XuperResponseDto<>("1", "系统繁忙，请稍后再试");
    }

    public static <Object> XuperResponseDto<Object> failure(String message) {
        return new XuperResponseDto<>("1", message);
    }

    public static <Object> XuperResponseDto<Object> failure(String code, String message) {
        return new XuperResponseDto<>(code, message);
    }

    public static <Object> XuperResponseDto<Object> failure(String code, String message, Object data) {
        return new XuperResponseDto<>(code, message, data);
    }

    public <T> T getParseData(Class<T> clazz) {
        try {
            if (getData() != null) {
                return JsonUtils.fromJson(JsonUtils.toJson(getData()), clazz);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String toJson() {
        return JsonUtils.toJson(this);
    }
}
