package com.video.model.utils;

import common.result.ResponseStatusEnum;

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

/**
 * @Author: codingliang
 * @Description: 接口统一返回
 * @Date: 2021-04-29 12:10
 * @Version: V1.0
 **/
public class CommonResult<T> extends BaseResult implements Serializable {

    private static final long serialVersionUID = 3616484754899974346L;

    public static CommonResult ok() {
        return ok("1", "执行成功");
    }

    public static <T> CommonResult<T> ok(String code, String msg) {
        return baseCreate(code, msg, true);
    }

    public static CommonResult fail() {
        return fail("-1", "执行失败");
    }

    public static CommonResult fail(String code, String msg) {
        return baseCreate(code, msg, false);
    }

    public CommonResult(){}

    private static <T> CommonResult<T> baseCreate(String code, String msg, boolean success) {
        CommonResult result = new CommonResult();
        result.setCode(code);
        result.setSuccess(success);
        result.setMessage(msg);
        return result;
    }

    public CommonResult(T data) {
        this.setCode(Integer.toString(ResponseStatusEnum.SUCCESS.status()));
        this.setMessage(ResponseStatusEnum.SUCCESS.msg());
        this.setSuccess(ResponseStatusEnum.SUCCESS.success());
        this.setData(data);
    }

    public static CommonResult exception(ResponseStatusEnum responseStatus) {
        return new CommonResult(responseStatus);
    }

    /**
     * 错误返回，map中包含了多条错误信息，可以用于表单验证，把错误统一的全部返回出去
     * @param map
     * @return
     */
    public static CommonResult errorMap(Map map) {
        return new CommonResult(ResponseStatusEnum.FAILED, map);
    }

    public CommonResult(ResponseStatusEnum responseStatus, T data) {
        this.setCode(Integer.toString(responseStatus.status()));
        this.setMessage(responseStatus.msg());
        this.setSuccess(responseStatus.success());
        this.setData(data);
    }

    /**
     * 错误返回，直接返回错误的消息
     * @param msg
     * @return
     */
    public static CommonResult errorMsg(String msg) {
        return new CommonResult(ResponseStatusEnum.FAILED, msg);
    }

    public CommonResult<T> setResult(T data) {
        this.setData(data);
        return this;
    }

    public T getData() {
        return (T) super.getData();
    }
}
