package com.huatek.frame.base.util;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.time.LocalDateTime;
import java.util.Collection;

import org.springframework.beans.BeansException;
import org.springframework.beans.FatalBeanException;
import org.springframework.util.Assert;

import com.huatek.torch.sql.beans.LocalUser;
import com.huatek.torch.util.tools.UserUtil;
import com.huatek.torch.util.uuid.Uuid;

/**
 * The type Bean utils.
 *
 * @author Ezio.Han
 * @date 2018 -05-10 10:55
 */
public class BeanUtils extends org.springframework.beans.BeanUtils {

    /**
     * Copy properties with ignore null.
     * 属性复制忽略null值
     *
     * @param source 原对象
     * @param target 目标对象
     * @throws BeansException the beans exception
     */
    public static void copyPropertiesWithIgnoreNull(Object source, Object target) throws BeansException {
        Assert.notNull(source, "Source must not be null");
        Assert.notNull(target, "Target must not be null");
        Class<?> actualEditable = target.getClass();
        PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
        for (PropertyDescriptor targetPd : targetPds) {
            if (targetPd.getWriteMethod() != null) {
                PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
                if (sourcePd != null && sourcePd.getReadMethod() != null) {
                    try {
                        Method readMethod = sourcePd.getReadMethod();
                        if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                            readMethod.setAccessible(true);
                        }
                        Object value = readMethod.invoke(source);
                        // 这里判断以下 value 是否为空 当然这里也能进行一些特殊要求的处理 例如绑定时格式转换等等
                        if (value != null) {
                            Method writeMethod = targetPd.getWriteMethod();
                            if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                                writeMethod.setAccessible(true);
                            }
                            writeMethod.invoke(target, value);
                        }
                    } catch (Throwable ex) {
                        throw new FatalBeanException("Could not copy properties from source to target", ex);
                    }
                }
            }
        }
    }

    /**
     * Trim this object string fields.
     * 去除对象字符串字段两端的空格
     *
     * @param bean the bean
     * @throws IllegalAccessException the illegal access exception
     */
    public static void trimThisObjectStringFields(Object bean) throws IllegalAccessException {
        if (bean == null) {
            return;
        }
        Field[] fields = bean.getClass().getDeclaredFields();
        if (fields == null) {
            return;
        }
        for (Field f : fields) {
            if (f.getType().isPrimitive()) {
                continue;
            }
            if (f.getType().equals(String.class)) {
                f.setAccessible(true);
                String value = (String) f.get(bean);
                f.set(bean, trim(value));
            }
        }
    }

    /**
     * 去除对象字符串字段两端的空格
     *
     * @param <T>        the type parameter
     * @param collection the collection
     * @throws IllegalAccessException the illegal access exception
     */
    public static <T> void trimThisListObjectStringFields(Collection<T> collection) throws IllegalAccessException {
        for (T t : collection) {
            trimThisObjectStringFields(t);
        }
    }

    /**
     * Trim string.
     *
     * @param str the str
     * @return the string
     */
    private static String trim(String str) {
        return str == null ? null : str.trim();
    }

    /**
     * 初始化entity
     */
    public static <T> T initEntity(T obj, String token) throws IllegalAccessException {
        LocalUser localUser = UserUtil.getLocalUser(token);
        setFieldValueByFieldName(obj, "createName", localUser.getUserName());
        setFieldValueByFieldName(obj, "creater", localUser.getUid());
        setFieldValueByFieldName(obj, "createTime", LocalDateTime.now());
        setFieldValueByFieldName(obj, "id", Uuid.getUUID());
        setFieldValueByFieldName(obj, "deleted", Constants.DEFAULT_NO);
        setFieldValueByFieldName(obj, "version", 0);
        return obj;
    }

    public static <T> T updateModify(T obj, String token) throws IllegalAccessException {
        LocalUser localUser = UserUtil.getLocalUser(token);
        setFieldValueByFieldName(obj, "modifyName", localUser.getUserName());
        setFieldValueByFieldName(obj, "modifier", localUser.getUid());
        setFieldValueByFieldName(obj, "modifyTime", LocalDateTime.now());
        Object version = getFieldValueByFieldName(obj, "version");
        Integer modifyVersion = 0;
        if (version==null){
            version = modifyVersion;
            version = ((Integer) version) + 1;
        }else {
            version = ((Integer) version) + 1;
        }
        setFieldValueByFieldName(obj, "version", version);
        return obj;
    }

    /**
     * 通过属性名设置属性值,不存在的属性名忽略设置值
     *
     * @param object    object
     * @param fieldName fieldName
     * @param value     value
     * @throws IllegalAccessException IllegalAccessException
     */
    private static void setFieldValueByFieldName(Object object, String fieldName, Object value) throws IllegalAccessException {
        //获取obj类的字节文件对象
        @SuppressWarnings("rawtypes")
		Class c = object.getClass();
        // 获取该类的成员变量

        Field f = null;
        try {
            f = c.getDeclaredField(fieldName);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
            return;
        }
        // 取消语言访问检查
        f.setAccessible(true);
        // 给变量赋值
        f.set(object, value);
    }

    /**
     * 通过属性名获取属性值,不存在的属性名返回null
     *
     * @param object    object
     * @param fieldName fieldName
     */
    private static Object getFieldValueByFieldName(Object object, String fieldName) {
        try {
            Field field = object.getClass().getDeclaredField(fieldName);
            //设置对象的访问权限，保证对private的属性的访问
            field.setAccessible(true);
            return field.get(object);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


}
