package com.bonus.utils;

import com.alibaba.fastjson.JSON;
import com.bonus.common.core.exception.ServiceException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class LeBeanUtil {
   public static String[] getNullPropertyNames(Object source) {
      BeanWrapper src = new BeanWrapperImpl(source);
      PropertyDescriptor[] pds = src.getPropertyDescriptors();
      Set<String> emptyNames = new HashSet();
      PropertyDescriptor[] var4 = pds;
      int var5 = pds.length;

      for(int var6 = 0; var6 < var5; ++var6) {
         PropertyDescriptor pd = var4[var6];
         Object srcValue = src.getPropertyValue(pd.getName());
         if (srcValue == null) {
            emptyNames.add(pd.getName());
         }
      }

      String[] result = new String[emptyNames.size()];
      return (String[])emptyNames.toArray(result);
   }

   public static void copyProperties(Object source, Object target) {
      if (source != null && target != null) {
         BeanUtils.copyProperties(source, target, getNullPropertyNames(source));
      } else {
         throw new ServiceException("复制对象时,源和目标对象均不能为空");
      }
   }

   public static void copyProperties(Object source, Object target, String... ignoreProperties) {
      BeanUtils.copyProperties(source, target, ignoreProperties);
   }

   public static <T> T copyCreateProperties(Object source, Class<T> tClass) {
      return source == null ? (T) new Object() : JSON.parseObject(JSON.toJSONString(source), tClass);
   }

   public static <T> List copyCreateList(List sourceList, Class<T> tClass) {
      return (List)(CollectionUtils.isEmpty(sourceList) ? new ArrayList() : JSON.parseArray(JSON.toJSONString(sourceList), tClass));
   }

   public static String fieldLikeHandle(String fieldName) {
      return StringUtils.hasText(fieldName) ? "%" + fieldName + "%" : null;
   }
}
