package com.pcloud.common.utils;

import java.util.List;

import com.pcloud.common.page.PageBeanNew;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import com.google.common.collect.Lists;

/**
 * @author：songx
 * @date：2018年8月24日,下午2:18:40
 */
public class BeanNewUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(BeanNewUtils.class);

    /**
     * 实体类之间的转换
     *
     * @param source 来源
     * @param clazz  目标对象
     * @return
     */
    public static <T> T copyProperties(Object source, Class<T> clazz) {
        if (source == null) {
            return null;
        }
        T t = null;
        try {
            t = clazz.newInstance();
        } catch (Exception e) {
            LOGGER.error("clazz newInstance is error:" + e.getMessage(), e);
        }
        BeanUtils.copyProperties(source, t);
        return t;
    }

    /**
     * 实体类之间的转换
     *
     * @param sources 来源
     * @param clazz   目标对象
     * @return
     */
    public static <T> List<T> copyProperties(List<?> sources, Class<T> clazz) {
        if (ListUtils.isEmpty(sources)) {
            return null;
        }
        List<T> results = Lists.newArrayList();
        for (Object source : sources) {
            results.add(copyProperties(source, clazz));
        }
        return results;
    }

    /**
     * 分页结果的实体类之间的转换
     *
     * @param source
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> PageBeanNew<T> copyProperties(PageBeanNew<?> source, Class<T> clazz) {
        if (source == null) {
            return null;
        }
        List<?> recordList = source.getRecordList();
        PageBeanNew<T> result = new PageBeanNew<T>();
        result.setCurrentPage(source.getCurrentPage());
        result.setNumPerPage(source.getNumPerPage());
        result.setPageCount(source.getPageCount());
        result.setTotalCount(source.getTotalCount());
        source.setBeginPageIndex(source.getBeginPageIndex());
        source.setEndPageIndex(source.getEndPageIndex());
        if (ListUtils.isEmpty(recordList)) {
            result.setRecordList(Lists.newArrayList());
            return result;
        }
        result.setRecordList(copyProperties(recordList, clazz));
        return result;
    }

}
