package com.tzy.common.utils.bean;

import com.github.dozermapper.core.DozerBeanMapperBuilder;
import com.github.dozermapper.core.Mapper;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Component
public class DozerUtils {

    /**
     * commonMapper，如果没有传mapper过来，默认使用这个
     * dozer/dozer-mapping.xml 是相对resources目录的路径
     */
    public static Mapper  mapper = DozerBeanMapperBuilder.create()
            .withMappingFiles("dozer/dozer-mapping.xml")
            .build();

    /**
     * 单个对象转换
     * 传入需要转换的对象，返回转换后的对象
     * 用法：CommonDozerUtil.map(dto,Destination.class)
     *
     * @param source           源对象
     * @param destinationClass
     * @param <T>
     * @return
     */
    public static <T> T map(Object source, Class<T> destinationClass) {
        if (source != null) {
            return mapper.map(source, destinationClass);
        }
        return null;
    }

    /**
     * list转换
     * 用法：CommonDozerUtil.mapList(list,Destination.class)
     *
     * @param sourceList
     * @param destinationClass
     * @param <T>
     * @return
     */
    public static <T> List<T> mapList(Collection<?> sourceList, Class<T> destinationClass) {
        List<T> destinationList = new ArrayList<>();
        if (sourceList != null && sourceList.size() > 0) {
            for (Object sourceObject : sourceList) {
                T destinationObject = map(sourceObject, destinationClass);
                destinationList.add(destinationObject);
            }
        }
        return destinationList;
    }

    /**
     * 将对象A的值拷贝到对象B中
     *
     * @param source            对象A
     * @param destinationObject 对象B
     */
    public static void copy(Object source, Object destinationObject) {
        mapper.map(source, destinationObject);
    }

}