package com.starry.common.result;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.beans.ConstructorProperties;
import java.io.Serializable;
import java.util.List;
import lombok.Data;

/**
 * Generic API response wrapper for better Swagger typing.
 */
@Data
@ApiModel(value = "统一返回结果（泛型）")
public class TypedR<T> implements Serializable {
    public static final String OK_MSG = "请求成功";
    public static final String FAIL_MSG = "请求失败";

    @ApiModelProperty(value = "是否成功")
    private boolean success;

    @ApiModelProperty(value = "返回码")
    private Integer code;

    @ApiModelProperty(value = "返回消息")
    private String message;

    @ApiModelProperty(value = "返回数据")
    private T data;

    @ApiModelProperty(value = "总条数")
    private Long total;

    @ApiModelProperty(value = "分页信息")
    private PageInfo pageInfo;

    public TypedR() {}

    private TypedR(int code, boolean success, String message, T data) {
        this.code = code;
        this.success = success;
        this.message = message;
        this.data = data;
    }

    public static <T> TypedR<T> ok(T data) {
        return new TypedR<>(ResultCodeEnum.SUCCESS.getCode(), true, ResultCodeEnum.SUCCESS.getMessage(), data);
    }

    public static <T> TypedR<T> okMessage(String msg, T data) {
        return new TypedR<>(ResultCodeEnum.SUCCESS.getCode(), true, msg, data);
    }

    /**
     * Build a list response from MyBatis-Plus page while flattening records/total/pageInfo.
     */
    public static <T> TypedR<List<T>> okPage(IPage<T> page) {
        TypedR<List<T>> r = new TypedR<>(ResultCodeEnum.SUCCESS.getCode(), true,
                ResultCodeEnum.SUCCESS.getMessage(), page.getRecords());
        r.setTotal(page.getTotal());
        r.setPageInfo(new PageInfo((int) page.getCurrent(), (int) page.getSize(), page.getTotal(), page.getPages()));
        return r;
    }

    public static <T> TypedR<T> error(String msg) {
        return new TypedR<>(ResultCodeEnum.FAILED.getCode(), false, msg, null);
    }

    public static <T> TypedR<T> error(int errorCode, String msg) {
        return new TypedR<>(errorCode, false, msg, null);
    }

    @Data
    public static class PageInfo {
        @ApiModelProperty("当前页")
        protected int currentPage;
        @ApiModelProperty("页大小")
        protected int pageSize;
        @ApiModelProperty("总记录数")
        protected long totalCount;
        @ApiModelProperty("总页数")
        protected long totalPage;

        public PageInfo() {}

        @ConstructorProperties({"currentPage", "pageSize", "totalCount", "totalPage"})
        public PageInfo(int currentPage, int pageSize, long totalCount, long totalPage) {
            this.currentPage = currentPage;
            this.pageSize = pageSize;
            this.totalCount = totalCount;
            this.totalPage = totalPage;
        }
    }
}
