package com.microservices.wiki.refactoring.utils;



import org.apache.commons.collections4.CollectionUtils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;

public class ConvertBean {

    public static HashMap<String, Object> convertToMap(Object obj) throws Exception{
        HashMap<String, Object> map = new HashMap<String, Object>();
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            String varName = field.getName();
            boolean accessFlag = field.isAccessible();
            field.setAccessible(true);
            Object o = field.get(obj);
            if (o != null)
                map.put(varName, o.toString());

            field.setAccessible(accessFlag);
        }

        return map;
    }

    /**
     * 将List<String>集合 转化为String
     * 如{"aaa","bbb"} To 'aaa','bbb'
     */
    public static String convertListToString(List<String> strlist){
        StringBuilder sb = new StringBuilder();
        if(CollectionUtils.isNotEmpty(strlist)){
            for (int i=0;i<strlist.size();i++) {
                if(i==0){
                    sb.append("'").append(strlist.get(i)).append("'");
                }else{
                    sb.append(",").append("'").append(strlist.get(i)).append("'");
                }
            }
        }
        return sb.toString();

    }

    public static HashMap<String, String> convertToStringMap(Object obj) throws Exception{
        HashMap<String, String> map = new HashMap<String, String>();
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            String varName = field.getName();
            boolean accessFlag = field.isAccessible();
            field.setAccessible(true);
            Object o = field.get(obj);
            if (o != null)
                map.put(varName, o.toString());

            field.setAccessible(accessFlag);
        }

        return map;
    }
}
