package com.persagy.server.entities.response

import com.alibaba.fastjson.JSONArray
import lombok.NoArgsConstructor
import lombok.extern.slf4j.Slf4j
import java.lang.Exception
import lombok.Data
import java.io.Serializable
import java.lang.IllegalArgumentException
import java.lang.reflect.*
import java.lang.reflect.Array

/**
 * @description: 数据中台返回值通用类
 * @author: lgy
 * @since: 2021/08/11 15:40
 * @version: V1.0
 */
@Data
@NoArgsConstructor
@Slf4j
class DmpResult<T> : Serializable {
    val result: String? = null
    val data: T? = null
    val count: Int? = null
    val message: String? = null
    fun getData(clazz: Class<T>): T? {
        if (data == null) {
            var t: T? = null
            try {
                t = clazz.newInstance()
            } catch (e: Exception) {
                //DmpResult.log.error(e.message, e)
            }
            return t
        }
        return data
    }

    fun getData(t: T): T {
        return data ?: t
    }

    companion object {
        /**
         * 成功
         */
        const val SUCCESS = "success"

        /**
         * 失败
         */
        const val FAILURE = "failure"
        private const val serialVersionUID = 1L

        // type不能直接实例化对象，通过type获取class的类型，然后实例化对象
        fun getRawType(type: Type?): Class<*> {
            return if (type is Class<*>) {
                type
            } else if (type is ParameterizedType) {
                val rawType = type.rawType
                rawType as Class<*>
            } else if (type is GenericArrayType) {
                val componentType = type.genericComponentType
                Array.newInstance(getRawType(componentType), 0).javaClass
            } else if (type is TypeVariable<*>) {
                Any::class.java
            } else if (type is WildcardType) {
                getRawType(type.upperBounds[0])
            } else {
                val className = if (type == null) "null" else type.javaClass.name
                throw IllegalArgumentException("Expected a Class, ParameterizedType, or GenericArrayType, but <$type> is of type $className")
            }
        }
    }
}