package com.persagy.proxy.common.entity;

import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.lang.reflect.*;

/**
 * @description: 数据中台返回值通用类
 * @author: lgy
 * @since: 2021/08/11 15:40
 * @version: V1.0
 */
@Data
@NoArgsConstructor
@Slf4j
public class DmpResult<T> implements Serializable {

    /**
     * 成功
     */
    public final static String SUCCESS = "success";
    /**
     * 失败
     */
    public final static String FAILURE = "failure";

    private static final long serialVersionUID = 1L;

    private String result;

    private T data;

    private Integer count;

    private String message;

    public T getData(Class<T> clazz) {
        if (data == null) {
            T t = null;
            try {
                t = clazz.newInstance();
            } catch (Exception e) {
                log.error(e.getMessage(),e);
            }
            return t;
        }
        return data;
    }

    public T getData(T t) {
        if (data == null) {
            return t;
        }
        return data;
    }
    // type不能直接实例化对象，通过type获取class的类型，然后实例化对象
    public static Class<?> getRawType(Type type) {
        if (type instanceof Class) {
            return (Class) type;
        } else if (type instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) type;
            Type rawType = parameterizedType.getRawType();
            return (Class) rawType;
        } else if (type instanceof GenericArrayType) {
            Type componentType = ((GenericArrayType) type).getGenericComponentType();
            return Array.newInstance(getRawType(componentType), 0).getClass();
        } else if (type instanceof TypeVariable) {
            return Object.class;
        } else if (type instanceof WildcardType) {
            return getRawType(((WildcardType) type).getUpperBounds()[0]);
        } else {
            String className = type == null ? "null" : type.getClass().getName();
            throw new IllegalArgumentException("Expected a Class, ParameterizedType, or GenericArrayType, but <" + type + "> is of type " + className);
        }
    }

}
