package api.common.util;


import java.lang.reflect.Method;
import java.util.LinkedList;
import java.util.List;

/**
 * 参数转换工具类
 */
public class ParamUtil {

    /**
     * 将多级下拉二维数组中的数据，赋值到对应对象的属性中
     */
    @SuppressWarnings("unchecked")
    public static void arrConvertObj(String[][] arr,Object object) {
        try {
            if(arr == null || arr.length == 0){
                return ;
            }
            for (int i = 0; i < arr.length; i++) {
                String[] selector = arr[i];
                //至少包含两级
                if(selector != null && selector.length >= 2){
                    //截取type和value
                    String type = selector[selector.length-2];
                    String value = selector[selector.length-1];
                    String filedName = type.substring(0,1).toUpperCase() + type.substring(1);
                    //get方法
                    String getMethodName = "get" + filedName ;
                    Method getMethod = object.getClass().getMethod(getMethodName,null);

                    List<String> getValue = (List<String>) getMethod.invoke(object);
                    if(getValue == null || getValue.size() == 0){
                        getValue = new LinkedList<>();
                    }
                    getValue.add(value);
                    //set方法
                    String setMethodName = "set" + filedName;
                    Method setMethod = object.getClass().getMethod(setMethodName, List.class);
                    setMethod.invoke(object, getValue);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
