FormulaUtils.java 84 KB

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