package net.northking.cctp.common.http;


import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import net.northking.cctp.common.exception.PlatformError;

import java.io.Serializable;
import java.util.Date;

/**
 * HTTP接口统一应答载体
 * @author xiusong.xie
 * @since 1.0
 */
@ApiModel(description = "HTTP接口统一应答载体")
public class ResultWrapper<T> implements Serializable
{

  @ApiModelProperty("交易是否成功")
  private boolean success = false;

  @ApiModelProperty("应答代码")
  private String code;

  @ApiModelProperty("报错信息")
  private String message;

  @ApiModelProperty("时间戳")
  private Long timestamp = new Date().getTime();

  public String getCode()
  {
    return code;
  }

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

  public String getMessage()
  {
    return message;
  }

  public void setMessage(String message)
  {
    this.message = message;
  }

  @ApiModelProperty("应答数据")
  private T data;

  public T getData()
  {
    return data;
  }

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

  public boolean isSuccess()
  {
    return success;
  }

  public void setSuccess(boolean success)
  {
    this.success = success;
  }

  public long getTimestamp()
  {
    return timestamp;
  }

  public void setTimestamp(long timestamp)
  {
    this.timestamp = timestamp;
  }

  /**
   * 成功且无返回数据
   *
   * @return 接口返回对象
   */
  public ResultWrapper<T> success()
  {
    this.setSuccess(true);
    this.setCode(ResultCodeEnum.SUCCESS.getCode());
    this.setMessage(ResultCodeEnum.SUCCESS.getMessage());
    return this;
  }

  /**
   * 成功
   *
   * @param data 返回的数据
   * @return 接口返回对象
   */
  public ResultWrapper<T> success(T data)
  {
    this.setData(data);
    return this.success();
  }

  /**
   * 失败
   *
   * @param code  返回码
   * @param error 错误信息
   * @return 接口返回对象
   */
  public ResultWrapper<T> fail(String code, String error)
  {
    this.setSuccess(false);
    this.code = code;
    this.message = error;

    if (this.code == null || "".equals(this.code))
    {
      this.code = ResultCodeEnum.FAIL.getCode();
    }
    if (this.message == null || "".equals(this.message))
    {
      this.message = ResultCodeEnum.FAIL.getMessage();
    }
    return this;
  }

  /**
   * 失敗
   *
   * @param code  返回码
   * @param error 错误信息
   * @param data  返回的数据
   * @return 接口返回对象
   */
  public ResultWrapper<T> fail(String code, String error, T data)
  {
    this.setData(data);
    return fail(code, error);
  }

  /**
   * 失败
   *
   * @param platformError 错误信息
   * @return 接口返回对象
   */
  public ResultWrapper<T> fail(PlatformError platformError)
  {
    return fail(platformError.getCode() + "", platformError.getMsg());
  }

  /**
   * 失败，请求的数据不存在
   *
   * @return 接口返回对象
   */
  public ResultWrapper<T> failNothingness()
  {
    return fail("900001", "请求的数据不存在");
  }

}