package com.ssyf.common.web.result;
import cn.hutool.core.util.StrUtil;
import com.ssyf.common.web.apicode.ApiCode;
import com.ssyf.common.web.apicode.IApiCode;
import lombok.Data;
import lombok.ToString;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 接口返回对象
 * @author huwei
 * @date 2022/7/5 10:02
 */
@Data
@ToString
@Accessors(chain = true)
public class Result<T> implements Serializable {
    /**
     * 返回编码，参见返回编码集
     */
    private String code;
    /**
     * 描述信息
     */
    private String msg;
    /**
     * 返回参数
     * 动态值，与接口相对应
     */
    private T data;

    /**
     * 静态工具
     */
    private Result() {
    }

    public static <T> Result success() {
        return success(null);
    }

    public static <T> Result success(T data) {
        return success(null ,data);
    }

    public static <T> Result success(String msg , T data) {
        return create(null ,msg ,data);
    }

    public static <T> Result successPage(List<T> list, long total, long current, long size) {
        Map<String, Object> res = new HashMap<>(8);
        res.put("records", list);
        res.put("total", total);
        res.put("current", current);
        res.put("size", size);
        return success(res);
    }

    public static Result fail(IApiCode apiCode){
        return fail(apiCode.getCode() , apiCode.getMessage());
    }

    public static Result fail(String code, String msg) {
        return fail(code, msg, null);
    }

    public static <T> Result fail(String code, String msg, T data) {
        return create(code ,msg ,data);
    }

    private static <T> Result create(String code , String msg , T data){
        code = StrUtil.isBlank(code) ? ApiCode.Ok.getCode() : code;
        msg = StrUtil.isBlank(msg) ? ApiCode.Ok.getMessage() : msg;
        return new Result().setCode(code).setMsg(msg).setData(data);
    }
}
