package cn.common.interaction.resp.base;


import cn.common.common.enums.ErrorCode;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;

import java.io.Serializable;
import java.time.Clock;
import java.time.Instant;
import java.time.LocalDateTime;

/**
 * Api请求返回实体
 * @author created by Singer email:singer-coder@qq.com
 * @time 2018/9/29
 * @description
 */
@Data
public class ApiResponse<E> implements Serializable {

    private static final long serialVersionUID = -8099598967725340002L;

    /**
     * 请求序列号
     */
    private String requestSeqNo;

    /**
     * 错误码
     */
    private String code;

    /**
     * 错误信息
     */
    private String message;

    /**
     * 是否成功
     */
    private Boolean success = Boolean.FALSE;

    /**
     * 接口返回时间
     */
    @JSONField(format="yyyy-MM-dd HH:mm:ss")
    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    private LocalDateTime responseTime = LocalDateTime.ofInstant(Instant.now(), Clock.systemDefaultZone().getZone());

    /**
     * 接口响应时间
     */
    private String spendTime;

    /**
     * 返回的数据
     */
    private E data;

    public ApiResponse() {
    }

    public ApiResponse(String requestSeqNo,
                       String code,
                       String message,
                       Boolean success,
                       E data) {
        this.requestSeqNo = requestSeqNo;
        this.code = code;
        this.message = message;
        this.data = data;
        this.success = success;
    }

    public static ApiResponse error() {
        return error(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()), "未知异常，请联系管理员");
    }

    public static ApiResponse error(String msg) {
        return error(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()), msg);
    }

    public static ApiResponse error(String code, String msg) {
        ApiResponse r = new ApiResponse();
        r.setCode(code);
        r.setMessage(msg);
        r.setSuccess(false);
        return r;
    }

    public static ApiResponse success() {
        ApiResponse r = new ApiResponse();
        r.setCode(ErrorCode.SUCCESS.getCode());
        r.setMessage(ErrorCode.SUCCESS.getMessage());
        r.setSuccess(false);
        return r;
    }

    public static ApiResponse unSuccess(ErrorCode errorCode) {
        ApiResponse r = new ApiResponse();
        r.setCode(errorCode.getCode());
        r.setMessage(errorCode.getMessage());
        r.setSuccess(false);
        return r;
    }

    public static ApiResponse ok(Object data) {
        ApiResponse r = new ApiResponse();
        r.setMessage("操作成功");
        r.setData(data);
        r.setSuccess(false);
        return r;
    }

}
