package org.linlinjava.jz.core.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.thoughtworks.xstream.XStream;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.*;

import java.util.HashMap;

@Component
public class BeanUtil implements ApplicationContextAware {
    protected static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public static Object getBean(String name) {
        return context.getBean(name);
    }

    public static <T> T getBean(Class<T> c) {
        return context.getBean(c);
    }

    /*
     * object change to map
     * */
    public static Map<String, Object> Obj2Map(Object obj) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            map.put(field.getName(), field.get(obj));
        }
        return map;
    }

    /*
    * map trun to xml
    * */
    public static  String MapToXML(Map<String,Object> map){
        StringBuilder stringBuilder=new StringBuilder();
        stringBuilder.append("<xml>");
        for (String key : map.keySet()) {
            stringBuilder.append("<"+key+">");
            Object value=map.get(key);
            stringBuilder.append(value==null?"":value.toString());
            stringBuilder.append("</"+key+">");
        }
        stringBuilder.append("</xml>");
        return  stringBuilder.toString();
    }

    /*
    * object to map
    * */
    public static Map<?, ?> objectToMap (Object obj) {
        if (obj == null) {
            return null;
        }

        ObjectMapper objectMapper = new ObjectMapper();
        Map<?, ?> mappedObject = objectMapper.convertValue(obj, Map.class);

        return mappedObject;
    }

   /* *//**
     * xml转成bean泛型方法
     * @param resultXml
     * @param clazz
     * @param <T>
     * @return
     *//*
    public static <T> T xmlToBean(String resultXml, Class clazz) {
        // XStream对象设置默认安全防护，同时设置允许的类
        XStream stream = new XStream();
        XStream.setupDefaultSecurity(stream);
        stream.allowTypes(new Class[]{clazz});
        stream.processAnnotations(new Class[]{clazz});
        stream.setMode(XStream.NO_REFERENCES);
        stream.ignoreUnknownElements();
        stream.alias("xml", clazz);
        return (T) stream.fromXML(resultXml);
    }*/
}
