package com.microservices.dss.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.text.ParseException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class DataStructureConvertUtil {

    public static Map<Object,Object> MapInitByMonth(int monthDiff, String endTime) throws ParseException {

        Map<Object, Object> map_init = new LinkedHashMap<>();
        //构建一个size为monthDiff，按顺序的日期作为key,value为0
        for(int i=-(monthDiff);i<=0;i++){
            map_init.put(DateUtil.OnlyYearMonthDateAddByMonth(endTime,i),0);
        }
        return map_init;
    }

    public static int[] dbResult2Array(List<Object> db_result, String key, String value, Map<Object, Object> map_init, int[] resultArray) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();

        for (Object o : db_result) {
            // 使用 ObjectMapper 直接将对象转为 Map
            Map<?, ?> m = mapper.convertValue(o, Map.class);
            Object mapKey = m.get(key);
            if (map_init.containsKey(mapKey)) {
                map_init.put(mapKey, m.get(value));
            }
        }

        int index = 0; // 维护一个索引
        for (Object mapValue : map_init.values()) {
            if (index < resultArray.length) { // 确保不会越界
                resultArray[index++] = Integer.parseInt(mapValue.toString());
            }
        }

        return resultArray;
    }
}
