package com.prolog.rdc.tms.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import com.alibaba.excel.annotation.ExcelProperty;
import com.prolog.common.util.ToolKits;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 *
 * 导入公共方法
 *
 * @className :ImportUtils
 * @author :fanzw
 * @creationTime :2022/04/29
 * @description :
 *
 * @modifier :fanzw
 * @modifyTime :2022/04/29
 * @reviseRemarks:
 *
 * @version :1.0.0
 *
 */
@Slf4j
public class ImportUtils {

	/**
	 * 设置ExcelProperty注解对应的value
	 * 
	 * @param <T>
	 * @param properties 属性字段和注解属性字段值 键值对
	 * @param tClass     泛型类
	 */
	@SuppressWarnings("unchecked")
	public static <T> void setHeaderValue(Properties properties, Class<?> tClass) {
		ToolKits.isParamNull(properties, "properties file must mot be null");
		if (properties.size() == 0) {
			ToolKits.isParamNull(properties, "properties file must mot be null");
		}

		Set<Map.Entry<Object, Object>> entries = properties.entrySet();
		entries.forEach(entry -> {
			try {
				// 属性名
				String key = String.valueOf(entry.getKey());
				ToolKits.isParamNull(key, "属性名不能为空");

				// 属性值
				String value = String.valueOf(entry.getValue());
				ToolKits.isParamNull(value, "属性值不能为空");

				// 反射找到对应字段
				Field displayName = tClass.getDeclaredField(key);
				// 获取字段上的注解
				ExcelProperty annotation = displayName.getAnnotation(ExcelProperty.class);
				// 获取代理处理器
				InvocationHandler invocationHandler = Proxy.getInvocationHandler(annotation);
				// 获取私有memberValues属性
				Field field = invocationHandler.getClass().getDeclaredField("memberValues");
				// 因为这个字段是 private final 修饰，所以要打开权限
				field.setAccessible(true);
				// 获取memberValues的属性map
				Map<String, Object> memberValues = (Map<String, Object>) field.get(invocationHandler);
				// 修改属性值
				memberValues.put("value", value.split(","));
				System.out.println();
			} catch (Exception e) {
				e.printStackTrace();
				log.error("设置ExcelProperty对应value属性失败", e);
			}
		});
	}
}
