/*
 * Copyright (c) 2020 pig4cloud Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.chushang.common.core.util;

import cn.hutool.core.collection.CollectionUtil;
import com.chushang.common.core.constant.Constants;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.BridgeMethodResolver;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.MethodParameter;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.SynthesizingMethodParameter;
import org.springframework.web.method.HandlerMethod;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Set;

/**
 * 类工具类
 *
 * @author L.cm
 */
@Slf4j
@UtilityClass
public class ClassUtils extends org.springframework.util.ClassUtils {

	private final ParameterNameDiscoverer PARAMETERNAMEDISCOVERER = new DefaultParameterNameDiscoverer();

	/**
	 * 获取方法参数信息
	 * @param constructor 构造器
	 * @param parameterIndex 参数序号
	 * @return {MethodParameter}
	 */
	public MethodParameter getMethodParameter(Constructor<?> constructor, int parameterIndex) {
		MethodParameter methodParameter = new SynthesizingMethodParameter(constructor, parameterIndex);
		methodParameter.initParameterNameDiscovery(PARAMETERNAMEDISCOVERER);
		return methodParameter;
	}

	/**
	 * 获取方法参数信息
	 * @param method 方法
	 * @param parameterIndex 参数序号
	 * @return {MethodParameter}
	 */
	public MethodParameter getMethodParameter(Method method, int parameterIndex) {
		MethodParameter methodParameter = new SynthesizingMethodParameter(method, parameterIndex);
		methodParameter.initParameterNameDiscovery(PARAMETERNAMEDISCOVERER);
		return methodParameter;
	}

	/**
	 * 获取Annotation
	 * @param method Method
	 * @param annotationType 注解类
	 * @param <A> 泛型标记
	 * @return {Annotation}
	 */
	public <A extends Annotation> A getAnnotation(Method method, Class<A> annotationType) {
		Class<?> targetClass = method.getDeclaringClass();
		// The method may be on an interface, but we need attributes from the target
		// class.
		// If the target class is null, the method will be unchanged.
		Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
		// If we are dealing with method with generic parameters, find the original
		// method.
		specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
		// 先找方法，再找方法上的类
		A annotation = AnnotatedElementUtils.findMergedAnnotation(specificMethod, annotationType);

		if (null != annotation) {
			return annotation;
		}
		// 获取类上面的Annotation，可能包含组合注解，故采用spring的工具类
		return AnnotatedElementUtils.findMergedAnnotation(specificMethod.getDeclaringClass(), annotationType);
	}

	/**
	 * 获取Annotation
	 * @param handlerMethod HandlerMethod
	 * @param annotationType 注解类
	 * @param <A> 泛型标记
	 * @return {Annotation}
	 */
	public <A extends Annotation> A getAnnotation(HandlerMethod handlerMethod, Class<A> annotationType) {
		// 先找方法，再找方法上的类
		A annotation = handlerMethod.getMethodAnnotation(annotationType);
		if (null != annotation) {
			return annotation;
		}
		// 获取类上面的Annotation，可能包含组合注解，故采用spring的工具类
		Class<?> beanType = handlerMethod.getBeanType();
		return AnnotatedElementUtils.findMergedAnnotation(beanType, annotationType);
	}
	public  boolean objCheckNonNull(Object object)
	{
		if (null == object){
			return false;
		}
		// 默认忽略 序列化
		return objCheckNonNull(object, Set.of(Constants.SERIAL_VERSION_STR));
	}

	/**
	 * 只要有一个 非null 值即为 true
	 */
	public boolean objCheckNonNull(Object object, Set<String> ignoreFieldNames)
	{
		Class<?> clazz = object.getClass();
		Field[] fields = clazz.getDeclaredFields();
		boolean flag = false;
		for(Field field : fields){
			field.setAccessible(true);
			Object fieldValue = null;
			try {
				String fieldName = field.getName();
				if (CollectionUtil.isNotEmpty(ignoreFieldNames)){
					// 要求 fieldName 必须一致, 大小写不同, 视为不同
					if (ignoreFieldNames.contains(fieldName))
						continue;
				}
				fieldValue = field.get(object);
				Type fieldType =field.getGenericType();
				if (log.isDebugEnabled()){
					log.debug("类名: {}, 属性类型: {},属性名: {}, 属性值: {}",clazz.getName(), fieldType, fieldName, fieldValue);
				}
			} catch (IllegalArgumentException | IllegalAccessException e) {
				e.printStackTrace();
			}
			if(fieldValue != null){
				flag = true;
				break;
			}
		}
		return flag;
	}

	public boolean objCheckAllNotNull(Object object){
		if (null == object) return false;
		return objCheckAllNotNull(object, Set.of(Constants.SERIAL_VERSION_STR));
	}
	/**
	 *
	 */
	public boolean objCheckAllNotNull(Object object, Set<String> ignoreFieldNames){
		// 默认其为true
		Set<Boolean> flagSet = new HashSet<>();
		flagSet.add(true);
		Class<?> clazz = object.getClass();
		Field[] fields = clazz.getDeclaredFields();
		for(Field field : fields){
			field.setAccessible(true);
			Object fieldValue = null;
			try {
				String fieldName = field.getName();
				if (CollectionUtil.isNotEmpty(ignoreFieldNames)){
					// 要求 fieldName 必须一致, 大小写不同, 视为不同
					if (ignoreFieldNames.contains(fieldName))
						continue;
				}
				fieldValue = field.get(object);
				Type fieldType =field.getGenericType();
				if (log.isDebugEnabled()){
					log.debug("类名: {}, 属性类型: {},属性名: {}, 属性值: {}",clazz.getName(), fieldType, fieldName, fieldValue);
				}
			} catch (IllegalArgumentException | IllegalAccessException e) {
				e.printStackTrace();
			}
			flagSet.add(fieldValue != null);
		}
		// 为1 时, 代表没有 false --> 也就是没有 null 值, 否则就是存在null 值
		return flagSet.size() == 1;
	}
}
