FormulaUtils.java 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892
  1. package com.mixsmart.utils;
  2. import cn.hutool.core.date.DatePattern;
  3. import cn.hutool.core.date.DateTime;
  4. import cn.hutool.log.StaticLog;
  5. import com.alibaba.fastjson.JSON;
  6. import com.alibaba.fastjson.JSONArray;
  7. import com.alibaba.fastjson.JSONObject;
  8. import com.alibaba.fastjson.annotation.JSONField;
  9. import com.itextpdf.text.pdf.PdfReader;
  10. import com.itextpdf.text.pdf.parser.*;
  11. import com.jfireel.expression.Expression;
  12. import org.apache.commons.lang.math.NumberUtils;
  13. import org.apache.http.*;
  14. import org.apache.http.client.HttpClient;
  15. import org.apache.http.client.entity.UrlEncodedFormEntity;
  16. import org.apache.http.client.methods.HttpGet;
  17. import org.apache.http.client.methods.HttpPost;
  18. import org.apache.http.entity.StringEntity;
  19. import org.apache.http.impl.client.HttpClientBuilder;
  20. import org.apache.http.impl.client.HttpClients;
  21. import org.apache.http.message.BasicNameValuePair;
  22. import org.apache.http.util.EntityUtils;
  23. import org.apache.poi.hssf.usermodel.HSSFDataFormatter;
  24. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  25. import org.apache.poi.ss.usermodel.*;
  26. import java.awt.Color;
  27. import org.jfree.chart.ChartFactory;
  28. import org.jfree.chart.ChartPanel;
  29. import org.jfree.chart.ChartUtils;
  30. import org.jfree.chart.JFreeChart;
  31. import org.jfree.chart.axis.*;
  32. import org.jfree.chart.plot.*;
  33. import org.jfree.chart.renderer.category.BarRenderer;
  34. import org.jfree.chart.renderer.category.LineAndShapeRenderer;
  35. import org.jfree.chart.renderer.xy.XYItemRenderer;
  36. import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
  37. import org.jfree.chart.renderer.xy.XYSplineRenderer;
  38. import org.jfree.chart.title.TextTitle;
  39. import org.jfree.chart.ui.RectangleEdge;
  40. import org.jfree.chart.ui.TextAnchor;
  41. import org.jfree.data.category.CategoryDataset;
  42. import org.jfree.data.category.DefaultCategoryDataset;
  43. import org.jfree.data.xy.XYSeries;
  44. import org.jfree.data.xy.XYSeriesCollection;
  45. import org.jsoup.Jsoup;
  46. import org.jsoup.nodes.Document;
  47. import org.jsoup.nodes.Element;
  48. import org.jsoup.select.Elements;
  49. import org.springblade.common.constant.CommonConstant;
  50. import org.springblade.common.utils.BaseUtils;
  51. import org.springblade.common.utils.SnowFlakeUtil;
  52. import org.springblade.common.utils.SystemUtils;
  53. import org.springblade.core.tool.utils.*;
  54. import org.springblade.manager.bean.TableInfo;
  55. import org.springblade.manager.dto.*;
  56. import org.springblade.manager.entity.Formula;
  57. import org.springblade.manager.entity.WbsTreeContract;
  58. import org.springblade.manager.formula.NodeTable;
  59. import org.springblade.manager.formula.impl.CompositeDataAccess;
  60. import org.springblade.manager.formula.impl.TableElementConverter;
  61. import org.springblade.manager.utils.FileUtils;
  62. import org.springblade.manager.vo.*;
  63. import org.springblade.system.cache.ParamCache;
  64. import org.springframework.core.annotation.AnnotationUtils;
  65. import reactor.core.publisher.Mono;
  66. import javax.imageio.ImageIO;
  67. import java.awt.*;
  68. import java.awt.Font;
  69. import java.awt.Shape;
  70. import java.awt.geom.AffineTransform;
  71. import java.awt.geom.Ellipse2D;
  72. import java.awt.geom.Rectangle2D;
  73. import java.awt.image.BufferedImage;
  74. import java.io.*;
  75. import java.lang.annotation.Annotation;
  76. import java.lang.reflect.Field;
  77. import java.math.BigDecimal;
  78. import java.nio.charset.StandardCharsets;
  79. import java.security.MessageDigest;
  80. import java.security.NoSuchAlgorithmException;
  81. import java.text.SimpleDateFormat;
  82. import java.time.LocalDate;
  83. import java.time.LocalDateTime;
  84. import java.util.*;
  85. import java.util.List;
  86. import java.util.concurrent.ThreadLocalRandom;
  87. import java.util.concurrent.atomic.AtomicInteger;
  88. import java.util.function.BiFunction;
  89. import java.util.function.Function;
  90. import java.util.regex.Matcher;
  91. import java.util.regex.Pattern;
  92. import java.util.stream.Collectors;
  93. import java.util.stream.IntStream;
  94. import java.util.stream.Stream;
  95. import static java.util.regex.Pattern.*;
  96. /**
  97. * @author yangyj
  98. * @Date 2022/7/14 15:55
  99. * @description 公式工具类
  100. */
  101. public class FormulaUtils {
  102. public static final String ELE_CODE_REG= "(?<=E\\[)[^]]+(?=])";
  103. public static final Pattern P = Pattern.compile(ELE_CODE_REG);
  104. /**元素标识*/
  105. public final static String E="E";
  106. /*确定各个元素在计算时的步长,算法:step=最长单元格数/当前元素单元格数*/
  107. public static LinkedHashMap<String,FormData> step(List<FormData> ele){
  108. LinkedHashMap<String,FormData> fdMap =new LinkedHashMap<>();
  109. FormData maxFormData = Collections.max(ele, Comparator.comparingInt((FormData ef)->ef.getValues().size()));
  110. FormData minFormData = Collections.min(ele, Comparator.comparingInt((FormData ef)->ef.getValues().size()));
  111. if (maxFormData.getValues().size() != minFormData.getValues().size()) {
  112. int baseLength = maxFormData.getValues().size();
  113. for (FormData formData : ele) {
  114. formData.setStep(baseLength / formData.getValues().size());
  115. }
  116. }
  117. ele.forEach(e->{
  118. fdMap.put(e.getCode(),e);
  119. });
  120. return fdMap;
  121. }
  122. /*确定公式执行环境变量*/
  123. public static List<LocalVariable> slice2Local(String f, LinkedHashMap<String,FormData> fdMap, TableElementConverter tec){
  124. CompositeDataAccess cda = new CompositeDataAccess(fdMap);
  125. List<LocalVariable> local= new ArrayList<>();
  126. while (cda.hasNext()){
  127. LinkedHashMap<String,ElementData> tip= cda.next();
  128. Map<String, Object> variable = new HashMap<>(tec.constantMap);
  129. @SuppressWarnings("unchecked")
  130. Map<String,Object> em= (Map<String, Object>) variable.computeIfAbsent(E, k->new HashMap<>());
  131. Integer index= new ArrayList<>(tip.values()).get(0).getIndex();
  132. for(Map.Entry<String,ElementData> se:tip.entrySet()){
  133. Object value=se.getValue().getValue();
  134. if(CustomFunction.isNumber(value)){
  135. if(StringUtils.isDouble(value)||f.contains("/")){
  136. em.put(se.getKey(),Double.parseDouble(value.toString()));
  137. }else{
  138. em.put(se.getKey(),StringUtils.handleObj2Integer(value));
  139. }
  140. }else{
  141. em.put(se.getKey(),StringUtils.handleNull(value).replaceAll("[ ]+","").trim());
  142. }
  143. }
  144. local.add(new LocalVariable(index,f,variable));
  145. }
  146. return local;
  147. }
  148. public static void putEle(String f,List<FormData> ele,Map<String, Object> currentMap,FormData fd){
  149. @SuppressWarnings("unchecked")
  150. Map<String,Object> em = (Map<String, Object>) currentMap.computeIfAbsent(E,(k)-> new HashMap<>());
  151. /*如果输入输出元素都是1对1*/
  152. if(f.split("[/+\\-*]").length>1&&!f.contains("{}")&&ele.stream().map(e->e.getCoordsList().size()).max(Comparator.comparingInt(e->e)).orElse(1)==1&&fd.getCoordsList().size()==1){
  153. ele.forEach(e->{
  154. Object value=e.getValues().get(0).getValue();
  155. if(CustomFunction.isNumber(value)){
  156. if(StringUtils.isDouble(value)||f.contains("/")){
  157. em.put(e.getCode(), Double.parseDouble(value.toString()));
  158. }else{
  159. em.put(e.getCode(),StringUtils.handleObj2Integer(value));
  160. }
  161. }else{
  162. em.put(e.getCode(),value);
  163. }
  164. });
  165. }else{
  166. ele.forEach(e-> em.put(e.getCode(),e.getRawValue()));
  167. }
  168. }
  169. public static final Random RD = new Random();
  170. public static Map<String,Object> triangleSquare(Object ranges){
  171. Map<String,Object> map =new HashMap<>();
  172. if(StringUtils.isEmpty(ranges)){
  173. //z的默认取值范围
  174. ranges="(0,15)";
  175. }
  176. Matcher m = RegexUtils.matcher("(\\-?\\d+)(\\D)(\\+?\\d+)",ranges.toString());
  177. if(m.find()) {
  178. int min = StringUtils.handObj2Integer(m.group(1));
  179. int max = StringUtils.handObj2Integer(m.group(3));
  180. Integer[] r = pythagorean(min, max);
  181. map.put("X", String.valueOf(r[0]));
  182. map.put("Y", String.valueOf(r[1]));
  183. map.put("Z", String.valueOf(r[2]));
  184. }
  185. return map;
  186. }
  187. /* public static void main(String[] args) {
  188. IntStream.range(0,10).boxed().forEach(i->{
  189. System.out.println(triangleSquare("-5,5"));
  190. });
  191. }*/
  192. /**
  193. * @Description 字符串相似度
  194. * @Param [s1, s2]
  195. * @return double
  196. * @Author yangyj
  197. * @Date 2023.04.12 18:01
  198. **/
  199. public static double getJaccardSimilarity(String s1, String s2) {
  200. Set<Character> set1 = new HashSet<>();
  201. Set<Character> set2 = new HashSet<>();
  202. for (char c : s1.toCharArray()) {
  203. set1.add(c);
  204. }
  205. for (char c : s2.toCharArray()) {
  206. set2.add(c);
  207. }
  208. Set<Character> intersection = new HashSet<>(set1);
  209. intersection.retainAll(set2);
  210. Set<Character> union = new HashSet<>(set1);
  211. union.addAll(set2);
  212. return (double) intersection.size() / union.size();
  213. }
  214. public static Double similarity(String s1,String s2){
  215. return getJaccardSimilarity(parseItemName(s1),parseItemName(s2));
  216. }
  217. /**
  218. * result[0]^2+result[1]^2=result[2]^2 result[] 元素均为正整数
  219. */
  220. public static Integer[] pythagorean(Integer min,Integer max){
  221. Integer[] result = null;
  222. List<Integer[]> list = new ArrayList<>();
  223. for(int i=1;i<=max;i++){
  224. for(int j=1;j<=max;j++){
  225. double tmp = Math.sqrt(Math.pow(i,2)+Math.pow(j,2));
  226. int z= (int) Math.round(tmp);
  227. if(min<z&&z<=max){
  228. Integer[] arr = new Integer[]{RD.nextBoolean()?i:-i,RD.nextBoolean()?j:-j,z};
  229. list.add(arr);
  230. }
  231. }
  232. }
  233. if(ListUtils.isNotEmpty(list)){
  234. Random rm = new Random();
  235. result = list.get(rm.nextInt(list.size()));
  236. }
  237. return result;
  238. }
  239. /*public static void main(String[] args) {
  240. FormData fd = new FormData();
  241. fd.setEName("1111");
  242. List<ElementData> list = new ArrayList<>();
  243. list.add(new ElementData(1,1,1));
  244. test(fd);
  245. System.out.println(fd.getEName());
  246. }*/
  247. /**写人元素数据,每个元素都是一个集合,每页的单元格数量乘以页数就是总长度*/
  248. public static void write(FormData fd, Object data){
  249. write(fd,data,false);
  250. }
  251. public static void write(FormData fd, Object data,Boolean retainEmpty ){
  252. if(Func.isEmpty(fd.getValues())){
  253. /*无定位信息不写入*/
  254. return;
  255. }
  256. try {
  257. /*一个单元格且存在多张,全部设置为自动拓展 20230816*/
  258. if(fd.getCoordsList().size()==1&&fd.getValues().size()>1&&fd.getFormula()!=null){
  259. fd.getFormula().setOutm(Formula.FULL);
  260. }
  261. /*写入前清空内容*/
  262. fd.getValues().forEach(t->t.setValue(null));
  263. if(data instanceof List){
  264. List<Object> values = (List<Object>) data;
  265. if(!retainEmpty){
  266. /*不包含空白内容*/
  267. values=values.stream().filter(StringUtils::isNotEmpty).collect(Collectors.toList());
  268. }
  269. if(values.size()>fd.getValues().size()){
  270. if(fd.getCoordsList().size()==1){
  271. /*元素只绑定了一个单元格的情况*/
  272. if(values.stream().filter(CustomFunction::containsZH).anyMatch(e->e.toString().contains("\n"))){
  273. fd.getValues().get(0).setValue(values.stream().filter(Objects::nonNull).map(Object::toString).collect(Collectors.joining()));
  274. }else{
  275. /*日期类型的元素只获取最后一个非空*/
  276. if(StringUtils.isEquals(4,fd.getEType())){
  277. fd.getValues().get(0).setValue(values.stream().filter(StringUtils::isNotEmpty).reduce((first, second) -> second).orElse(null));
  278. }else if(values.stream().filter(StringUtils::isNotEmpty).distinct().count()==1L){
  279. /*如果输入元素全是是一样的内容,则输入出元素则每个单元格也写入一样的内容*/
  280. values.stream().filter(StringUtils::isNotEmpty).findFirst().ifPresent(t->{
  281. for(int n=0;n<fd.getValues().size();n++){
  282. fd.getValues().get(n).setValue(t);
  283. }
  284. });
  285. }else{
  286. fd.getValues().get(0).setValue(values.stream().filter(StringUtils::isNotEmpty).map(StringUtils::handleNull).collect(Collectors.joining("、")));
  287. }
  288. }
  289. }else{
  290. for(int n=0;n<fd.getValues().size();n++){
  291. fd.getValues().get(n).setValue(values.get(n));
  292. }
  293. List<Object> overList=values.stream().skip(fd.getValues().size()).collect(Collectors.toList());
  294. List<Coords> coordsList = fd.getCoordsList();
  295. int addPage=(int)Math.ceil((double)overList.size()/(double)coordsList.size());
  296. fd.setAddPages(addPage);
  297. ElementData last =fd.getValues().get(fd.getValues().size()-1);
  298. int indexBase=last.getIndex()+1;
  299. List<ElementData> addList= new ArrayList<>();
  300. for(int i=0;i<addPage;i++){
  301. for(int j=0;j<coordsList.size();j++){
  302. /*超页就尽管写进去,格式化阶段再加表*/
  303. Coords coords = coordsList.get(j);
  304. Object v=null;
  305. int st=i*coordsList.size()+j;
  306. if(st<overList.size()){
  307. v= overList.get(st);
  308. }
  309. addList.add(new ElementData(indexBase+i,last.getGroupId(),v,coords.getX(),coords.getY()));
  310. }
  311. }
  312. fd.getValues().addAll(addList);
  313. }
  314. }else{
  315. for (int n = 0; n < values.size(); n++) {
  316. fd.getValues().get(n).setValue(values.get(n));
  317. }
  318. }
  319. }else{
  320. if(fd.getFormula()!=null&&Formula.FULL.equals(fd.getFormula().getOutm())){
  321. /*填充策略*/
  322. fd.getValues().forEach(e->e.setValue(data));
  323. }else{
  324. fd.getValues().get(0).setValue(data);
  325. }
  326. }
  327. fd.setUpdate(1);
  328. }catch (Exception e){
  329. e.printStackTrace();
  330. }
  331. }
  332. public static final String TBN_FN="TBN";
  333. /*把模型类转换成共识配置选项*/
  334. public static List<WbsFormElementVO> toElementVos(Class<?> clazz) {
  335. return DataModel.toElementVos(clazz);
  336. }
  337. public static String getEleKey(Class<?> clazz, String fieldName){
  338. try {
  339. Field field = clazz.getDeclaredField(fieldName);
  340. String TBN = (String) clazz.getField(TBN_FN).get(null);
  341. JSONField jf = AnnotationUtils.findAnnotation(field, JSONField.class);
  342. if (jf != null) {
  343. return TBN+StringPool.COLON+jf.name();
  344. }
  345. } catch (Exception e) {
  346. e.printStackTrace();
  347. }
  348. return StringPool.EMPTY;
  349. }
  350. public static JSONField getJSONField(Class<?> clazz, String fieldName){
  351. try {
  352. Field field = clazz.getDeclaredField(fieldName);
  353. String TBN = (String) clazz.getField(TBN_FN).get(null);
  354. JSONField jf = AnnotationUtils.findAnnotation(field, JSONField.class);
  355. if (jf != null) {
  356. return jf;
  357. }
  358. } catch (Exception e) {
  359. e.printStackTrace();
  360. }
  361. return null;
  362. }
  363. /*获取指定模型的页码元素*/
  364. public static String getPageCode(Class<?> clazz){
  365. return getEleKey(clazz,"pageCount");
  366. }
  367. public static String getPageTotal(Class<?> clazz){
  368. return getEleKey(clazz,"pageTotal");
  369. }
  370. public static String getPageIndex(Class<?> clazz){
  371. return getEleKey(clazz,"pageIndex");
  372. }
  373. public static JSONField getPageFormat(Class<?> clazz){
  374. return getJSONField(clazz,"pageCount");
  375. }
  376. /*根据数据模型实例生成带数据的元素,用于修改*/
  377. public static <T> LinkedHashMap<String,FormData> toFormDataMap(T bean){
  378. LinkedHashMap<String,FormData> result = new LinkedHashMap<>();
  379. if(bean!=null){
  380. try {
  381. @SuppressWarnings("unchecked")
  382. Map<String,String> map= JSON.parseObject(JSON.toJSONString(bean),Map.class);
  383. Class<?> clazz=bean.getClass();
  384. String TBN = (String) clazz.getField(TBN_FN).get(null);
  385. for (Field field : clazz.getDeclaredFields()) {
  386. JSONField jf = field.getAnnotation(JSONField.class);
  387. if (jf != null) {
  388. FormData fd = new FormData();
  389. fd.setCode(TBN+ StringPool.COLON +jf.name());
  390. fd.setEName(jf.label());
  391. fd.getValues().add(new ElementData(0,0,map.get(fd.getKey()),0,0));
  392. fd.getCoordsList().add(new Coords("0","0"));
  393. result.put(fd.getCode(),fd);
  394. }
  395. }
  396. }catch (Exception e){
  397. e.printStackTrace();
  398. }
  399. }
  400. return result;
  401. }
  402. /*根据数据模型建立空元素,待写入数据*/
  403. public static <T> LinkedHashMap<String,FormData> toFormDataMap(Class<T> clazz){
  404. LinkedHashMap<String,FormData> result = new LinkedHashMap<>();
  405. try {
  406. String TBN = (String) clazz.getField(TBN_FN).get(null);
  407. for (Field field : clazz.getDeclaredFields()) {
  408. JSONField jf = field.getAnnotation(JSONField.class);
  409. if (jf != null) {
  410. FormData fd = new FormData();
  411. fd.setCode(TBN+ StringPool.COLON +jf.name());
  412. fd.setEName(jf.label());
  413. fd.getCoordsList().add(new Coords("0","0"));
  414. result.put(fd.getCode(),fd);
  415. }
  416. }
  417. }catch (Exception e){
  418. e.printStackTrace();
  419. }
  420. return result;
  421. }
  422. /*把结果数据回写到元素*/
  423. public static<T>void put2FormData( LinkedHashMap<String,FormData> fdm,Map<String,Function<List<T>,List<Object>>> functionMap,List<T> dataList){
  424. fdm.values().stream()
  425. .filter(fd -> functionMap.containsKey(fd.getCode()))
  426. .forEach(fd -> {
  427. List<Object> raw = functionMap.get(fd.getCode()).apply(dataList);
  428. raw.stream().map(ElementData::new).forEach(fd.getValues()::add);
  429. });
  430. }
  431. /*根据数据模型对象,生成数据集合按字段获取数据的函数*/
  432. public static <T> Map<String, Function<List<T>, List<Object>>> fieldDataFcMap(Class<?> clazz) {
  433. Map<String, Function<T, Object>> fieldMap = functionMapBuilder(clazz);
  434. Map<String, Function<List<T>, List<Object>>> functionMap = new HashMap<>();
  435. for (Map.Entry<String, Function<T, Object>> functionEntry : fieldMap.entrySet()) {
  436. Function<List<T>, List<Object>> mapper = list -> list.stream().map(functionEntry.getValue()).collect(Collectors.toList());
  437. functionMap.put(functionEntry.getKey(), mapper);
  438. }
  439. return functionMap;
  440. }
  441. /*数据模型按字段生成内容获取函数*/
  442. public static <T> Map<String,Function<T,Object>> functionMapBuilder(Class<?> clazz){
  443. Map<String, Function<T, Object>> functionMap = new HashMap<>();
  444. try {
  445. String tbn=clazz.getField(TBN_FN).get(null).toString();
  446. for (Field field : clazz.getDeclaredFields()) {
  447. JSONField jf = field.getAnnotation(JSONField.class);
  448. if(jf!=null) {
  449. /*ordinal<=100的情况下才会生成动态行字段输出函数*/
  450. if(jf.ordinal()<=100) {
  451. String key = tbn + StringPool.COLON + jf.name();
  452. String fieldName = field.getName();
  453. Function<T, Object> function = getFunction(clazz, fieldName);
  454. functionMap.put(key, function);
  455. }
  456. }
  457. }
  458. }catch (Exception e){
  459. e.printStackTrace();
  460. }
  461. return functionMap;
  462. }
  463. private static <T> Function<T, Object> getFunction(Class<?> clazz, String fieldName) {
  464. return certificate -> {
  465. try {
  466. Field field = clazz.getDeclaredField(fieldName);
  467. field.setAccessible(true);
  468. return field.get(certificate);
  469. } catch (Exception e) {
  470. e.printStackTrace();
  471. return null;
  472. }
  473. };
  474. }
  475. /*list转TreeNode*/
  476. public static <K,T> Map<K, TreeNode<T>> list2TreeNode(Function<TreeNode<T>,K> keyMapper,List<T> list,Function<T,TreeNode<T>> fc,Function<TreeNode<T>,K> classifier){
  477. Map<K, TreeNode<T>> mTreeMap = new HashMap<>();
  478. if (Func.isNotEmpty(list)) {
  479. for (T mt : list) {
  480. try {
  481. TreeNode<T> treeNode = fc.apply(mt);
  482. mTreeMap.put(keyMapper.apply(treeNode), treeNode);
  483. }catch (Exception e){
  484. e.printStackTrace();
  485. }
  486. }
  487. Map<K, List<TreeNode<T>>> group = mTreeMap.values().stream().collect(Collectors.groupingBy(classifier));
  488. group.forEach((k, v) -> {
  489. TreeNode<T> parent = mTreeMap.get(k);
  490. if (parent != null) {
  491. v = v.stream().sorted(Comparator.comparingInt(TreeNode::getSort)).collect(Collectors.toList());
  492. parent.setChildren(v);
  493. v.forEach(e -> e.setParent(parent));
  494. }
  495. });
  496. }
  497. return mTreeMap;
  498. }
  499. /*TreeNode 排序*/
  500. public static <T> void treeNodeSort(int base,TreeNode<T> top){
  501. top.setSort(base);
  502. if(top.hasChildren()){
  503. for(TreeNode<T> child:top.getChildren()){
  504. child.setSort(base++);
  505. }
  506. }
  507. }
  508. /*回溯标记*/
  509. public static <T> void treeNodeChecked( TreeNode<T> tmp){
  510. int loop = 10;
  511. do{
  512. if(tmp.isChecked()) {
  513. /*已经检出则停止循环*/
  514. loop=0;
  515. }else{
  516. tmp.setChecked(true);
  517. tmp=tmp.getParent();
  518. }
  519. }while (tmp!=null&&loop-->0);
  520. }
  521. /*获取层级链*/
  522. public static <T> List<T> treeNodeChains( TreeNode<T> tmp){
  523. List<T> result = new ArrayList<>();
  524. int loop = 10;
  525. do{
  526. /*不包括顶层*/
  527. if(tmp.getParentId()!=0L) {
  528. result.add(tmp.getValue());
  529. }
  530. tmp=tmp.getParent();
  531. }while (tmp!=null&&loop-->0);
  532. Collections.reverse(result);
  533. return result;
  534. }
  535. /**从元素名称中解析项目名称,细化项目匹配用*/
  536. public static String parseItemName(String eName){
  537. if (StringUtils.isEmpty(eName)) {
  538. return eName;
  539. }
  540. String str = eName.replaceAll("\\s", "");
  541. Pattern pattern = compile("[((][^\\u4e00-\\u9fa5]+[))]|_+");
  542. String[] candidate = pattern.split(str);
  543. /*非中文非罗马数字1到10*/
  544. String regex = "[^\\u4e00-\\u9fa5\\u2160-\\u2169))((]+";
  545. Pattern p = compile(regex);
  546. return Arrays.stream(candidate)
  547. .filter(s -> !isContainKeywords(s))
  548. .map(s -> filterString(s, p))
  549. .collect(Collectors.joining());
  550. }
  551. /*A15检查内容专用*/
  552. public static String checkItemName(String eName){
  553. if (StringUtils.isEmpty(eName)) {
  554. return eName;
  555. }
  556. /*分割字符串,选取第一个匹配的子串*/
  557. String str = eName.replaceAll("\\s", "");
  558. Pattern pattern = compile("[((][^\\u4e00-\\u9fa5]+[))]|_+");
  559. String[] candidate = pattern.split(str);
  560. String regex = "[^\\u4e00-\\u9fa5]+";
  561. return Arrays.stream(candidate).map(s->s.replaceAll(regex,"")).distinct().filter(StringUtils::isNotEmpty).filter(s->!isContainKeywords2(s)).findFirst().orElse("");
  562. }
  563. private static String filterString(String s, Pattern p) {
  564. s=s.replaceAll("【[^【】]+】","");
  565. Matcher matcher = p.matcher(s);
  566. return matcher.replaceAll("").replaceAll(getRegex(), "").replaceAll("(设计|合格).*","");
  567. }
  568. private static String getRegex() {
  569. return "(在合格标准内|满足设计要求|质量评定|评定|判定|项目|总数|抽测|实测|偏差|尺量|关键|一般)";
  570. }
  571. private static boolean isContainKeywords(String s) {
  572. List<String> keywords = Arrays.asList( ":", "个","附录","抽查","测","求","小于","大于","检查","仪","按","不","各","记录","检验","且","规定","值或实","≤","≥","平均");
  573. return keywords.stream().anyMatch(s::contains);
  574. }
  575. private static boolean isContainKeywords2(String s) {
  576. List<String> keywords = Arrays.asList( "项目","检查","附录","记录","检验结果","结果");
  577. return keywords.stream().anyMatch(s::contains);
  578. }
  579. /**回归·测试变量*/
  580. public static List<String> itemNames =Arrays.asList(
  581. ""
  582. ,"压 实 度 (%)下路床 特重、极重交通荷载等级 设计值"
  583. ,"1△_压 实 度 (%)_下路床_轻、中及重交通 荷载等级_0.3m~0.8m_≧96_≧95_≧94_实测值或实测偏差值"
  584. ,"1△_压 实 度 (%)_下路提_轻、中及重交通 荷载等级_&gt;1.5m_≧93_≧92_≧90_实测值或实测偏差值"
  585. ,"1△_压 实 度 (%)_上路提_轻、中及重交通 荷载等级_0.8m~1.5m_≧94_≧94_≧93_实测值或实测偏差值"
  586. ,"压 实 度 (%)下路提 轻、中及重交通荷载等级 设计值"
  587. ,"压 实 度 (%)下路床 特重、极重交通荷载等级 合格率"
  588. ,"压 实 度 (%)下路提 轻、中及重交通荷载等级\t合格率"
  589. ,"5△_保护层 厚度 (mm)_基础、锚碇、墩台身、墩柱_±10_实测值或实测偏差值"
  590. ,"钢筋骨架尺寸宽、高或直径 (mm)_尺量:按骨架总数30%抽测_±5_实测值或实测偏差值"
  591. ,"钢筋骨架尺寸长 (mm)_±10_尺量:按骨架总数30%抽测_实测值或实测偏差值"
  592. , "受力钢筋间距 (mm)同排 梁、板、拱肋及拱上建筑 设计值"
  593. ,"受力钢筋间距 (mm)同排 梁、板、拱肋及拱上建筑 合格率"
  594. ," 箍筋、构造钢筋、螺旋筋间距(mm) 设计值"
  595. ,"箍筋、构造钢筋、螺旋筋间距(mm) 合格率"
  596. ,"实测项目_桩位 (mm)_群桩_≤100_质量评定_合格判定"
  597. ,"实测项目_桩位 (mm)_群桩_≤100_实测值或实测偏差值"
  598. ,"实测项目_桩位 (mm)_排架桩_实测值或实测偏差值"
  599. ,"实测项目_桩位 (mm)_排架桩_质量评定_合格判定"
  600. ,"实测项目_桩位 (mm)_群桩_≤100_质量评定_合格率(%)"
  601. ,"实测项目_桩位 (mm)_排架桩_质量评定_合格率(%)"
  602. ,"3△_支座高程(mm)_满足设计要求;设 计未要求时±5_水准仪:测每支座中心线_实测值或实测偏差值"
  603. ,"基底承载力(KPa)_不小于设计_直观或动力触探试验_实测值或实测偏差值"
  604. ,"实 测 项 目_花卉数量_满足设计要求_实测值或实测偏差值"
  605. ,"实 测 项 目_2△_草坪、草本地被覆盖率(%)_取弃土场绿 地_≥90_实测值或实测偏差值"
  606. ,"轴线偏位(mm)_全站仪:20m检查3点_实测值或实测偏差值"
  607. ,"1△_基材混合物喷射厚度(mm)_设计厚度±10_实测值或实测偏差值"
  608. ,"1△_混凝土强度 (MPA)_在合格标准内_按附录D检查_实测值或实测偏差值"
  609. ,"边坡坡度_不陡于设计值_水准仪:每200m测2点,且不少于5点_实测值或实测偏差值"
  610. ,"几何尺寸(mm)_±50_尺量:长、宽、高、壁厚各2点_实测值或实测偏差值"
  611. ,"4△_桩长(mm)_不小于设计_查施工记录_实测值或偏差值"
  612. ,"单桩每延米喷粉 (浆)量_不小于设计_查施工记录_实测值或偏差值"
  613. ,"搭接宽度(mm)_≥150【纵向】_尺量:抽查2%_实测值或实测偏差值",
  614. "搭接宽度(mm)_≥50(横向)_尺量:抽查2%_实测值或实测偏差值"
  615. ,"竖直度(mm)_挖孔桩_0.5%桩长,且≤200_铅锤线:每桩检测_实测值或实测偏差值"
  616. , "2△_压浆压力值 (Mpa)_满足施工技术 规范规定_查油压表读书;每管道检查_实测值或实测偏差值"
  617. , "基底承载力(KPa)_不小于设计_实测值或实测偏差值"
  618. ,"1△_受力钢筋间距 (mm)_两排以上间距_±5_实测值或实测偏差值"
  619. ,"1△梁(板)长度 (mm)_±5_实测值或实测偏差值"
  620. ,"墙面平整度(mm)_施工缝、变形缝处≤20_实测值或实测偏差值"
  621. ,"基底承载力(KPa)_不小于设计_实测值或实测偏差值"
  622. ,"1△_拱部超挖(mm)_Ⅱ、Ⅲ、Ⅳ级围岩(中硬岩 、软岩)_平均150,最大250_实测值或实测偏差值"
  623. ,"实 测 项 目_关键项目_压实度(%)_上路堤_轻、中及重交通荷载等级_0.8~1.5m_≥94_≥94_≥93_检查情况 (实测值)"
  624. ,"表面平整度(mm)_片石_≤35_检验结果"
  625. );
  626. /* public static void main(String[] args) {
  627. // itemNames.stream().map(FormulaUtils::parseItemName).forEach(System.out::println);
  628. itemNames.stream().map(FormulaUtils::checkItemName).forEach(System.out::println);
  629. }*/
  630. public static Object getValue(Cell cell) {
  631. if (cell != null) {
  632. switch (cell.getCellTypeEnum()) {
  633. case STRING:
  634. return cell.getStringCellValue() == null ? null : cell.getStringCellValue().trim();
  635. case NUMERIC:
  636. HSSFDataFormatter dataFormatter = new HSSFDataFormatter();
  637. return dataFormatter.formatCellValue(cell);
  638. case BOOLEAN:
  639. return cell.getBooleanCellValue();
  640. case ERROR:
  641. return cell.getErrorCellValue();
  642. case FORMULA:
  643. try {
  644. return cell.getStringCellValue();
  645. } catch (IllegalStateException e) {
  646. return "";
  647. }
  648. default:
  649. cell.setCellType(CellType.STRING);
  650. return cell.getStringCellValue() == null ? null : cell.getStringCellValue().trim();
  651. }
  652. }
  653. return null;
  654. }
  655. public static List<ElementData> getElementDataList(String coords,String values){
  656. if(StringUtils.isNotEmpty(coords,values)){
  657. List<Coords> coordsList = Stream.of(coords).flatMap(s -> Arrays.stream(s.split(";"))).map(s -> {
  658. String[] xy = s.split("_");
  659. return new Coords(xy[1], xy[0]);
  660. }).collect(Collectors.toList());
  661. return str2ElementData(values,coordsList,null,null);
  662. }
  663. return Collections.emptyList();
  664. }
  665. public static List<ElementData> str2ElementData(String pg, List<Coords> coordsList ,String code,Integer index){
  666. List<ElementData> eds = new ArrayList<>();
  667. if(StringUtils.isNotEmpty(pg)&&ListUtils.isNotEmpty(coordsList)) {
  668. if(code==null){
  669. code="code";
  670. }
  671. if(index==null){
  672. index=1;
  673. }
  674. String[] val = pg.split("☆");
  675. Map<String, Object> tmpMap = new LinkedHashMap<>();
  676. for (String s : val) {
  677. String[] t = s.split("_\\^_");
  678. String[] c = t[1].split("_");
  679. tmpMap.put(StringUtils.join(code, 0, index, Func.toInt(c[1]), Func.toInt(c[0]), StringPool.AT), t[0]);
  680. }
  681. for (Coords c : coordsList) {
  682. Object data = null;
  683. String key = StringUtils.join(code, 0, index, c.getX(), c.getY(), StringPool.AT);
  684. if (tmpMap.containsKey(key)) {
  685. data = tmpMap.get(key);
  686. }
  687. eds.add(new ElementData(index, 0, data, c.getX(), c.getY()));
  688. }
  689. }
  690. return eds;
  691. }
  692. /**
  693. * @Description Poi 动态执行公式 测试
  694. * @Param [url]
  695. * @Author yangyj
  696. * @Date 2023.05.05 14:28
  697. **/
  698. public static void evaluateFormulaCell(String url) {
  699. try {
  700. url="C:/Users/yangyj/Desktop/test.xlsx";
  701. Workbook workbook = WorkbookFactory.create(new File(url));
  702. Sheet sheet = workbook.getSheetAt(0);
  703. Cell cell = sheet.getRow(0).getCell(0);
  704. FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
  705. CellType cellType = evaluator.evaluateFormulaCellEnum(cell);
  706. if (cellType == CellType.NUMERIC) {
  707. double value = cell.getNumericCellValue();
  708. System.out.println("公式计算结果:" + value);
  709. } else if (cellType == CellType.STRING) {
  710. String value = cell.getStringCellValue();
  711. System.out.println("公式计算结果:" + value);
  712. }
  713. cell.setCellFormula("B1+C1+D1");
  714. evaluator.clearAllCachedResultValues();
  715. cellType = evaluator.evaluateFormulaCellEnum(cell);
  716. if (cellType == CellType.NUMERIC) {
  717. double value = cell.getNumericCellValue();
  718. System.out.println("公式计算结果:" + value);
  719. } else if (cellType == CellType.STRING) {
  720. String value = cell.getStringCellValue();
  721. System.out.println("公式计算结果:" + value);
  722. }
  723. }catch (IOException | InvalidFormatException e){
  724. e.printStackTrace();
  725. }
  726. }
  727. public static Map<String, String> getElementCell(String uri){
  728. return getElementCell(uri,null,null);
  729. }
  730. public static Map<String, String> getElementCell(String uri,String key) {
  731. return getElementCell(uri,key,null);
  732. }
  733. public static Map<String, String> getElementCell(String uri,String key,Document document) {
  734. try {
  735. String filter=" [keyname]";
  736. if(Func.isNotBlank(key)){
  737. filter="[keyname^="+key+"__]";
  738. }
  739. if(document==null){
  740. InputStream inputStreamByUrl = FileUtils.getInputStreamByUrl(uri);
  741. document=Jsoup.parse(IoUtil.readToString(inputStreamByUrl));
  742. }
  743. Map<String,String> result= document
  744. .select("table").first()
  745. .select(filter).stream()
  746. .map(d -> d.attr("keyname")).filter(StringUtils::isNotEmpty).map(e -> e.split("__"))
  747. .collect(
  748. Collectors.toMap(
  749. b -> b[0],
  750. b -> b[1],
  751. (v1, v2) -> v1 + ";" + v2
  752. )
  753. );
  754. if(result.size()>0){
  755. for(Map.Entry<String,String> entry:result.entrySet()){
  756. entry.setValue(FormulaUtils.coordsSorted(entry.getValue()));
  757. }
  758. }
  759. return result;
  760. }catch (Exception e){
  761. e.printStackTrace();
  762. return new HashMap<>();
  763. }
  764. }
  765. public static Map<String, String> getElementExcelCoords(String uri){
  766. return getElementExcelCoords(uri,null,null);
  767. }
  768. public static Map<String, String> getElementExcelCoords(Document document){
  769. return getElementExcelCoords(null,null,document);
  770. }
  771. public static Map<String, String> getElementExcelCoords(String uri,String key,Document document){
  772. try {
  773. String filter=" [keyname]";
  774. if(Func.isNotBlank(key)){
  775. filter="[keyname^="+key+"__]";
  776. }
  777. if(document==null){
  778. InputStream inputStreamByUrl = FileUtils.getInputStreamByUrl(uri);
  779. document=Jsoup.parse(IoUtil.readToString(inputStreamByUrl));
  780. }
  781. Map<String,String> result= document
  782. .select("table").first()
  783. .select(filter).stream()
  784. .filter(d -> Func.isNotEmpty(d.attr("keyname"))).filter(StringUtils::isNotEmpty).map(e ->new String[]{e.attr("keyname").split("__")[0],e.attr("y1")+"_"+e.attr("x1")})
  785. .collect(
  786. Collectors.toMap(
  787. b -> b[0],
  788. b -> b[1],
  789. (v1, v2) -> v1 + ";" + v2
  790. )
  791. );
  792. if(result.size()>0){
  793. for(Map.Entry<String,String> entry:result.entrySet()){
  794. entry.setValue(FormulaUtils.coordsSorted(entry.getValue()));
  795. }
  796. }
  797. return result;
  798. }catch (Exception e){
  799. e.printStackTrace();
  800. return new HashMap<>();
  801. }
  802. }
  803. public static LinkedHashMap<String,String> analyzeHtml(String uri,String key,Document document){
  804. try {
  805. String filter=" [keyname]";
  806. if(Func.isNotBlank(key)){
  807. filter="[keyname^="+key+"__]";
  808. }
  809. if(document==null){
  810. InputStream inputStreamByUrl = FileUtils.getInputStreamByUrl(uri);
  811. document=Jsoup.parse(IoUtil.readToString(inputStreamByUrl));
  812. }
  813. LinkedHashMap<String,String> map= document.select("table").first()
  814. .select(filter).stream()
  815. .filter(d -> Func.isNotEmpty(d.attr("keyname"))&&d.attr("keyname").split("__")[0].length()>3)
  816. .sorted(Comparator.comparingInt(e->Integer.parseInt(e.attr("keyname").split("__")[0].split("_")[1])))
  817. .collect(Collectors.toMap(e->e.attr("placeholder"),e->e.attr("keyname"),(v1,v2)-> v1+","+v2,LinkedHashMap::new));
  818. return map;
  819. }catch (Exception e){
  820. e.printStackTrace();
  821. }
  822. return new LinkedHashMap<>();
  823. }
  824. /* public static void main(String[] args) {
  825. String uri="C:\\www\\wwwroot\\Users\\hongchuangyanfa\\Desktop\\privateUrl\\1661661730033369088.html";
  826. analyzeHtml(uri,"",null);
  827. }*/
  828. /*解析html里的电签关键字*/
  829. public static Map<String,String> getESignMap(Document document){
  830. Map<String,String> result = new HashMap<>();
  831. if(document!=null) {
  832. Elements list = document.getElementsByAttribute("dqid");
  833. if (list != null && !list.isEmpty()) {
  834. list.stream().forEach(e -> {
  835. String dqid = e.attr("dqid");
  836. int y1=0;
  837. int x1=0;
  838. if (!e.hasAttr("y1") && !e.hasAttr("x1")&&e.children().size()>0) {
  839. Element element = e.children().get(0);
  840. y1 = Func.toInt(element.attr("y1"));
  841. x1 = Func.toInt(element.attr("x1"));
  842. }else {
  843. y1 = Func.toInt(e.attr("y1"));
  844. x1 = Func.toInt(e.attr("x1"));
  845. }
  846. result.put(y1+"_"+x1,dqid);
  847. });
  848. }
  849. }
  850. return result;
  851. }
  852. public static List<ElementData> setScale(Integer scale, List<ElementData> data){
  853. if(scale==null){
  854. scale=StringUtils.getScale(data.stream().map(ElementData::getValue).filter(StringUtils::isDouble).collect(Collectors.toList()));
  855. }
  856. Integer finalScale = scale;
  857. return data.stream().peek(e->{if(StringUtils.isDouble(e.getValue())){e.setValue(StringUtils.number2StringZero(e.getValue(),finalScale));}}).collect(Collectors.toList());
  858. }
  859. /**
  860. * @Description 定位信息排序
  861. * @Param [coords]
  862. * @return java.lang.String
  863. * @Author yangyj
  864. * @Date 2023.07.11 15:39
  865. **/
  866. public static String coordsSorted(String coords){
  867. if(StringUtils.isNotEmpty(coords)){
  868. List<String> dataList=Arrays.asList(coords.split(";"));
  869. if(dataList.size()>2){
  870. LinkedList<Integer> list=dataList.stream().map(e->e.split("_")[1]).distinct().map(Integer::parseInt).sorted(Comparator.comparingInt(e->e)).collect(Collectors.toCollection(LinkedList::new));
  871. if(list.getLast()-list.getFirst()>list.size()-1){
  872. coords=dataList.stream()
  873. .sorted(Comparator.comparingInt((String str) -> Integer.parseInt(str.split("_")[1]))
  874. .thenComparingInt(str -> Integer.parseInt(str.split("_")[0])))
  875. .collect(Collectors.joining(";"));
  876. }
  877. }
  878. }
  879. return coords;
  880. }
  881. public static String coordsSorted2(String coords){
  882. if(StringUtils.isNotEmpty(coords)){
  883. List<String> dataList=Arrays.asList(coords.split(";"));
  884. if(dataList.size()>2){
  885. /*判断分区:根据行列长度*/
  886. List<Integer> row =dataList.stream().map(e->e.split("_")[0]).distinct().map(Integer::parseInt).collect(Collectors.toList());
  887. List<Integer> column=dataList.stream().map(e->e.split("_")[1]).distinct().map(Integer::parseInt).collect(Collectors.toList());
  888. if(row.size()>=column.size()){
  889. /*纵向*/
  890. if(column.size()>1){
  891. List<List<Integer>> consecutiveGroups = IntStream.range(0, column.size())
  892. .boxed()
  893. .collect(Collectors.collectingAndThen(
  894. Collectors.groupingBy(
  895. i -> i - column.get(i),
  896. LinkedHashMap::new,
  897. Collectors.mapping(column::get, Collectors.toList())
  898. ),
  899. map -> new ArrayList<>(map.values())
  900. ));
  901. }
  902. }
  903. /* 确定区内方向:*/
  904. }
  905. }
  906. return coords;
  907. }
  908. /* public static void main(String[] args) {
  909. List<Integer> column = Arrays.asList(1, 2, 3, 5, 6, 7, 9, 11, 17);
  910. List<List<Integer>> consecutiveGroups = IntStream.range(0, column.size())
  911. .boxed()
  912. .collect(Collectors.collectingAndThen(
  913. Collectors.groupingBy(
  914. i -> i - column.get(i),
  915. LinkedHashMap::new,
  916. Collectors.mapping(column::get, Collectors.toList())
  917. ),
  918. map -> new ArrayList<>(map.values())
  919. ));
  920. AtomicInteger i = new AtomicInteger(column.get(0));
  921. List<List<Integer>> consecutiveGroups2= new ArrayList<>(column.stream().collect(Collectors.groupingBy(e -> e - i.getAndSet(e) > 1, LinkedHashMap::new, Collectors.toList())).values());
  922. System.out.println();
  923. }*/
  924. public static List<Object> slice(List<LocalVariable> local, String formula){
  925. int min =0;
  926. List<Object> result = new ArrayList<>();
  927. try {
  928. pretreatment(local,formula);
  929. List<Object> r= local.stream().map(e-> {
  930. /*所有依赖元素的内容必须非空才进行计算,否则返回空值*/
  931. return e.hasEmptyElementValue()?"": Expression.parse(e.getFormula()).calculate(e.getCurrentMap()).toString();
  932. }).collect(Collectors.toList());
  933. if(CollectionUtil.isNotEmpty(r)&&r.stream().anyMatch(StringUtils::isNotEmpty)){
  934. result.addAll(r);
  935. }
  936. }catch (Exception e){
  937. StaticLog.error("公式:{},执行出错",formula);
  938. }
  939. return result;
  940. }
  941. public static void pretreatment(List<LocalVariable> local,String formula){
  942. formula=StringUtils.removeMultiSpace(formula);
  943. if(formula.contains("LIST")){
  944. Matcher m=RegexUtils.matcher("\\(([^)]*)\\)/LIST",formula);
  945. while (m.find()){
  946. List<String> codes=getCodeList(m.group(1).replaceAll("[+-]",","));
  947. local=local.stream().peek(e->{
  948. @SuppressWarnings("unckecked")
  949. Map<String,Object> map = (Map<String, Object>) e.getCurrentMap().getOrDefault("E",new HashMap<>());
  950. int listSize=(int)codes.stream().filter(c->StringUtils.isNotEmpty(map.get(c))).count();
  951. if(listSize<=0||listSize>codes.size()){
  952. listSize=codes.size();
  953. }
  954. map.put("LIST",listSize);
  955. }).collect(Collectors.toList());
  956. }
  957. }
  958. }
  959. /**从方法参数中获取全部code*/
  960. public static List<String> getCodeList(String param){
  961. List<String> list = new ArrayList<>();
  962. if(StringUtils.isNotEmpty(param)){
  963. Arrays.stream(param.split(",")).forEach(s->{
  964. list.add(s.replaceAll("[E\\[\\]']",""));
  965. });
  966. }
  967. return list;
  968. }
  969. /**从时间段中获取最后一个日期*/
  970. static final String RANGE_DATE_REG="^\\[(\\d{4}[年.\\-]\\d{2}[月.\\-]\\d{2}[日]?),\\s+(\\d{4}[年.\\-]\\d{2}[月.\\-]\\d{2}[日]?)]$";
  971. public static String range2end(String t){
  972. if(t!=null&&Pattern.matches(RANGE_DATE_REG,t)){
  973. t=t.replaceAll("^\\[|]$","").split(",")[1].trim();
  974. }
  975. return t;
  976. }
  977. public static List<String> duration2date(String duration){
  978. try {
  979. if (duration != null && Pattern.matches(RANGE_DATE_REG, duration)) {
  980. return Arrays.stream(duration.replaceAll("^\\[|]$", "").split(",")).map(String::trim).map(s -> new DateTime(s).toString(DatePattern.NORM_DATE_PATTERN)).collect(Collectors.toList());
  981. }
  982. return Collections.singletonList(new DateTime(duration).toString(DatePattern.NORM_DATE_PATTERN));
  983. }catch (Exception e){
  984. return Collections.singletonList(new DateTime().toString(DatePattern.NORM_DATE_PATTERN));
  985. }
  986. }
  987. public static FormData createFormDataFast(String name,String code,String values,String coords){
  988. if(StringUtils.isNotEmpty(code,name)){
  989. if(StringUtils.isNotEmpty(coords)) {
  990. /*定位信息存在才合法*/
  991. List<Coords> coordsList = Stream.of(coords).flatMap(s -> Arrays.stream(s.split(";"))).map(s -> {
  992. String[] xy = s.split("_");
  993. return new Coords(xy[1], xy[0]);
  994. }).collect(Collectors.toList());
  995. List<ElementData> eds = new ArrayList<>();
  996. if (StringUtils.isNotEmpty(values)) {
  997. String[] pages = values.split(";;");
  998. for (int index = 0; index < pages.length; index++) {
  999. String pg = pages[index];
  1000. if (Func.isNotBlank(pg)) {
  1001. String[] val = pg.split("☆");
  1002. Map<String, Object> tmpMap = new LinkedHashMap<>();
  1003. for (String s : val) {
  1004. String[] t = s.split("_\\^_");
  1005. String[] c = t[1].split("_");
  1006. tmpMap.put(StringUtils.join(code, 0, index, Func.toInt(c[1]), Func.toInt(c[0]), StringPool.AT), t[0]);
  1007. }
  1008. for (Coords c : coordsList) {
  1009. Object data = null;
  1010. String key = StringUtils.join(code, 0, index, c.getX(), c.getY(), StringPool.AT);
  1011. if (tmpMap.containsKey(key)) {
  1012. data = tmpMap.get(key);
  1013. }
  1014. eds.add(new ElementData(index, 0, data, c.getX(), c.getY()));
  1015. }
  1016. }
  1017. }
  1018. } else {
  1019. eds = coordsList.stream().map(c -> new ElementData(0, 0, null, c.getX(), c.getY())).collect(Collectors.toList());
  1020. }
  1021. FormData one = new FormData(code, eds, null, coords);
  1022. one.setEName(name);
  1023. /*备份原始数据,用于更新比较*/
  1024. one.init();
  1025. return one;
  1026. }
  1027. }
  1028. return null;
  1029. }
  1030. public static void mainT(String[] args) throws IOException {
  1031. XYSeries series = new XYSeries("每月实际完成");
  1032. series.add(10.2, 1.82);
  1033. series.add(11.9, 1.86);
  1034. series.add(15.9, 1.87);
  1035. series.add(19.3, 1.85);
  1036. series.add(20.3, 1.80);
  1037. XYSeriesCollection dataset = new XYSeriesCollection();
  1038. dataset.addSeries(series);
  1039. JFreeChart chart = ChartFactory.createXYLineChart(
  1040. "按月进度", // 标题
  1041. "X", // 横轴标题
  1042. "Y", // 纵轴标题
  1043. dataset, // 数据集
  1044. PlotOrientation.VERTICAL, // 图表方向
  1045. true, // 是否显示图例
  1046. false, // 是否生成工具提示
  1047. false // 是否生成URL链接
  1048. );
  1049. // 设置字体
  1050. Font titleFont = new Font("SimSun", Font.PLAIN, 18); // 指定使用宋体字体
  1051. Font axisFont = new Font("SimSun", Font.PLAIN, 12); // 指定使用宋体字体
  1052. // 设置标题字体
  1053. TextTitle title = chart.getTitle();
  1054. title.setFont(titleFont);
  1055. XYPlot plot = (XYPlot) chart.getPlot();
  1056. XYSplineRenderer renderer = new XYSplineRenderer();
  1057. plot.setRenderer(renderer);
  1058. plot.setBackgroundPaint(Color.WHITE);
  1059. // Set the line stroke and shape for the renderer
  1060. renderer.setSeriesStroke(0, new BasicStroke(2.0f));
  1061. Shape circle = new Ellipse2D.Double(-3, -3, 6, 6);
  1062. renderer.setSeriesShape(0, circle);
  1063. renderer.setSeriesPaint(0, Color.BLUE);
  1064. // 自定义 X 轴刻度
  1065. NumberAxis domainAxis = (NumberAxis) plot.getDomainAxis();
  1066. domainAxis.setTickUnit(new NumberTickUnit(5)); // 设置刻度间隔
  1067. domainAxis.setRange(0.0, 25); // 设置轴的范围
  1068. // 自定义 Y 轴刻度
  1069. NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
  1070. rangeAxis.setTickUnit(new NumberTickUnit(0.01)); // 设置刻度间隔
  1071. rangeAxis.setRange(1.79, 1.90); // 设置轴的范围
  1072. // 添加横杠
  1073. for(int i=175;i<190;i++){
  1074. ValueMarker marker = new ValueMarker((double) i /100);
  1075. marker.setPaint(Color.BLUE); // 横杠的颜色
  1076. plot.addRangeMarker(marker);
  1077. }
  1078. ChartPanel chartPanel = new ChartPanel(chart);
  1079. chartPanel.setPreferredSize(new Dimension(500, 400));
  1080. // 保存图表为图片
  1081. int width = 800;
  1082. int height = 600;
  1083. ChartUtils.saveChartAsPNG(new File("C:/Users/yangyj/Desktop/Swap_space/poi_statistics.png"), chart, width, height);
  1084. }
  1085. private static CategoryDataset createDataset( double[] actualProgress, double[] plannedProgress) {
  1086. String[] months = {"一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"};
  1087. /* int[] actualProgress = {10, 15, 18, 27, 35, 48};
  1088. int[] plannedProgress = {10, 15, 20, 25, 30, 35};*/
  1089. DefaultCategoryDataset dataset = new DefaultCategoryDataset();
  1090. for (int i = 0; i < actualProgress.length; i++) {
  1091. dataset.addValue(actualProgress[i], "实际进度", months[i]);
  1092. }
  1093. for (int i = 0; i < plannedProgress.length; i++) {
  1094. dataset.addValue(plannedProgress[i], "计划进度", months[i]);
  1095. }
  1096. return dataset;
  1097. }
  1098. private static JFreeChart createChart(CategoryDataset dataset) {
  1099. JFreeChart chart = ChartFactory.createBarChart(
  1100. "施工进度对比图",
  1101. "月份",
  1102. "进度 (%)",
  1103. dataset,
  1104. PlotOrientation.VERTICAL,
  1105. true,
  1106. true,
  1107. false
  1108. );
  1109. CategoryPlot plot = (CategoryPlot) chart.getPlot();
  1110. // 设置中文字体以避免乱码
  1111. Font font = new Font("宋体", Font.PLAIN, 12);
  1112. chart.getTitle().setFont(font);
  1113. plot.getDomainAxis().setTickLabelFont(font);
  1114. plot.getDomainAxis().setLabelFont(font);
  1115. plot.getRangeAxis().setTickLabelFont(font);
  1116. plot.getRangeAxis().setLabelFont(font);
  1117. chart.getLegend().setItemFont(font);
  1118. plot.setDomainAxis(new CategoryAxis("月份"));
  1119. plot.setRangeAxis(new NumberAxis("进度 (%)"));
  1120. BarRenderer barRenderer = new BarRenderer();
  1121. barRenderer.setSeriesPaint(0, new Color(0, 0, 255));
  1122. barRenderer.setSeriesPaint(1, new Color(0, 255, 0));
  1123. plot.setRenderer(barRenderer);
  1124. // 添加第二个数据集,绘制为曲线
  1125. DefaultCategoryDataset lineDataset = new DefaultCategoryDataset();
  1126. String[] months = {"一月", "二月", "三月", "四月", "五月", "六月"};
  1127. int[] actualProgress = {10, 15, 18, 27, 35, 48};
  1128. int[] plannedProgress = {10, 15, 20, 25, 30, 35};
  1129. for (int i = 0; i < actualProgress.length; i++) {
  1130. lineDataset.addValue(actualProgress[i], "实际进度", months[i]);
  1131. }
  1132. for (int i = 0; i < plannedProgress.length; i++) {
  1133. lineDataset.addValue(plannedProgress[i], "计划进度", months[i]);
  1134. }
  1135. plot.setDataset(1, lineDataset);
  1136. plot.mapDatasetToRangeAxis(1, 0);
  1137. LineAndShapeRenderer lineRenderer = new LineAndShapeRenderer();
  1138. lineRenderer.setSeriesPaint(0, new Color(255, 0, 0));
  1139. lineRenderer.setSeriesPaint(1, new Color(255, 165, 0));
  1140. plot.setRenderer(1, lineRenderer);
  1141. // 设置 X 轴标签
  1142. CategoryAxis domainAxis = plot.getDomainAxis();
  1143. domainAxis.setCategoryLabelPositions(
  1144. org.jfree.chart.axis.CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 4.0)
  1145. );
  1146. // 设置 Y 轴范围
  1147. ValueAxis rangeAxis = plot.getRangeAxis();
  1148. rangeAxis.setRange(0, 100);
  1149. return chart;
  1150. }
  1151. public static String getSysLocalFileUrl() {
  1152. String file_path = ParamCache.getValue(CommonConstant.SYS_LOCAL_URL);
  1153. if (org.springblade.common.utils.SystemUtils.isMacOs()) {
  1154. file_path = "/Users/hongchuangyanfa/Desktop/";
  1155. } else if (SystemUtils.isWindows()) {
  1156. file_path = "C://upload//";
  1157. }
  1158. return file_path;
  1159. }
  1160. public static byte[] chapterScheduleChart( double[] actualProgress ,double[] plannedProgress){
  1161. CategoryDataset dataset = createDataset(actualProgress,plannedProgress);
  1162. JFreeChart chart = createChart(dataset);
  1163. try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
  1164. ChartUtils.writeChartAsPNG(out, chart, 800, 600);
  1165. return out.toByteArray();
  1166. } catch (IOException e) {
  1167. e.printStackTrace();
  1168. }
  1169. return null;
  1170. }
  1171. public static String chapterScheduleChartUrl( LinkedHashMap<Integer,Double> actualMap, LinkedHashMap<Integer,Double> plannedMap,int startYear,int endYear){
  1172. try {
  1173. JFreeChart chart =chartTest(actualMap,plannedMap, startYear, endYear);
  1174. String path= getSysLocalFileUrl() + "/pdf//"+SnowFlakeUtil.getId()+".png";
  1175. ChartUtils.saveChartAsPNG(new File(path), chart, 1200, 900);
  1176. return path;
  1177. } catch (Exception e) {
  1178. e.printStackTrace();
  1179. }
  1180. return null;
  1181. }
  1182. public static JFreeChart chartTest2(double[] actualProgressData ,double[] plannedProgressData) throws IOException {
  1183. // 创建数据集
  1184. XYSeries actualProgress = new XYSeries("实际进度");
  1185. XYSeries plannedProgress = new XYSeries("计划进度");
  1186. // 填充数据集
  1187. for (int i = 0; i < actualProgressData.length; i++) {
  1188. actualProgress.add(i, actualProgressData[i]);
  1189. plannedProgress.add(i, plannedProgressData[i]);
  1190. }
  1191. XYSeriesCollection dataset = new XYSeriesCollection();
  1192. dataset.addSeries(actualProgress);
  1193. dataset.addSeries(plannedProgress);
  1194. // 创建图表
  1195. JFreeChart chart = ChartFactory.createXYLineChart(
  1196. "施工进度对比图", // 标题
  1197. "日期进度 (%)", // X轴标签
  1198. "完成量 (%)", // Y轴标签
  1199. dataset, // 数据集
  1200. org.jfree.chart.plot.PlotOrientation.VERTICAL, // 方向
  1201. true, // 显示图例
  1202. true, // 生成工具
  1203. false // 生成URL
  1204. );
  1205. // 设置中文字体以避免乱码
  1206. Font font = new Font("宋体", Font.PLAIN, 12);
  1207. chart.getTitle().setFont(font);
  1208. chart.getLegend().setItemFont(font);
  1209. XYPlot plot = chart.getXYPlot();
  1210. plot.setDomainGridlinesVisible(true);
  1211. plot.setRangeGridlinesVisible(true);
  1212. plot.setDomainGridlinePaint(Color.LIGHT_GRAY);
  1213. plot.setRangeGridlinePaint(Color.LIGHT_GRAY);
  1214. plot.setBackgroundPaint(Color.WHITE);
  1215. XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
  1216. renderer.setSeriesPaint(0, Color.BLUE);
  1217. renderer.setSeriesPaint(1, Color.GREEN);
  1218. plot.setRenderer(renderer);
  1219. // 设置顶部的月份轴
  1220. /* String[] months = {"一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"};
  1221. String[] years = {"2023年", "2024年", "2025年", "2026年"};*/
  1222. String[] months =new String[4 * 12];
  1223. for(int i=2023;i<=2026;i++){
  1224. for(int n=1;n<=12;n++){
  1225. int index=(i-2023)*12+n-1;
  1226. months[index]=i+"年"+n+"月";
  1227. }
  1228. }
  1229. // 设置顶部的月份轴
  1230. SymbolAxis monthAxis = new SymbolAxis("月份", months) ;
  1231. monthAxis.setTickLabelFont(font);
  1232. monthAxis.setLabelFont(font);
  1233. monthAxis.setVerticalTickLabels(true);
  1234. monthAxis.setRange(0, 47); // 设置范围来适应月份标签
  1235. plot.setDomainAxis(monthAxis);
  1236. // 设置Y轴的范围
  1237. NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
  1238. rangeAxis.setRange(0, 100); // Y轴从0到100
  1239. rangeAxis.setTickUnit(new NumberTickUnit(10));
  1240. rangeAxis.setLabelFont(font);
  1241. rangeAxis.setTickLabelFont(font);
  1242. /* // 添加月份轴
  1243. plot.setRangeAxis(2, monthAxis);
  1244. plot.mapDatasetToDomainAxis(0, 1); // 将数据映射到月份轴*/
  1245. return chart;
  1246. }
  1247. public static JFreeChart chartTest(LinkedHashMap<Integer,Double> actualMap, LinkedHashMap<Integer,Double> plannedMap,int startYear,int endYear) {
  1248. // 创建完整的数据集
  1249. XYSeriesCollection dataset = new XYSeriesCollection();
  1250. // 创建日期范围
  1251. long startDate=BaseUtils.getTimeMs(startYear,1);
  1252. long endDate = BaseUtils.getTimeMs(endYear,12);
  1253. // 初始化数据系列
  1254. XYSeries actualSeries = new XYSeries("实际进度");
  1255. XYSeries plannedSeries = new XYSeries("计划进度");
  1256. // 填充数据系列
  1257. actualMap.forEach((yearMonth,ratio)->{
  1258. actualSeries.add(BaseUtils.getTimeMs(yearMonth/100,yearMonth%100),ratio);
  1259. });
  1260. plannedMap.forEach((yearMonth,ratio)->{
  1261. plannedSeries.add(BaseUtils.getTimeMs(yearMonth/100,yearMonth%100),ratio);
  1262. });
  1263. dataset.addSeries(actualSeries);
  1264. dataset.addSeries(plannedSeries);
  1265. // 创建图表
  1266. JFreeChart chart = ChartFactory.createTimeSeriesChart(
  1267. "施工进度对比图",
  1268. "时间",
  1269. "完成量 (%)",
  1270. dataset,
  1271. true,
  1272. true,
  1273. false);
  1274. // 设置中文字体以避免乱码
  1275. Font font = new Font("宋体", Font.PLAIN, 12);
  1276. chart.getTitle().setFont(font);
  1277. chart.getLegend().setItemFont(font);
  1278. XYPlot plot = (XYPlot) chart.getPlot();
  1279. plot.setDomainGridlinesVisible(true);
  1280. plot.setRangeGridlinesVisible(true);
  1281. plot.setDomainGridlinePaint(Color.LIGHT_GRAY);
  1282. plot.setRangeGridlinePaint(Color.LIGHT_GRAY);
  1283. plot.setBackgroundPaint(Color.WHITE);
  1284. XYItemRenderer renderer = new XYSplineRenderer();
  1285. renderer.setSeriesPaint(0, Color.BLUE);
  1286. renderer.setSeriesPaint(1, Color.GREEN);
  1287. plot.setRenderer(renderer);
  1288. // 设置 DateAxis
  1289. DateAxis monthAxis = (DateAxis) plot.getDomainAxis();
  1290. monthAxis.setDateFormatOverride(new SimpleDateFormat("yyyy年MM月"));
  1291. monthAxis.setTickLabelFont(font);
  1292. monthAxis.setLabelFont(font);
  1293. monthAxis.setLowerBound(startDate);
  1294. monthAxis.setUpperBound(endDate);
  1295. // 确保每个月都有一个标签
  1296. monthAxis.setTickUnit(new DateTickUnit(DateTickUnitType.MONTH,1));
  1297. monthAxis.setVerticalTickLabels(true);
  1298. // 设置Y轴的范围
  1299. NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
  1300. rangeAxis.setRange(0, 100);
  1301. rangeAxis.setTickUnit(new NumberTickUnit(10));
  1302. rangeAxis.setLabelFont(font);
  1303. rangeAxis.setTickLabelFont(font);
  1304. return chart;
  1305. }
  1306. public static void main2(String[] args) throws IOException {
  1307. LinkedHashMap<Integer,Double> actualProgress = new LinkedHashMap<>();
  1308. LinkedHashMap<Integer,Double> plannedProgress = new LinkedHashMap<>();
  1309. JFreeChart chart = chartTest(actualProgress,plannedProgress,2023,2025);
  1310. /* try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
  1311. BufferedImage bufferedImage = chart.createBufferedImage(800, 600);
  1312. ImageIO.write(bufferedImage, "png", out);
  1313. FileOutputStream fos = new FileOutputStream("C:/Users/yangyj/Desktop/Swap_space/poi_statistics.png");
  1314. fos.write(out.toByteArray());
  1315. } catch (IOException e) {
  1316. e.printStackTrace();
  1317. }*/
  1318. try {
  1319. ChartUtils.saveChartAsPNG(new File("C:/Users/yangyj/Desktop/Swap_space/poi_statistics.png"), chart, 1200, 900);
  1320. // 保存图表到内存
  1321. } catch (Exception e) {
  1322. e.printStackTrace();
  1323. }
  1324. }
  1325. /**字符串sha256映射*/
  1326. public static String sha256(String input) {
  1327. try {
  1328. MessageDigest digest = MessageDigest.getInstance("SHA-256");
  1329. byte[] encodedHash = digest.digest(input.getBytes(StandardCharsets.UTF_8));
  1330. StringBuilder hexString = new StringBuilder();
  1331. for (byte b : encodedHash) {
  1332. String hex = Integer.toHexString(0xff & b);
  1333. if (hex.length() == 1) {
  1334. hexString.append('0');
  1335. }
  1336. hexString.append(hex);
  1337. }
  1338. return hexString.toString();
  1339. } catch (NoSuchAlgorithmException e) {
  1340. e.printStackTrace();
  1341. }
  1342. return "";
  1343. }
  1344. /**根据步长获取字符*/
  1345. public static String getEveryNthChar(String input, int step) {
  1346. StringBuilder result = new StringBuilder();
  1347. for (int i = 0; i < input.length(); i += step) {
  1348. result.append(input.charAt(i));
  1349. }
  1350. return result.toString();
  1351. }
  1352. /**最大循环次数*/
  1353. public static int MAX_LOOP=20;
  1354. /**
  1355. * @Description 当前提交表单数据公式执行最小影响元素范围
  1356. * @Param [curTableNames:当前提交页面对应表编号, processFds:当前工序包含的所有元素]
  1357. * @Author yangyj
  1358. * @Date 2023.10.09 15:26
  1359. **/
  1360. public static List<FormData> registerFd(List<String> curTableNames, List<FormData> processFds){
  1361. Map<Boolean,List<FormData>> group = processFds.stream().collect(Collectors.partitioningBy(e->curTableNames.contains(e.getTableName())));
  1362. List<FormData> curFormDatas =group.get(true);
  1363. /*提交叶包含元素*/
  1364. List<FormData> initiator= new ArrayList<>(curFormDatas);
  1365. List<FormData> other=group.get(false);
  1366. /*当前提交页元素影响到的元素都要重新执行公式*/
  1367. pick(curFormDatas,other,curFormDatas,fds->fds.stream().map(FormData::getCode).collect(Collectors.toSet()));
  1368. /*当前提交页的元素公式依赖加载*/
  1369. pick(initiator,other,curFormDatas,fds->fds.stream().filter(f->f.executable()&&f.getFormula().getRely()!=null).flatMap(f->f.getFormula().getRelyList().stream()).collect(Collectors.toSet()));
  1370. return curFormDatas;
  1371. }
  1372. /**
  1373. * @Description 调训符合条件的元素
  1374. * @Param [initiator 初始集合, other 待选集合, curFormDatas 结果集, function:挑选方法]
  1375. * @Author yangyj
  1376. * @Date 2023.10.12 14:53
  1377. **/
  1378. public static void pick(List<FormData> initiator,List<FormData> other,List<FormData> curFormDatas ,Function<List<FormData>,Set<String>> function){
  1379. List<FormData> curFormDatasAdd=new ArrayList<>(initiator);
  1380. int loop=0;
  1381. do{
  1382. loop++;
  1383. Set<String> codeSet= function.apply(curFormDatasAdd);
  1384. Map<Boolean,List<FormData>> groupTmp = other.stream().collect(Collectors.partitioningBy(e->codeSet.contains(e.getCode())));
  1385. curFormDatasAdd=groupTmp.get(true);
  1386. if(curFormDatasAdd.isEmpty()){
  1387. loop=MAX_LOOP;
  1388. }else{
  1389. curFormDatas.addAll(curFormDatasAdd);
  1390. }
  1391. other=groupTmp.get(false);
  1392. }while (!other.isEmpty()&&loop<MAX_LOOP);
  1393. }
  1394. /**最小加载页面,只要包含当前提交元素的页面都需要加载*/
  1395. public static Map<String,List<Long>> relatedPages(List<FormData> curFormDatas ,List<NodeTable> tableAll){
  1396. Set<String> initTableNames= curFormDatas.stream().map(FormData::getTableName).collect(Collectors.toSet());
  1397. return tableAll.stream().filter(e->initTableNames.contains(e.getInitTableName())).collect(Collectors.groupingBy(NodeTable::getInitTableName,Collectors.mapping(NodeTable::getPKeyId,Collectors.toList())));
  1398. }
  1399. /*比较两组单元格内容是否一样*/
  1400. public static boolean compareElementDataList(List<ElementData> before ,List<ElementData> cur){
  1401. if(Func.isNotEmpty(before)&&Func.isNotEmpty(cur)&&before.size()==cur.size()){
  1402. String sa= before.stream().map(ElementData::stringValue).collect(Collectors.joining());
  1403. String sc= cur.stream().map(ElementData::stringValue).collect(Collectors.joining());
  1404. return sa.equals(sc);
  1405. }
  1406. return false;
  1407. }
  1408. /**分割treeCode*/
  1409. public static List<String> treeCodeSplit(String treeCode){
  1410. List<String> result = new ArrayList<>();
  1411. if(Func.isNotBlank(treeCode)){
  1412. /*字符总长度*/
  1413. int max =treeCode.length()-3,
  1414. /*累计字符长度字符*/
  1415. sum=0,
  1416. /*第几次循环*/
  1417. count=0;
  1418. do{
  1419. result.add(treeCode.substring(0, sum+=Math.min(3,++count)));
  1420. }while (sum<max&&count<MAX_LOOP);
  1421. }
  1422. return result;
  1423. }
  1424. /* public static void main(String[] args) {
  1425. System.out.println(milestone("k8+120.23"));
  1426. }*/
  1427. /*从测点名称中获取里程*/
  1428. public static Double milestone(String s){
  1429. Pattern pattern=Pattern.compile("(?i)K(\\d+)\\+([\\d.]+)");
  1430. Matcher matcher = pattern.matcher(s);
  1431. if(matcher.find()){
  1432. return Double.parseDouble(matcher.group(1))*1000+ Double.parseDouble(matcher.group(2));
  1433. }
  1434. return null;
  1435. }
  1436. public static void sort( List<FormData> list,int n){
  1437. /*System.out.println("剩余计算次数:"+n+"次");*/
  1438. if(move(list)&&n>0){
  1439. sort(list,--n);
  1440. }
  1441. }
  1442. public static Boolean move( List<FormData> list){
  1443. for(int i=0;i<list.size();i++){
  1444. FormData f=list.get(i);
  1445. Matcher m =P.matcher(f.getFormula().getFormula());
  1446. List<String> cp = new ArrayList<>();
  1447. while (m.find()){
  1448. cp.add(m.group());
  1449. }
  1450. Map<Boolean,List<FormData>> map= list.stream().skip(i+1).collect(Collectors.partitioningBy(e->cp.contains(e.getCode())));
  1451. List<FormData> match =map.get(true);
  1452. if(CollectionUtil.isNotEmpty(match)){
  1453. for(FormData r:match){
  1454. list.remove(r);
  1455. }
  1456. list.addAll(0,match);
  1457. return true;
  1458. }
  1459. }
  1460. return false;
  1461. }
  1462. public static void relyParse(Formula f){
  1463. if(Func.isNotBlank(f.getFormula())){
  1464. List<String> l = new ArrayList<>();
  1465. Matcher m = P.matcher(f.getFormula());
  1466. while (m.find()){
  1467. String tmp =m.group().replaceAll("'","");
  1468. String cp=tmp;
  1469. if(tmp.indexOf(StringPool.COLON)!=tmp.lastIndexOf(StringPool.COLON)){
  1470. tmp=tmp.substring(tmp.indexOf(":")+1);
  1471. /*移除跨节点标识*/
  1472. f.setFormula(f.getFormula().replace(cp,tmp));
  1473. }
  1474. l.add(tmp);
  1475. }
  1476. if(l.size()>0){
  1477. f.setRely(String.join(",", l));
  1478. }else{
  1479. f.setRely("");
  1480. }
  1481. }
  1482. }
  1483. /*复制表页*/
  1484. public static WbsTreeContract copyPage(WbsTreeContract origin){
  1485. WbsTreeContract target = new WbsTreeContract();
  1486. BeanUtil.copy(origin, target);
  1487. target.setPKeyId(SnowFlakeUtil.getId());
  1488. target.setCreateTime(new Date());
  1489. String nodeName = origin.getNodeName();
  1490. String[] oldName = nodeName.split("__");
  1491. if (oldName.length>1) {
  1492. nodeName = oldName[0] + "__" + (Integer.parseInt(oldName[1]) + 1);
  1493. } else {
  1494. nodeName = nodeName + "__" + 1;
  1495. }
  1496. target.setNodeName(nodeName);
  1497. target.setIsCopeTab(2);
  1498. target.setIsTabPdf(1); // pdf 不能预览
  1499. target.setIsBussShow(1); // 是否隐藏表
  1500. target.setTabFileType(1);//没有上传附件
  1501. target.setPdfUrl("");
  1502. return target;
  1503. }
  1504. public static String recovery(List<ElementData> dataList) {
  1505. if (Func.isNotEmpty(dataList)) {
  1506. return dataList.stream().filter(e -> !e.isEmpty()).map(e -> e.stringValue() + "_^_" + e.getY() + "_" + e.getX()).collect(Collectors.joining("☆"));
  1507. }
  1508. return "";
  1509. }
  1510. private static final Map<Character, Integer> CHINESE_TO_ARABIC = new HashMap<>();
  1511. static {
  1512. CHINESE_TO_ARABIC.put('零', 0);
  1513. CHINESE_TO_ARABIC.put('一', 1);
  1514. CHINESE_TO_ARABIC.put('二', 2);
  1515. CHINESE_TO_ARABIC.put('三', 3);
  1516. CHINESE_TO_ARABIC.put('四', 4);
  1517. CHINESE_TO_ARABIC.put('五', 5);
  1518. CHINESE_TO_ARABIC.put('六', 6);
  1519. CHINESE_TO_ARABIC.put('七', 7);
  1520. CHINESE_TO_ARABIC.put('八', 8);
  1521. CHINESE_TO_ARABIC.put('九', 9);
  1522. CHINESE_TO_ARABIC.put('十', 10);
  1523. CHINESE_TO_ARABIC.put('百', 100);
  1524. CHINESE_TO_ARABIC.put('千', 1000);
  1525. CHINESE_TO_ARABIC.put('万', 10000);
  1526. }
  1527. public static int chineseToArabic(String chineseNumber) {
  1528. int result = 0;
  1529. int multiplier = 1;
  1530. for (int i = chineseNumber.length() - 1; i >= 0; i--) {
  1531. char c = chineseNumber.charAt(i);
  1532. if (CHINESE_TO_ARABIC.containsKey(c)) {
  1533. int value = CHINESE_TO_ARABIC.get(c);
  1534. if(value!=0&&value%10==0&&i!=0){
  1535. multiplier=value;
  1536. }else{
  1537. result=result+value*multiplier;
  1538. }
  1539. } else {
  1540. throw new IllegalArgumentException("Invalid Chinese numeral: " + c);
  1541. }
  1542. }
  1543. return result;
  1544. }
  1545. /*public static void main(String[] args) {
  1546. *//* System.out.println(chineseToArabic("二十九"));
  1547. System.out.println(chineseToArabic("一"));
  1548. System.out.println(chineseToArabic("十一"));*//*
  1549. System.out.println(chineseToArabic("十"));
  1550. *//* System.out.println(chineseToArabic("一百二十"));
  1551. System.out.println(chineseToArabic("一百二十二"));
  1552. System.out.println(chineseToArabic("一百零二"));*//*
  1553. }*/
  1554. /*获取引用code的元素*/
  1555. public static Stream<FormData> beRelyFrom( Map<String, FormData> formDataMap ,String code){
  1556. return formDataMap.values().stream().filter(e->e.executable()&& code.equals(e.getFormula().getRely()));
  1557. }
  1558. public static Stream<FormData> beRelyFrom( Map<String, FormData> formDataMap ,String tableNumber ,String keys){
  1559. Set<String> keySet = Arrays.stream(keys.split(",")).map(s->tableNumber+":"+s.trim()).collect(Collectors.toSet());
  1560. return formDataMap.values().stream().filter(e->e.executable()&& keySet.contains(e.getFormula().getRely()));
  1561. }
  1562. /*根据code查找元素 */
  1563. public static Optional<FormData> elementFindByCode( Map<String, FormData> formDataMap ,String code){
  1564. return formDataMap.values().stream().filter(e->code.equals(e.getCode())).findAny();
  1565. }
  1566. /*根据key查找元素 ,用于元素范围在同一张表情况*/
  1567. public static Optional<FormData> elementFindByKey( Map<String, FormData> fdm ,String key){
  1568. return fdm.values().stream().filter(e->key.equals(e.getCode().split(":")[1])).findAny();
  1569. }
  1570. /*创建T集合的指定字段fb的合计方法*/
  1571. public static <T> Function<List<T>, String> createSumFunction(Function<T,BigDecimal> fb) {
  1572. return (pl) -> pl.stream()
  1573. .map(fb)
  1574. .reduce(BigDecimal.ZERO, BigDecimal::add)
  1575. .toString();
  1576. }
  1577. public static List<TableInfo> getTableInfoList(JSONArray dataArray) {
  1578. if (dataArray != null && !dataArray.isEmpty()) {
  1579. List<TableInfo> result = new ArrayList<>();
  1580. for (int m = 0; m < dataArray.size(); m++) {
  1581. TableInfo tableInfo = new TableInfo();
  1582. com.alibaba.fastjson.JSONObject dataInfo2 = dataArray.getJSONObject(m);
  1583. //
  1584. tableInfo.setContractId(dataInfo2.getString("contractId"));
  1585. tableInfo.setPkeyId(dataInfo2.getString("pkeyId"));
  1586. tableInfo.setProjectId(dataInfo2.getString("projectId"));
  1587. //huangjn 填报的类型,施工或监理
  1588. tableInfo.setClassify(dataInfo2.getString("classify"));
  1589. //设置首件信息
  1590. setFirstData(dataInfo2, tableInfo);
  1591. //设置日志信息
  1592. setTheLogData(dataInfo2, tableInfo);
  1593. dataInfo2.fluentRemove("contractId")
  1594. .fluentRemove("pkeyId")
  1595. .fluentRemove("p_key_id")
  1596. .fluentRemove("projectId")
  1597. .fluentRemove("classify")
  1598. .fluentRemove("pickerKey")
  1599. .fluentRemove("id")
  1600. .fluentRemove("isFirst")
  1601. .fluentRemove("firstNodeId")
  1602. .fluentRemove("isTheLog")
  1603. .fluentRemove("theLogId")
  1604. .fluentRemove("linkTabIds")
  1605. .fluentRemove("recordTime")
  1606. .fluentRemove("businessId")
  1607. .fluentRemove("sourceUrl")
  1608. .fluentRemove("pdfUrl")
  1609. .fluentRemove("firstFileName")
  1610. .fluentRemove("");
  1611. // 计算数据
  1612. LinkedHashMap<String, List<String>> dataMap = dataInfo2.keySet().stream().filter(e -> e.contains("__")).collect(Collectors.groupingBy(e -> e.split("__")[0], LinkedHashMap<String, List<String>>::new, Collectors.toList()));
  1613. LinkedHashMap<String, String> dataMap2 = new LinkedHashMap<>();
  1614. // 字段组合
  1615. for (String k : dataMap.keySet()) {
  1616. if (dataMap.get(k).size() > 1 && !dataMap.get(k).contains("000Z")) {
  1617. String[] ziduan = dataMap.get(k).toArray(new String[]{});
  1618. String temp = "";
  1619. for (int i = 0; i < ziduan.length - 1; i++) {
  1620. for (int j = 0; j < ziduan.length - i - 1; j++) {
  1621. Integer tr = Integer.parseInt((ziduan[j].split("__")[1]).split("_")[0]);
  1622. Integer td = Integer.parseInt(ziduan[j].split("__")[1].split("_")[1]);
  1623. Integer tr_1 = Integer.parseInt(ziduan[j + 1].split("__")[1].split("_")[0]);
  1624. Integer td_1 = Integer.parseInt(ziduan[j + 1].split("__")[1].split("_")[1]);
  1625. if (tr > tr_1 && td.equals(td_1)) { //纵向排序
  1626. temp = ziduan[j];
  1627. ziduan[j] = ziduan[j + 1];
  1628. ziduan[j + 1] = temp;
  1629. }
  1630. }
  1631. }
  1632. String lastStr = dataInfo2.getString(ziduan[0]) + "_^_" + ziduan[0].split("__")[1];
  1633. for (int i = 1; i < ziduan.length; i++) {
  1634. String keyData = dataInfo2.getString(ziduan[i]);
  1635. if (org.apache.commons.lang.StringUtils.isNotEmpty(keyData) && !keyData.equals("")) {
  1636. lastStr += "☆" + dataInfo2.getString(ziduan[i]) + "_^_" + ziduan[i].split("__")[1];
  1637. }
  1638. }
  1639. dataMap2.put(k, lastStr);
  1640. } else {
  1641. String dataVal = dataInfo2.getString(dataMap.get(k).get(0));
  1642. if (org.apache.commons.lang.StringUtils.isNotEmpty(dataVal)) {
  1643. if (dataVal.contains("Ljava")) {
  1644. Object o = dataInfo2.get(dataMap.get(k).get(0));
  1645. dataVal = JSON.toJSONString(o).replace("\"", "");
  1646. }
  1647. dataMap2.put(k, dataVal + "_^_" + dataMap.get(k).get(0).split("__")[1]);
  1648. }
  1649. }
  1650. }
  1651. dataInfo2.put("p_key_id", tableInfo.getPkeyId());
  1652. dataInfo2.put("classify",tableInfo.getClassify());
  1653. dataInfo2.put("contractId",tableInfo.getContractId());
  1654. dataInfo2.put("projectId",tableInfo.getProjectId());
  1655. tableInfo.setDataMap(dataMap2);
  1656. result.add(tableInfo);
  1657. }
  1658. return result;
  1659. }
  1660. return null;
  1661. }
  1662. public static void setFirstData(com.alibaba.fastjson.JSONObject dataInfo2, TableInfo tableInfo) {
  1663. //huangjn 判断是否是首件
  1664. if (dataInfo2.containsKey("isFirst")) {
  1665. tableInfo.setIsFirst(dataInfo2.getString("isFirst"));
  1666. }
  1667. //huangjn 判断是否是首件
  1668. //首件资料绑定的节点
  1669. if (dataInfo2.containsKey("firstNodeId")) {
  1670. tableInfo.setFirstNodeId(dataInfo2.getString("firstNodeId"));
  1671. }
  1672. //首件ID(编辑时有值,新增时为空)
  1673. if (dataInfo2.containsKey("firstId")) {
  1674. tableInfo.setFirstId(dataInfo2.getString("firstId"));
  1675. }
  1676. //源文件
  1677. if (dataInfo2.containsKey("sourceUrl")) {
  1678. tableInfo.setSourceUrl(dataInfo2.getString("sourceUrl"));
  1679. }
  1680. //pdfUrl
  1681. if (dataInfo2.containsKey("pdfUrl")) {
  1682. tableInfo.setPdfUrl(dataInfo2.getString("pdfUrl"));
  1683. }
  1684. //文件名称
  1685. if (dataInfo2.containsKey("firstFileName")) {
  1686. tableInfo.setFirstFileName(dataInfo2.getString("firstFileName"));
  1687. }
  1688. //关联的信息
  1689. if (dataInfo2.containsKey("linkProcessList")) {
  1690. tableInfo.setLinkProcessList(dataInfo2.getJSONArray("linkProcessList"));
  1691. }
  1692. }
  1693. public static void setTheLogData(JSONObject dataInfo2, TableInfo tableInfo) {
  1694. //huangjn 判断是否是日志
  1695. if (dataInfo2.containsKey("isTheLog")) {
  1696. tableInfo.setIsTheLog(dataInfo2.getString("isTheLog"));
  1697. }
  1698. //huangjn 判断是否是日志
  1699. //huangjn 日志ID
  1700. if (dataInfo2.containsKey("theLogId")) {
  1701. tableInfo.setTheLogId(dataInfo2.getString("theLogId"));
  1702. }
  1703. //huangjn 日志ID
  1704. //huangjn 日志勾选的工序
  1705. if (dataInfo2.containsKey("linkTabIds")) {
  1706. tableInfo.setLinkTabIds(dataInfo2.getJSONArray("linkTabIds"));
  1707. }
  1708. //huangjn 日志勾选的工序
  1709. //huangjn 日志所选时间
  1710. if (dataInfo2.containsKey("recordTime")) {
  1711. tableInfo.setRecordTime(dataInfo2.getString("recordTime"));
  1712. }
  1713. //huangjn 日志所选时间
  1714. //huangjn 每份填报数据的id,目前日志专用
  1715. if (dataInfo2.containsKey("id")) {
  1716. tableInfo.setBusinessId(dataInfo2.getString("id"));
  1717. }
  1718. //huangjn 每份填报数据的id,目前日志专用
  1719. }
  1720. }