package com.test.bijihoudaun.common.response;

import lombok.Data;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;

import java.io.Serializable;
import java.net.URI;

/**
 * 统一返回结果类
 * @param <T> 数据类型
 */
@Data
public class R<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    private Integer code; // 状态码
    private String msg;  // 消息
    private T data;      // 数据

    // 成功返回
    public static <T> R<T> success() {
        return success(null);
    }

    public static <T> R<T> success(T data) {
        R<T> r = new R<>();
        r.setCode(ResultCode.SUCCESS.getCode());
        r.setMsg(ResultCode.SUCCESS.getMsg());
        r.setData(data);
        return r;
    }

    // 分页成功返回
    public static <T> R<T> pageSuccess(long total, T data) {
        PageR<T> r = new PageR<>();
        r.setCode(ResultCode.SUCCESS.getCode());
        r.setMsg(ResultCode.SUCCESS.getMsg());
        r.setData(data);
        r.setTotal(total);
        return r;
    }

    // 失败返回
    public static <T> R<T> fail() {
        return fail(ResultCode.FAILED);
    }

    public static <T> R<T> fail(ResultCode resultCode) {
        return fail(resultCode.getCode(), resultCode.getMsg());
    }

    public static <T> R<T> fail(String msg) {
        return fail(ResultCode.FAILED.getCode(), msg);
    }

    public static <T> R<T> fail(Integer code, String msg) {
        R<T> r = new R<>();
        r.setCode(code);
        r.setMsg(msg);
        return r;
    }

    // 转换为ProblemDetail
    public static ProblemDetail toProblemDetail(ResultCode resultCode, HttpStatus status) {
        ProblemDetail problemDetail = ProblemDetail.forStatus(status);
        problemDetail.setType(URI.create("https://api.test.com/errors/" + resultCode.name().toLowerCase()));
        problemDetail.setTitle(resultCode.getMsg());
        problemDetail.setDetail(resultCode.getMsg());
        problemDetail.setProperty("code", resultCode.getCode());
        return problemDetail;
    }

    // 分页返回结果类
    private static class PageR<T> extends R<T> {
        private long total;

        public long getTotal() {
            return total;
        }

        public void setTotal(long total) {
            this.total = total;
        }
    }
}
