package com.xjrsoft.common.model.result;

import com.xjrsoft.common.enums.ResponseCode;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

/**
 * 返回数据
 */
public class RT<T> {
    /**
     * 返回码
     * 0 正常，其他异常
     */
    private int code = 0;

    private boolean success = true;

    /**
     * 描述
     */
    private String msg = "";

    /**
     * 结果数据
     */
    private T data;

    public int getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }

    public T getData() {
        return data;
    }

    public boolean getSuccess(){
        return success;
    }

    public static RT ok() {
        return new RT();
    }

    public static <T> RT<T> ok(T result) {
        RT<T> r = new RT<>();
        r.data = result;
        return r;
    }

    public static <T> RT<T> ok(String msg, T result) {
        RT<T> r = new RT<>();
        r.data = result;
        r.msg = msg;
        return r;
    }

    public static <T> RT<T> error() {
        return error(ResponseCode.INTERNAL_SERVER_ERROR.getCode(), "未知异常，请联系管理员");
    }

    public static <T> RT<T> error(String msg) {
        return error(ResponseCode.INTERNAL_SERVER_ERROR.getCode(), msg);
    }

    public static <T> RT<T> error(int code, String msg) {
        RT<T> r = new RT();
        r.code = code;
        r.msg = msg;
        return r;
    }

    public static ResponseEntity<byte[]> fileStream(byte[] bot, String fileName) {

        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        return new ResponseEntity<byte[]>(bot, headers, HttpStatus.OK);
    }
}
