package cn.hmsoft.jdbc.mapper;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

import cn.hmsoft.helper.BeanHelper;

/**********************
 * 将数据库表每条记录转换成一个对象，为性能考虑，支持一层嵌套
 * 
 * @author zxq
 * @create 2019-05-06 22:17:13
 * @version 2.0.0
 * @email: revisit@126.com
 * @Company: www.hmsoft.cn
 */
public class BeanMapper<T> extends AbstractMapper<T> {
	// 实体的模板
	private Class<T> clazz;
	// 基础类型
	private static Map<String, String> paramMap;
	static {
		synchronized (BeanMapper.class) {
			paramMap = new HashMap<String, String>();
			paramMap.put("Integer", "Integer");
			paramMap.put("Double", "Double");
			paramMap.put("Float", "Float");
			paramMap.put("Long", "Long");
			paramMap.put("long", "long");
			paramMap.put("BigDecimal", "BigDecimal");
			paramMap.put("Date", "Date");
			paramMap.put("LocalDateTime", "LocalDateTime");
			paramMap.put("LocalDate", "LocalDate");
			paramMap.put("LocalTime", "LocalTime");
			paramMap.put("String", "String");
			paramMap.put("List", "List");
			paramMap.put("ArrayList", "ArrayList");
			paramMap.put("Map", "Map");
			paramMap.put("HashMap", "HashMap");
			paramMap.put("LinkedHashMap", "LinkedHashMap");
			paramMap.put("HashTable", "HashTable");
		}
	}

	public BeanMapper(Class<T> clazz) {
		this.clazz = clazz;

	}

	@Override
	public T mapRow(ResultSet rs, int rownum) {
		// 设置查询到的字段
		if (this.columnsIsNull())
			this.setCurrentColumns(rs);
		try {
			T entity = this.clazz.newInstance();
			Map<String, Object> fieldMap = new HashMap<String, Object>();
			for (Field field : this.clazz.getDeclaredFields()) {
				// 如果是简单类型，则无需设置子属性值
				if (paramMap.containsKey(field.getType().getSimpleName()) || field.getType().isPrimitive())
					continue;
				// 复杂类型
				Object object = null;

				try {
					object = field.getType().newInstance();
				} catch (Exception e) {
				}
				if (object == null)
					continue;
				field.setAccessible(true);
				field.set(entity, object);
				fieldMap.put(field.getName(), object);
			}

			for (String column : this.columns) {
				try {
					Object oValue = rs.getObject(column);
					if (oValue == null)
						continue;					
					if (oValue.getClass().toString().endsWith("java.sql.Date")) {
						oValue = rs.getTimestamp(column).toLocalDateTime().toLocalDate();
					} else if (oValue.getClass().toString().endsWith("java.sql.Timestamp")) {
						oValue = ((Timestamp) oValue).toLocalDateTime();
					} else if (oValue.getClass().toString().endsWith("java.sql.Time")) {
						oValue = rs.getTimestamp(column).toLocalDateTime().toLocalTime();
					}
					BeanHelper.beanFromDataRecord(entity, column, oValue);
					// 设置其他变量
					for (Object object : fieldMap.values()) {
						BeanHelper.beanFromDataRecord(object, column, oValue);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			return entity;
		} catch (Exception e) {
		}
		return null;
	}

}
