package com.microservices.common.core.utils;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.CaseFormat;
import com.microservices.common.core.exception.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author otto
 */
public class JSONUtils {

    private static final Logger logger = LoggerFactory.getLogger(JSONUtils.class);

    /**
     * 将Java对象属性转换为下划线结构形式的JSON对象
     *
     * @param source         JAVA对象
     * @param target         JSON对象
     * @param formatPatterns 时间格式
     */
    public static void convertObjectToJSONObject(Object source, JSONObject target, Map<Class<?>, String> formatPatterns) {
        // 获取source对象的所有属性
        Field[] fields = source.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                Object value = field.get(source);
                // 将属性名转换为下划线结构的形式
                String key = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, field.getName());
                if (value != null) {
                    // 如果字段类型为Date类型，并且指定了格式化的pattern，则对Date类型进行format
                    if (value instanceof Date && formatPatterns != null && formatPatterns.containsKey(Date.class)) {
                        SimpleDateFormat sdf = new SimpleDateFormat(formatPatterns.get(Date.class));
                        target.put(key, sdf.format((Date) value));
                    } else {
                        // 将属性值放入JSONObject中
                        target.put(key, value);
                    }
                } else {
                    // 如果属性值为null，则以null放入JSONObject中
                    target.put(key, null);
                }
            } catch (IllegalAccessException e) {
                logger.error("convertObjectToJSONObject error: " + e);
                throw new ServiceException("JAVA对象转换为下划线结构的JSON对象时发生异常");
            }
        }
    }
    public static Long getLongByObject(Object longObj) {
        long id;
        if (longObj instanceof Integer) {
            Integer idInt = (Integer) longObj;
            id = idInt.longValue();
        } else if (longObj instanceof Long) {
            id = (Long) longObj;
        } else {
            throw new ServiceException("Id类型错误");
        }
        return id;
    }

    public static List<Long> getLongListByJsonArray(JSONArray jsonArray) {
        List<Long> list = new ArrayList<>();
        if (jsonArray == null) {
            return list;
        }

        for (Object idObj : jsonArray.toArray()) {
            list.add(getLongByObject(idObj));
        }
        return list;
    }

}
