package com.sckw.core.utils;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSONObject;
import com.sckw.core.model.constant.Global;

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

/**
 * @author zkGlobal
 * @description 集合框架处理类
 * @date 2020/06/06 09:03:53
 */
public class CollectionUtils extends CollectionUtil {
    private static final int DEFAULT_INITIAL_CAPACITY = 16;

    public CollectionUtils() {
    }

    /**
     * @Description 创建HashMap
     * @Author dengyinghui
     * @Date 2019/5/12
     * @return
     */
    public static synchronized Map<String, Object> createHashMap(){
	  return new HashMap<>(DEFAULT_INITIAL_CAPACITY);
    }

    /**
     * @Description 从Map中获取String值
     * @param map map集合
     * @param key key值
     * @Author dengyinghui
     * @Date 2019/5/14
     * @return
     */
    public static String getString(Map<String, Object> map, String key){
	  if(map == null){
		return null;
	  }
	  return StringUtils.valueOf(map.get(key));
    }

    /**
     * @Description 从Map中获取Integer值
     * @param map map集合
     * @param key key值
     * @Author dengyinghui
     * @Date 2019/5/14
     * @return
     */
    public static Integer getInteger(Map<String, Object> map, String key){
	  if(map == null){
		return null;
	  }
	  return (Integer)map.get(key);
    }

    /**
     * @Description 从Map中获取Date值
     * @param map map集合
     * @param key key值
     * @Author dengyinghui
     * @Date 2019/5/14
     * @return
     */
    public static Date getDate(Map<String, Object> map, String key){
	  if(map == null){
		return null;
	  }
	  return (Date)map.get(key);
    }

    /**
     * @Description JSONObject转MAP<String,String>
     * @param object JSONObject对象
     * @Author bernie
     * @Date 2019/08/02
     * @return HashMap<String, String> map结果
     */
    public static HashMap<String, String> toHashMap(JSONObject object)
    {
	  HashMap<String, String> data = new HashMap<>(16);
	  Set<String> keys =  object.keySet();
	  Iterator it = keys.iterator();
	  // 遍历jsonObject数据，添加到Map对象
	  while (it.hasNext())
	  {
		String key = String.valueOf(it.next());
		String value = (String) object.get(key);
		data.put(key, value);
	  }
	  return data;
    }

    public static boolean isEmpty(Collection<?> list) {
	  return list == null || list.size() == 0;
    }

    public static Set<String> valueOfSet(String str) {
	  return valueOfSet(str, ",");
    }

    public static Set<String> valueOfSet(String str, String split) {
	  Set<String> set = new HashSet();
	  str = StringUtils.trimNull(str);
	  if (!StringUtils.isEmpty(str)) {
		String[] strs = str.split(split);
		if (!StringUtils.isEmpty(strs)) {
		    String[] var7 = strs;
		    int var6 = strs.length;

		    for(int var5 = 0; var5 < var6; ++var5) {
			  String string = var7[var5];
			  string = StringUtils.trimNull(string);
			  if (!StringUtils.isEmpty(string)) {
				set.add(string);
			  }
		    }
		}
	  }

	  return set;
    }

    public static List<String> valueOfList(String str) {
	  return valueOfList(str, ",");
    }

    public static List<String> valueOfList(String str, String split) {
	  List<String> list = new ArrayList();
	  str = StringUtils.trimNull(str);
	  if (!StringUtils.isEmpty(str)) {
		String[] strs = str.split(split);
		if (!StringUtils.isEmpty(strs)) {
		    String[] var7 = strs;
		    int var6 = strs.length;

		    for(int var5 = 0; var5 < var6; ++var5) {
			  String string = var7[var5];
			  string = StringUtils.trimNull(string);
			  if (!StringUtils.isEmpty(string)) {
				list.add(string);
			  }
		    }
		}
	  }

	  return list;
    }

    /**
     * 按照List<Map<String,Object>>里面map的某个value重新封装成多个不同的list, 原始数据类型List<Map
     * <String,Object>>, 转换后数据类型Map<String,List<Map<String,Object>>>
     * @param list
     * @param oneMapKey
     * @return
     */
    public static Map<String, Object> change(List<Map<String, Object>> list, String oneMapKey) {
	  Map<String, Object> resultMap = CollectionUtils.createHashMap();
	  Set<Object> setTmp = new HashSet<Object>();
	  for (Map<String, Object> tmp : list) {
		setTmp.add(tmp.get(oneMapKey));
	  }
	  Iterator<Object> it = setTmp.iterator();
	  while (it.hasNext()) {
		String oneSetTmpStr = (String) it.next();
		List<Map<String, Object>> oneSetTmpList = new ArrayList<Map<String, Object>>();
		for (Map<String, Object> tmp : list) {
		    String oneMapValueStr = (String) tmp.get(oneMapKey);
		    if (oneMapValueStr.equals(oneSetTmpStr)) {
			  oneSetTmpList.add(tmp);
		    }
		}
		resultMap.put(oneSetTmpStr, oneSetTmpList);
	  }
	  return resultMap;
    }

    /**
     * 按照List<Map<String,Object>>里面map的某个value重新封装成多个不同的list, 原始数据类型List<Map
     * <String,Object>>, 转换后数据类型Map<String,List<Map<String,Object>>>
     * @param list
     * @param oneMapKey
     * @return
     */
    public static List<Map<String, Object>> change2(List<Map<String, Object>> list, String oneMapKey,
								    List<Map<String, Object>> outList) {
	  // 1.将某个key的值存在set中
	  Set<Object> setTmp = new HashSet<Object>();
	  for (Map<String, Object> tmp : list) {
		setTmp.add(tmp.get(oneMapKey));
	  }
	  // 2.遍历set
	  Iterator<Object> it = setTmp.iterator();
	  while (it.hasNext()) {
		String oneMapValueStr = "";
		String oneSetTmpStr = (String) it.next();
		Map<String, Object> oneSetTmpMap = CollectionUtils.createHashMap();
		List<Map<String, Object>> oneSetTmpList = new ArrayList<Map<String, Object>>();

		for (Map<String, Object> tmp : list) {
		    oneMapValueStr = (String) tmp.get(oneMapKey);
		    if (oneSetTmpStr.equals(oneMapValueStr)) {
			  oneSetTmpMap.put("key", oneSetTmpStr);
			  oneSetTmpList.add(tmp);
		    }
		}
		oneSetTmpMap.put("children", oneSetTmpList);
		outList.add(oneSetTmpMap);
	  }
	  return outList;
    }

	/**
	 * 开始分页
	 * @param list
	 * @param page 页码
	 * @param pageSize 每页多少条数据
	 * @return
	 */
	public static List startPage(List list, Integer page,
								 Integer pageSize) {
		if (list == null) {
			return null;
		}
		if (list.size() == 0) {
			return null;
		}
		// 记录总数
		Integer count = list.size();
		int fromIndex = Math.min((page - 1) * pageSize,count);
		int toIndex = Math.min(fromIndex + pageSize,count);

		List pageList = list.subList(fromIndex, toIndex);
		return pageList;
	}

	/**
	 * Map 按值排序
	 * @param params
	 * @return
	 */
	public static Set<Map.Entry<String, Integer>> valueSort(Map<String, Integer> params){
		Set<Map.Entry<String, Integer>> treeSet = new TreeSet<Map.Entry<String, Integer>>(
				new Comparator<Map.Entry<String, Integer>>() {
					@Override
					public int compare(Map.Entry<String, Integer> o1,
									   Map.Entry<String, Integer> o2) {
						Integer d1 = o1.getValue();
						Integer d2 = o2.getValue();
						int r = d2.compareTo(d1);

						if (r != 0) {
							return r;
						} else {
							return o2.getKey().compareTo(o1.getKey());
						}
					}
				});
		treeSet.addAll(params.entrySet());
		return treeSet;
	}

	/**
	 * 获取list中对象key值为value的对象
	 * @param list 数据集
	 * @param key key
	 * @param value 匹配值
	 * @return
	 */
	public List<Map<String, Object>> listByKeyValue(List<Map<String, Object>> list, String key, String value) {
		if (CollectionUtils.isEmpty(list)) {
			return null;
		}
		List<Map<String, Object>> outList = new ArrayList();
		for (Map<String, Object> map:list) {
			Object str = map.get(key);
			if (StringUtils.isNotBlank(str) && StringUtils.objectStr(str).equals(value)) {
				outList.add(map);
			}
		}

		return outList;
	}

	/**
	 * 校验list中对象key值是否存在与value不一致的情况
	 * @param list 数据集
	 * @param key key
	 * @param value 匹配值
	 * @return
	 */
	public static boolean listByKeyValueV1(List<Map<String, Object>> list, String key, String value) {
		if (CollectionUtils.isEmpty(list)) {
			return false;
		}
		for (Map<String, Object> map:list) {
			Object str = map.get(key);
			if (StringUtils.isNotBlank(str) && !StringUtils.objectStr(str).equals(value)) {
				return true;
			}
		}

		return false;
	}


    public static void main(String[] args) {
	  Map<String, Object> map1 = CollectionUtils.createHashMap();
	  Map<String, Object> map2 = CollectionUtils.createHashMap();
	  Map<String, Object> map3 = CollectionUtils.createHashMap();
	  Map<String, Object> map4 = CollectionUtils.createHashMap();
	  Map<String, Object> map5 = CollectionUtils.createHashMap();

	  List<Map<String, Object>> inList = new ArrayList<Map<String, Object>>();
	  map1.put("id", "111");
	  map1.put("name", "tom");
	  map1.put("sex", "male");

	  map2.put("id", "222");
	  map2.put("name", "jack");
	  map2.put("sex", "male");

	  map3.put("id", "333");
	  map3.put("name", "lucy");
	  map3.put("sex", "female");

	  map4.put("id", "444");
	  map4.put("name", "lucy");
	  map4.put("sex", "female");

	  inList.add(map1);
	  inList.add(map2);
	  inList.add(map3);
	  inList.add(map4);
	  System.out.println("原始inList:" + inList);


	  map5.put("一类（爆炸品）", map4);
	  map5.put("二类（压缩,液化气体）", null);
	  map5.put("三类（易燃液体）", null);
	  map5.put("四类（易燃固体，自燃物品和遇湿易燃）", map3);
	  map5.put("五类（氧化剂，有机过氧化物）", null);
	  map5.put("六类（毒害品，感染类物品）", null);
	  map5.put("七类（放射性物质）", null);
	  map5.put("八类（腐蚀品）", null);
	  map5.put("九类（危险废弃物）", map2);
	  map5.put("普货", null);
	  map5.put("其他", map2);

	  Map<String, Object> resultMap = CollectionUtils.createHashMap();
	  // resultMap = change(list, "sex");
	  resultMap = change(inList, "name");
	  System.out.println("按照map中的某个值重新封装后的resultMap:" + JSONObject.toJSONString(resultMap));

	  List<Map<String, Object>> outList = new ArrayList<Map<String, Object>>();
	  System.out.println("retList==1==:" + outList);
	  outList = change2(inList, "name", outList);
	  System.out.println("retList==2==:" + JSONObject.toJSONString(outList));

	  List list = toList("165159551228710912,165181777487335424,165181777487335425,165181777487335426", false);
	  System.out.println(list);

    }

    /**
     * @desc: object转list
     * @author: yzc
     * @date: 2023-06-26 15:27
     * @Param obj:
     * @Param clazz:
     * @return: java.util.List<T>
     */
    public static <T> List<T> objectCastList(Object obj, Class<T> clazz) {
        List<T> result = new ArrayList<>();
        if (obj instanceof List<?>) {
			for (Object o : (List<?>) obj) {
				result.add(clazz.cast(o));
			}
		}
		return result;
    }

	/**
	 * 对象转Map
	 * @param object
	 * @return
	 * @throws IllegalAccessException
	 */
	public static Map beanToMap(Object object) throws Exception {
		Map<String, Object> map = new HashMap<>(Global.NUMERICAL_SIXTEEN);
		Field[] fields = object.getClass().getDeclaredFields();
		for (Field field : fields) {
			field.setAccessible(true);
			map.put(field.getName(), field.get(object));
		}
		return map;
	}

	/**
	 * map转对象
	 * @param map
	 * @param beanClass
	 * @param <T>
	 * @return
	 * @throws Exception
	 */
	public static <T> T mapToBean(Map map, Class<T> beanClass) throws Exception {
		T object = beanClass.getDeclaredConstructor().newInstance();
		Field[] fields = object.getClass().getDeclaredFields();
		for (Field field : fields) {
			int mod = field.getModifiers();
			if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
				continue;
			}
			field.setAccessible(true);
			if (map.containsKey(field.getName())) {
				field.set(object, map.get(field.getName()));
			}
		}
		return object;
	}

	/**
	 * @param str 数组转换值
	 * @param bool true 原顺序、false 倒序
	 * @desc 字符串转换集合
	 * @author zk
	 * @date 2023/8/7
	 **/
	public static List toList(String str, boolean bool) {
		if (StringUtils.isNotBlank(str)) {
			List idArray = Arrays.asList(str.split(Global.COMMA));
			if (!bool) {
				Collections.reverse(idArray);
			}
			return idArray;
		} else {
			return new ArrayList();
		}
	}

}
