package easydo.technology.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.annotation.TableField;
import easydo.technology.annotation.NotTableField;

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

/**
 * map工具类
 *
 *
 * @author whz 2020-12-25
 */
public class MapUtil {

    /**
     * map转List
     */
    public static <T> List<T> mapToList(Map<String, Object> map, Class<T> clazz, String key) {
        List<T> t = null;
        JSONObject jsonObject = mapToJson(map);
        JSONArray array = jsonObject.getJSONArray(key);
        t = array.toJavaList(clazz);
        return t;
    }

    /**
     * map转Json
     */
    public static JSONObject mapToJson(Map<String, Object> map) {
        String data = JSON.toJSONString(map);
        return JSON.parseObject(data);
    }


    /**
     * map中取key对应的value
     *
     * @param map
     * @param key
     * @return
     */
    public static String mapToString(Map<String, Object> map, String key) {
        JSONObject jsonObject = mapToJson(map);
        return jsonObject.getString(key);
    }

    /**
     * map中取类对象
     *
     * @param map
     * @param clazz
     * @param key
     * @param <T>
     * @return
     */
    public static <T> T mapToObject(Map<String, Object> map, Class<T> clazz, String key) {
        T t = null;
        JSONObject jsonObject = mapToJson(map);
        JSONObject object = jsonObject.getJSONObject(key);
        t = object.toJavaObject(clazz);
        return t;
    }

    public static <T> T mapToObject(Map<String, Object> map, Class<T> clazz) {
        T t = null;
        JSONObject jsonObject = mapToJson(map);
        t = jsonObject.toJavaObject(clazz);
        return t;
    }


    /**
     * 对象转化为Map
     *
     * @param obj
     * @return
     * @throws Exception
     */
    public static Map<String, Object> objectToMap(Object obj) throws Exception {
        if (obj == null) {
            return new HashMap<>();
        }
        Map<String, Object> map = new HashMap<>();

        Field[] declaredFields = obj.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            if ("folders".equals(field.getName()) || "serialVersionUID".equals(field.getName())) {
                continue;
            }
            if (field.isAnnotationPresent(NotTableField.class)) {
                continue;
            }
            if (field.isAnnotationPresent(TableField.class)) {
                if (!field.getAnnotation(TableField.class).exist()) {
                    continue;
                }
            }
            field.setAccessible(true);
            if (StringUtil.isEmpty(field.get(obj))) {
                continue;
            }
            map.put(field.getName(), field.get(obj));
        }

        return map;
    }
}
