package abacus.springboot.example.util;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * <p>Title:JsonStringRemoveRepetUtil</p>
   <p>Description:json字符串-对比</p>
   @author chuanZeng 
   @date 2026年8月18日
 */
public class JsonStringRemoveRepetUtil {
	
	public String[] removeRepet(String oldStr,String newStr){
		if(StringUtils.isEmpty(oldStr)||StringUtils.isEmpty(newStr)) return new String[]{oldStr,newStr};
		try{
			JSONObject oldjo=JSONObject.parseObject(oldStr);
			JSONObject newjo=JSONObject.parseObject(newStr);
			if(oldjo==null||newjo==null) return new String[]{oldStr,newStr};
			List<String> rkeys=new ArrayList<String>();
			List<String> akeys=new ArrayList<String>();
			for(String key:oldjo.keySet()){
				if(oldjo.getString(key)==null&&newjo.getString(key)==null){
					rkeys.add(key);
				}else if(oldjo.getString(key)==null&&newjo.getString(key)!=null||oldjo.getString(key)!=null&&newjo.getString(key)==null){
					
				}else if(oldjo.getString(key).startsWith("{")){//对象
					if(oldjo.getJSONObject(key).getString("id").equals(newjo.getJSONObject(key).getString("id"))){
						rkeys.add(key);
					}
				}else if(oldjo.getString(key).startsWith("[")){//数组
					if(oldjo.getString(key).equals(newjo.getString(key)))
						rkeys.add(key);
					else
						akeys.add(key);
				}else if(oldjo.getString(key).equals(newjo.getString(key))){
					rkeys.add(key);
				}
			}
			if(!rkeys.isEmpty()){
				for(String key:rkeys){
					oldjo.remove(key);
					newjo.remove(key);
				}
			}
			if(!akeys.isEmpty()){
				for(String key:akeys){
					JSONArray oldja= oldjo.getJSONArray(key);
					JSONArray newja= newjo.getJSONArray(key);
					if(oldja.isEmpty()||newja.isEmpty()) continue;
					List<String> oldli=new ArrayList<String>();
					for(Object obj:oldja){
						JSONObject jo=(JSONObject) obj;
						oldli.add(jo.toJSONString());
					}
					List<String> newli=new ArrayList<String>();
					for(Object obj:newja){
						JSONObject jo=(JSONObject) obj;
						newli.add(jo.toJSONString());
					}
					oldli.retainAll(newli);
					if(!oldli.isEmpty()){
						String olds=oldjo.getString(key);
						String news=newjo.getString(key);
						for(String str:oldli){
							olds=olds.replace(str, "").replace(",,", ",");
							news=news.replace(str, "").replace(",,", ",");
						}
						olds=olds.replace("[,", "[").replace(",]", "]");
						news=news.replace("[,", "[").replace(",]", "]");
						if(olds.equals("[]"))
							oldjo.remove(key);
						else
							oldjo.put(key, olds);
						if(news.equals("[]"))
							newjo.remove(key);
						else
							newjo.put(key, news);
					}
				}
			}
			oldStr=oldjo.toJSONString();
			newStr=newjo.toJSONString();
		}catch(Exception e){
			e.printStackTrace();
		}
		return new String[]{oldStr,newStr};
	}
}
