xiejun
2023-10-17 b727fefd8bfb38400aec054df1f45f1174001cb9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
package com.vci.ubcs.code.service.impl;
 
 
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.vci.ubcs.code.mapper.CommonsMapper;
import com.vci.ubcs.starter.web.constant.VciSystemVarConstants;
import com.vci.ubcs.starter.web.toolmodel.DateConverter;
import com.vci.ubcs.starter.web.util.Md5;
import com.vci.ubcs.starter.web.util.VciDateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
 
import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
 
/**
 * 公式处理
 * @author weidy
 * @date 2022-02-11
 *
 */
@Service
public class FormulaServiceImpl {
 
    /**
     * 日志文件
     */
    private Logger logger = LoggerFactory.getLogger(getClass());
    /**
     * 通用查询
     */
    @Resource
    CommonsMapper commonsMapper;
 
//    /**
//     * 业务数据服务
//     */
//    @Autowired
//    private WebBoServiceI boService;
 
    /**
     * 是否运行完成
     */
    private Boolean formulaBlag = true;
    /**
     * 运算符
     */
    public static List<String> lc = new ArrayList<String>();
 
    static {
        lc.add("+");
        lc.add("-");
        lc.add("*");
        lc.add("/");
    }
 
    /**
     * 逻辑运算符
     */
    public static List<String> lj = new ArrayList<String>();
    static {
        lj.add(">");
        lj.add("<");
        lj.add("=");
        lj.add("!");
    }
 
    /**
     * 函数,int数组注释,第一个标识:0自带函数 1自定义函数;第二个标识:参数个数
     */
    public static Map<String, int[]> funMap = new HashMap<String, int[]>();
    // int数组注释,第一个标识:0自带函数 1自定义函数;第二个标识:参数个数
    static {
        // 自带函数,可利用反射机制
        funMap.put("abs", new int[] { 0, 1 });
        funMap.put("acos", new int[] { 0, 1 });
        funMap.put("asin", new int[] { 0, 1 });
        funMap.put("atan", new int[] { 0, 1 });
        funMap.put("cbrt", new int[] { 0, 1 });
        funMap.put("ceil", new int[] { 0, 1 });
        funMap.put("cos", new int[] { 0, 1 });
        funMap.put("cosh", new int[] { 0, 1 });
        funMap.put("exp", new int[] { 0, 1 });
        funMap.put("expm1", new int[] { 0, 1 });
        funMap.put("floor", new int[] { 0, 1 });
        funMap.put("log", new int[] { 0, 1 });
        funMap.put("log10", new int[] { 0, 1 });
        funMap.put("log1p", new int[] { 0, 1 });
        funMap.put("random", new int[] { 0, 0 });
        funMap.put("rint", new int[] { 0, 1 });
        funMap.put("round", new int[] { 0, 1 });
        funMap.put("signum", new int[] { 0, 1 });
        funMap.put("sin", new int[] { 0, 1 });
        funMap.put("sinh", new int[] { 0, 1 });
        funMap.put("sqrt", new int[] { 0, 1 });
        funMap.put("tan", new int[] { 0, 1 });
        funMap.put("tanh", new int[] { 0, 1 });
        funMap.put("max", new int[] { 0, 2 });
        funMap.put("min", new int[] { 0, 2 });
 
        // 自定义函数
        funMap.put("if", new int[] { 1, 3 });
        funMap.put("sum", new int[] { 1, 2 });
        funMap.put("sub", new int[] { 1, 2 });
        funMap.put("mul", new int[] { 1, 2 });
        funMap.put("div", new int[] { 1, 2 });
        funMap.put("mod", new int[] { 1, 2 });
        funMap.put("toInt", new int[] { 1, 1 });
        funMap.put("toDouble", new int[] { 1, 1 });
        funMap.put("doubleRound", new int[] { 1, 2 });
        funMap.put("zeroIfNull", new int[] { 1, 1 });
        funMap.put("endsWith", new int[] { 1, 2 });
        funMap.put("startsWith", new int[] { 1, 2 });
        funMap.put("charAt", new int[] { 1, 2 });
        funMap.put("equalsIgnoreCase", new int[] { 1, 2 });
        funMap.put("indexOf", new int[] { 1, 2 });
        funMap.put("isEmpty", new int[] { 1, 1 });
        funMap.put("lastIndexOf", new int[] { 1, 2 });
        funMap.put("leftStr", new int[] { 1, 2 });
        funMap.put("length", new int[] { 1, 1 });
        funMap.put("mid", new int[] { 1, 3 });
        funMap.put("right", new int[] { 1, 2 });
        funMap.put("rightStr", new int[] { 1, 2 });
        funMap.put("tolowercase", new int[] { 1, 1 });
        funMap.put("touppercase", new int[] { 1, 1 });
        funMap.put("trimzero", new int[] { 1, 1 });
        funMap.put("compareDate", new int[] { 1, 2 });
        funMap.put("nowDate", new int[] { 1, 0 });
        funMap.put("chinaDate", new int[] { 1, 1 });
        funMap.put("dateDdd", new int[] { 1, 2 });
        funMap.put("dateBalanceYear",new int[] {1,3});
        funMap.put("dateBalanceDay",new int[] {1,2});
        funMap.put("dateformat", new int[] { 1, 2 });
        funMap.put("nowDatetime", new int[] { 1, 0 });
        funMap.put("dayOf", new int[] { 1, 1 });
        funMap.put("nowMon", new int[] { 1, 1 });
        funMap.put("monOf", new int[] { 1, 1 });
        funMap.put("nowTime", new int[] { 1, 0 });
        funMap.put("nowYear", new int[] { 1, 0 });
        funMap.put("yearOf", new int[] { 1, 1 });
        funMap.put("getChineseCurrency", new int[] { 1, 1 });
        funMap.put("setThmark", new int[] { 1, 1 });
        funMap.put("toChinese", new int[] { 1, 1 });
        funMap.put("getcolvalue", new int[] { 1, 5 });
        funMap.put("MD5", new int[]{1,1});
        funMap.put("getValueByMethod", new int[]{1,3});
    }
 
    /**
     * 公式初始化转换
     *
     * @param str 公式的内容
     * @return 转换后的内容
     */
    private  String strCast(String str) {
        // str = str.toLowerCase();// 去除空格,变小写
        if (str == null ? true : str.length() == 0) {
            return "0";
        }
        str = str.trim();
        if (!checkFormula(str)) {
            formulaError();
            return str;
        }
        str = str.replaceAll(",", ",");
        str = str.replaceAll("\\+-", "-");
        str = str.replaceAll("-\\+", "-");
        //str = str.replaceAll(" ", "");
        return str;
    }
 
    /**
     * 检查公式中括号出现次数是否正确
     *
     * @param formulaStr 公式的内容
     * @return true 表示校验成功
     */
    private  boolean checkFormula(String formulaStr) {
        formulaBlag = true;
        int count = 0;
        for (int i = 0; i < formulaStr.length(); i++) {
            String s = String.valueOf(formulaStr.charAt(i));
            if ("(".equals(s)) {
                count++;
            } else if (")".equals(s)) {
                count--;
            }
            if (count < 0) {
                formulaBlag = false;
                break;
            }
        }
        formulaBlag = count == 0;
        return formulaBlag;
    }
 
    /**
     * 分割函数
     *
     * @param str 字符串
     * @param bs 分割符
     * @return 转换后的内容
     */
    private  String[] spliteFun(String str, String bs) {
        List<String> list = new ArrayList<String>();
        String bds = "";
        int bracket = 0;
        int len = str.length();
        for (int i = 0; i < len; i++) {
            String s = String.valueOf(str.charAt(i));
            if ("(".equals(s)) {
                bracket++;
            } else if (")".equals(s)) {
                bracket--;
            }
 
            if (bracket == 0 && bs.equals(s)) {
                list.add(bds);
                bds = "";
                continue;
            }
 
            bds += s;
        }
 
        list.add(bds);
 
        String[] ss = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            ss[i] = list.get(i);
        }
 
        return ss;
    }
 
    /**
     * 用户自定义函数
     *
     * @param str 字符串
     * @param funStr 函数的内容
     * @return
     */
    private  String customFun(String str, String funStr) {
        String reval = "false";
        String[] gss = spliteFun(str, ",");
        //每一个参数,我都应该去看看是否还有()。这说明里面是方法
        for (int i = 0; i < gss.length; i++) {
            String record = gss[i];
            if(StringUtils.isNotBlank(record) && record.contains("(") && record.contains(")")){
                gss[i] = calculate(gss[i]);
            }
        }
        if ("if".equals(funStr)) {
            //logger.debug("第一个参数:" + gss[0]);
            if (compare(gss[0])) {
                reval = calculate(gss[1]);
            } else {
                reval = calculate(gss[2]);
            }
        } else if ("sum".equals(funStr)) {
            BigDecimal ln = new BigDecimal(gss[0]);
            BigDecimal rn = new BigDecimal(gss[1]);
            reval = ln.add(rn).doubleValue() + "";
        } else if ("sub".equals(funStr)) {
            BigDecimal ln = new BigDecimal(gss[0]);
            BigDecimal rn = new BigDecimal(gss[1]);
            reval = ln.subtract(rn).doubleValue() + "";
        } else if ("mul".equals(funStr)) {
            BigDecimal ln = new BigDecimal(gss[0]);
            BigDecimal rn = new BigDecimal(gss[1]);
            reval = ln.multiply(rn).doubleValue() + "";
        } else if ("div".equals(funStr)) {
            BigDecimal ln = new BigDecimal(gss[0]);
            BigDecimal rn = new BigDecimal(gss[1]);
            if (rn.doubleValue() == 0) {
                formulaError();
                //reval = "0";
                return reval;
            } else {
                reval = ln.divide(rn, 10, BigDecimal.ROUND_HALF_UP) + "";
            }
 
        } else if ("mod".equals(funStr)) {
            int rn = Integer.parseInt(gss[1]);
            if (rn == 0) {
                formulaError();
 
                return reval;
            }
            int ln = Integer.parseInt(gss[0]);
            reval = (ln % rn) + "";
        } else if ("toInt".equals(funStr)) {
            reval = (int) Math.floor(new Double(calculate(gss[0]))) + "";
        } else if("toDouble".equals(funStr)){
            reval = new Double(calculate(gss[0])) + "";
        }else if("MD5".equals(funStr)){
            reval = Md5.md5(calculate(gss[0]));
        }else if ("doubleRound".equals(funStr)) {
            try {
                BigDecimal b = new BigDecimal(calculate(gss[0]));
                reval = b.setScale(Integer.parseInt(gss[1]),
                    BigDecimal.ROUND_HALF_UP).doubleValue()
                    + "";
            } catch (Exception e) {
                e.printStackTrace();
                formulaError();
            }
 
        } else if ("zeroIfNull".equals(funStr)) {
            logger.debug(gss[0]);
            if ("null".equals(gss[0]) || gss[0].trim().length() == 0) {
                reval = "0";
                return reval;
            }
            reval = gss[0];
        } else if ("endsWith".equals(funStr)) {
            reval = "false";
            if (gss[0].endsWith(gss[1])) {
                reval = "true";
            }
 
        } else if ("startsWith".equals(funStr)) {
            reval = "false";
            if (gss[0].startsWith(gss[1])) {
                reval = "true";
            }
        } else if ("charAt".equals(funStr)) {
            try {
                reval = String.valueOf(gss[0].charAt(Integer.parseInt(gss[1])));
            } catch (Exception e) {
                e.printStackTrace();
                formulaError();
                reval = "";
            }
 
        } else if ("equalsignoreCase".equals(funStr)) {
            if (gss[0].equalsIgnoreCase(gss[1])) {
                reval = "true";
            }
        } else if ("indexOf".equals(funStr)) {
            reval = gss[0].indexOf(gss[1]) + "";
        } else if ("isEmpty".equals(funStr)) {
            if (gss[0].trim().length() == 0 || "".equals(gss[0])
                || "null".equals(gss[0])) {
                reval = "true";
            }
        } else if ("lastIndexOf".equals(funStr)) {
            reval = gss[0].lastIndexOf(gss[1]) + "";
        } else if ("leftStr".equals(funStr)) {
            reval = gss[0].substring(0, Integer.parseInt(gss[1]));
        } else if ("length".equals(funStr)) {
            reval = gss[0].length() + "";
        } else if ("right".equals(funStr)) {
            reval = String.valueOf(gss[0].charAt(gss[0].length()
                - Integer.parseInt(gss[1])));
 
        } else if ("rightStr".equals(funStr)) {
            reval = gss[0]
                .substring(gss[0].length() - Integer.parseInt(gss[1]));
        } else if ("mid".equals(funStr)) {
            try {
                reval = gss[0].substring(Integer.parseInt(gss[1]),
                    Integer.parseInt(gss[2]));
            }catch (Exception e) {
                e.printStackTrace();
                formulaError();
                reval = "";
            }
 
        } else if ("tolowercase".equals(funStr)) {
            reval = gss[0].toLowerCase();
        } else if ("touppercase".equals(funStr)) {
            reval = gss[0].toUpperCase();
        } else if ("trimZero".equals(funStr)) {
            int len = gss[0].length() - 1;
            for (int i = len; i >= 0; i--) {
                if (gss[0].charAt(i) == '0') {
                    gss[0] = gss[0].substring(0, gss[0].length() - 1);
                } else {
                    reval = gss[0];
                    break;
                }
            }
        } else if ("compareDate".equals(funStr)) {
            if (gss[0].indexOf("date") != -1) {
                gss[0] = calculate(gss[0]);
            }
            if (gss[1].indexOf("date") != -1) {
                gss[1] = calculate(gss[1]);
            }
            gss[0] = gss[0].replaceAll("`", "-");
            gss[1] = gss[1].replaceAll("`", "-");
            String result;
            try {
                result = VciDateUtil.compareDate(gss[0], gss[1]);
                if ("=".equals(result)) {
                    reval = "true";
                }
                ;
            } catch (Exception e) {
                e.printStackTrace();
                formulaError();
            }
 
        } else if ("nowDate".equals(funStr)) {
            reval = VciDateUtil.getNowString("yyyy-MM-dd");
        } else if ("chinaDate".equals(funStr)) {
            try {
                if (gss[0].indexOf("date") != -1) {
                    gss[0] = calculate(gss[0]);
                }
                gss[0] = gss[0].replaceAll("`", "-");
                reval = VciDateUtil.getChinaDate(gss[0]);
                return reval;
            } catch (Exception e) {
                e.printStackTrace();
                formulaError();
            }
        } else if ("dateAdd".equals(funStr)) {
            try {
                if (gss[0].indexOf("date") != -1) {
                    gss[0] = calculate(gss[0]);
                }
                gss[0] = gss[0].replaceAll("`", "-");
                DateConverter dateConverter = new DateConverter();
                dateConverter.setAsText(gss[0]);
                Date date = VciDateUtil.getDateAddDay(dateConverter.getValue(),
                    Integer.parseInt(gss[1]));
                reval = VciDateUtil.date2Str(date, VciDateUtil.DateTimeFormat);
                return reval;
            } catch (Exception e) {
                e.printStackTrace();
                formulaError();
            }
        } else if("dateBalanceYear".equals(funStr)) {
            //求时间的差额
            //3个参数,对比的源值,对比的目标值,是否进一
            String sourceDate = gss[0];
            String targetDate = gss[1];
            boolean remainderType = "true".equalsIgnoreCase(gss[2]) ? true : false;
            DateConverter dateConverter = new DateConverter();
            dateConverter.setAsText(sourceDate);
            Date sDate = dateConverter.getValue();
            Date tDate = new Date();
            if (StringUtils.isBlank(targetDate)) {
                dateConverter.setAsText(targetDate);
                tDate = dateConverter.getValue();
            }
 
            Period p = Period.between(LocalDate.parse(VciDateUtil.date2Str(sDate, VciDateUtil.DateTimeMillFormat), DateTimeFormatter.ofPattern(VciDateUtil.DateTimeMillFormat)),
                LocalDate.parse(VciDateUtil.date2Str(tDate, VciDateUtil.DateTimeMillFormat), DateTimeFormatter.ofPattern(VciDateUtil.DateTimeMillFormat)));
            reval = String.valueOf((remainderType && (p.getMonths() > 0 || p.getDays() > 0)) ? (p.getYears() + 1) : p.getYears());
            //月份相差是没办法计算
        }else if("dateBalanceDay".equals(funStr)){
            String sourceDate = gss[0];
            String targetDate = gss[1];
            DateConverter dateConverter = new DateConverter();
            dateConverter.setAsText(sourceDate);
            Date sDate = dateConverter.getValue();
            Date tDate = new Date();
            if (StringUtils.isNotBlank(targetDate)) {
                dateConverter.setAsText(targetDate);
                tDate = dateConverter.getValue();
            }
            reval = String.valueOf(TimeUnit.DAYS.convert(Math.abs(sDate.getTime()-tDate.getTime()),TimeUnit.MILLISECONDS));
        }else if ("dateformat".equals(funStr)) {
            if (gss[0].indexOf("date") != -1) {
                gss[0] = calculate(gss[0]);
            }
            gss[0] = gss[0].replaceAll("`", "-");
            gss[1] = gss[1].replaceAll("`", "-");
            Date date;
            try {
                if("''".equalsIgnoreCase(gss[0])) {
                    gss[0] = VciDateUtil.getNowString();
                }
                DateConverter dateConverter =new DateConverter();
                dateConverter.setAsText(gss[0]);
                date = dateConverter.getValue();
                reval = VciDateUtil.date2Str(date, gss[1].replace("&"," "));
                return reval;
            } catch (Exception e) {
                e.printStackTrace();
                formulaError();
            }
 
        } else if ("nowDatetime".equals(funStr)) {
            reval = VciDateUtil.getNowString();
        } else if ("dayOf".equals(funStr)) {
            if (gss[0].indexOf("date") != -1) {
                gss[0] = calculate(gss[0]);
            }
            gss[0] = gss[0].replaceAll("`", "-");
            try {
                Date date = VciDateUtil.str2Date(gss[0], "yyyy-MM-dd");
                reval = date.getDate() + "";
                return reval;
            } catch (Exception e) {
                e.printStackTrace();
                formulaError();
            }
        } else if ("nowNon".equals(funStr)) {
            try {
                reval = VciDateUtil.getNowString("MM");
                return reval;
            } catch (Exception e) {
                e.printStackTrace();
                formulaError();
            }
        } else if ("monOf".equals(funStr)) {
            if (gss[0].indexOf("date") != -1) {
                gss[0] = calculate(gss[0]);
            }
            gss[0] = gss[0].replaceAll("`", "-");
            try {
                Date date = VciDateUtil.str2Date(gss[0], "yyyy-MM-dd");
                reval = date.getMonth() + "";
                return reval;
            } catch (Exception e) {
                e.printStackTrace();
                formulaError();
            }
        } else if ("nowTime".equals(funStr)) {
            reval = VciDateUtil.getNowString("HH:mm:ss");
            return reval;
        } else if ("nowYear".equals(funStr)) {
            reval = VciDateUtil.getNowString("yyyy");
            return reval;
        } else if ("yearOf".equals(funStr)) {
            if (gss[0].indexOf("date") != -1) {
                gss[0] = calculate(gss[0]);
            }
            gss[0] = gss[0].replaceAll("`", "-");
            try {
                Date date = VciDateUtil.str2Date(gss[0], "yyyy-MM-dd");
                reval = date.getYear() + 1900 + "";
                return reval;
            } catch (Exception e) {
                e.printStackTrace();
                formulaError();
            }
        } else if ("getChineseCurrency".equals(funStr)) {
            gss[0] = calculate(gss[0]);
            reval = toChineseCurrency(gss[0]);
        } else if ("setThmark".equals(funStr)) {
            String numstr = "";
 
            String[] number = gss[0].split("\\.");
            //logger.debug(number[0]);
            for (int i = number[0].length() - 1; i >= 0; i--) {
                if (i % 3 == 2 && i < number[0].length() - 1) {
                    numstr += ",";
                }
                numstr += number[0].charAt(i);
            }
            reval = "";
            for (int i = numstr.toCharArray().length - 1; i >= 0; i--) {
                reval += numstr.toCharArray()[i];
            }
            if (gss[0].indexOf(".") != -1) {
                reval += "." + number[1];
            }
 
        } else if ("toChinese".equals(funStr)) {
            gss[0] = calculate(gss[0]);
            //logger.debug(gss[0]);
            reval = toChinese(gss[0]);
        } else if ("getcolvalue".equals(funStr)) {
            if (gss[0].trim().length() == 0 || gss[1].trim().length() == 0
                || gss[2].trim().length() == 0
                || gss[3].trim().length() == 0
                || gss[4].trim().length() == 0) {
                formulaError();
                return reval;
            }
            reval = getColValue(gss[0], gss[1], gss[2], gss[3], gss[4]);
        }else if("getValueByMethod".equalsIgnoreCase(funStr)){
            if (gss[0].trim().length() == 0 || gss[1].trim().length() == 0
                || gss[2].trim().length() == 0) {
                formulaError();
                return reval;
            }
            reval = getValueByMethod(gss[0], gss[1], gss[2]);
        }
 
        return reval;
    }
 
    // 逻辑表达式判断
    private  boolean compare(String str) {
        if ("true".equals(calculate(str))) {
            return true;
        } else if ("false".equals(calculate(str))) {
            return false;
        }
        boolean flag = false;
        boolean bs = false;
        int len = str.length();
        int bracket = 0;
        String ljbds = "";
        double d_left = 0;
        double d_right = 0;
        for (int i = 0; i < len; i++) {
            String s = String.valueOf(str.charAt(i));
            if ("(".equals(s)) {
                bracket++;
            } else if (")".equals(s)) {
                bracket--;
            }
 
            if (bracket == 0 && lj.contains(s)) {
                for (int j = i; j < len; j++) {
                    String ts = String.valueOf(str.charAt(j));
                    if (lj.contains(ts)) {
                        ljbds += ts;
                    } else {
                        bs = true;
                        break;
                    }
                }
            }
            if (bs) {
                break;
            }
        }
        //logger.debug("逻辑表达式:" + ljbds);
        String[] s = str.split(ljbds);
        //logger.debug("左边:" + (s[0]));
        //logger.debug("右边:" + (s[1]));
        if (isNumber(calculate(s[0])) && isNumber(calculate(s[1]))) {
            d_left = new Double(calculate(s[0]));
            d_right = new Double(calculate(s[1]));
        } else {
            formulaError();
            return false;
        }
 
        if ("<".equals(ljbds)) {
            if (d_left < d_right) {
                return true;
            }
        } else if (">".equals(ljbds)) {
            if (d_left > d_right) {
                return true;
            }
        } else if ("=".equals(ljbds)) {
            if (d_left == d_right) {
                return true;
            }
        } else if (">=".equals(ljbds)) {
            if (d_left >= d_right) {
                return true;
            }
        } else if ("<=".equals(ljbds)) {
            if (d_left <= d_right) {
                return true;
            }
        } else if ("<>".equals(ljbds) || "!=".equals(ljbds)) {
            if (d_left != d_right) {
                return true;
            }
        } else {
            formulaError();
        }
        return flag;
    }
 
    /**
     * 使用公式计算结果
     * @param dataMap 本场景变量的值
     * @param calculateString 公式的内容
     * @return 执行后的值
     */
    public String getValueByFormula(Map<String,String> dataMap,String calculateString){
        final String[] finalRule = new String[]{calculateString};
        if(!CollectionUtils.isEmpty(dataMap)){
            dataMap.forEach((key,value)->{
                if(value == null){
                    value = "";
                }
                finalRule[0] = finalRule[0].replace("${" + key + "}",value);
            });
        }
        return calculate(finalRule[0]);
    }
 
    /**
     * 递归调用运算,注意变量需要自行替换
     *
     * @param str
     * @return
     */
    public  String calculate(String str) {
        str = this.strCast(str);
        if (!formulaBlag) {
            //logger.debug("公式不正确");
            return str;
        }
        boolean onlyFunction = str.length()>2 && str.startsWith("->");
        if(onlyFunction){
            str = str.substring(2);
        }
        //需要替换系统变量
        Map<String, String> systemVarValueMap = new HashMap<>();//VciSystemVarConstants.getSystemVarValueMap();
        if(!CollectionUtils.isEmpty(systemVarValueMap)){
            final String[] finalStr = new String[]{str};
            systemVarValueMap.forEach((key,value)->{
                if(value == null){
                    value = "";
                }
                finalStr[0] = finalStr[0].replace( key,value);
            });
            str = finalStr[0];
        }
        String reval = "";
        String bds = "";
        int bracket = 0;// 对应括号个数
        int pos = 0;
        boolean title = false;
        // 如果以负数开头,先去掉负号
        if (str.substring(0, 1).equals("-")) {
            str = str.substring(1);
            title = true;
        }
 
        int len = str.length();
        for (int i = 0; i < len; i++) {
            String s = String.valueOf(str.charAt(i));
            pos = i;
            bracket = 0;
            if (!lc.contains(s)) {// 如果没遇到运算符
                if ("(".equals(s)) {// 如果遇到左括号
                    if (funMap.containsKey(bds)) {// 如果左括号前是函数
                        for (int j = i + 1; j < len; j++) {// 从左括号后开始循环
                            pos++;// 累计移动字符位数
                            String ts = String.valueOf(str.charAt(j));// 单个字符
                            // reval+=ts;
                            if ("(".equals(ts))// 如果是左括号累计
                            {
                                bracket++;
                            } else if (")".equals(ts)) {// 如果是右括号进行减少
                                bracket--;
                                if (bracket == -1) {// 如果是-1,标识括号结束
                                    reval = reval.substring(0, reval.length()
                                        - bds.length());// 重新获得去掉函数头的表达式
                                    reval += this.funCalculate(
                                        str.substring(i + 1, j), bds);// 表达式加上函数结果,形成新表达式
                                    i = pos;// 计数器增加
                                    bds = "";// 函数头清空
                                    break;// 退出本次循环
                                }
                            }
                        }
                    } else if ("".equals(bds) || lc.contains(bds)) {// 如果是普通运算
                        //logger.debug("普通运算");
                        for (int j = i + 1; j < len; j++) {
                            pos++;
                            String ts = String.valueOf(str.charAt(j));
                            if ("(".equals(ts)) {
                                bracket++;
                            } else if (")".equals(ts)) {
                                bracket--;
                                if (bracket == -1) {
                                    logger.debug("当前计算的字符串为:"
                                        + str.substring(i + 1, pos));
                                    reval += calculate(str
                                        .substring(i + 1, pos));
                                    i = pos;
                                    bds = "";
                                    break;
                                }
                            }
                        }
                    } else {
                        logger.debug("没有此函数");
                        formulaError();
                    }
                } else {// 累加总表达式和最后一个运算数(或函数)
                    bds += s;
                    reval += s;
                }
            } else {// 遇到运算符最后一个运算数(或函数)清空
                bds = "";
                reval += s;
            }
        }
        // 如果为负数 在前面加负号
        if (title) {
            reval = "0-" + reval;
        }
        if(onlyFunction){
 
            return reval;
        }
        String result =  basicOperation(reval);
        logger.debug("计算结果" + result);
        return result;
    }
 
    /**
     * 函数运算
     *
     * @param gs
     * @param funStr
     * @return
     */
    private  String funCalculate(String gs, String funStr) {
        String rval = "0";
        logger.debug("函数名:" + funStr);
        if (funMap.containsKey(funStr)) {
            int[] csi = funMap.get(funStr);
            try {
                if (csi[0] == 0) {// java内部函数,通过反射调用
                    Class[] cs = new Class[csi[1]];
                    Object[] objs = new Object[csi[1]];
                    String[] gss = splitParameter(gs);
                    for (int i = 0; i < csi[1]; i++) {
                        cs[i] = double.class;
                        objs[i] = new Double(calculate(gss[i]));
                    }
                    Class cls = Class.forName("java.lang.Math");
                    Method m = cls.getMethod(funStr, cs);
                    logger.debug("方法名:" + m);
                    rval = String.valueOf(m.invoke(cls, objs));
                } else if (csi[0] == 1) {// 自定义函数
                    rval = customFun(gs, funStr);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
 
        return rval;
    }
 
    // 公式里的参数分割
    public static String[] splitParameter(String str) {
        int len = str.length();
        boolean flag = true;
        String tstr = "";
 
        for (int i = 0; i < len; i++) {
            String s = String.valueOf(str.charAt(i));
            if ("(".equals(s)) {
                flag = false;
            } else if (")".equals(s)) {
                flag = true;
            }
            if (flag && ",".equals(s)) {
                tstr += "@";
            } else {
                tstr += s;
            }
        }
        return tstr.split("@");
 
    }
 
    /**
     * 四则运算表达式处理
     *
     * @param gs
     * @return
     */
    private  String basicOperation(String gs) {
        gs = gs + "+0"; // 因为下面的计算是遇到符号才进行,所以多加入一个计算符号,不影响值.
        if(gs.indexOf("-")>-1){//包含有-号或者是负数
            if(gs.startsWith("-")) {
                gs = "0" + gs;
            }
//            if(gs.indexOf("-")>0&&lc.contains(gs.substring(gs.indexOf("-")-1,gs.indexOf("-")))){//紧挨着旁边就是运算符,怎么办啊
//                //gs = gs.substring(0,gs.indexOf("-")-1) + "(0" + gs.substring(gs.indexOf("-"))
//            }
        }
        String c1 = "";// 第一个运算符号
        String c2 = "";// 第二个运算符号
        String s1 = "";// 第一个运算数
        String s2 = "";// 第二个运算数
        String s3 = "";// 第三个运算数
 
        int len = gs.length();
        for (int i = 0; i < len; i++) {
            String s = String.valueOf(gs.charAt(i));// 获得该位置字符并转换成字符串做比较
            if (lc.contains(s)) { // 如果是运算符号
                if (c1.length() == 0)// 如果第一个运算符号为空,加入
                {
                    c1 = s;
                } else if (c2.length() == 0) {// 否则,如果第二个运算符号为空,加入
                    c2 = s;// 第二个运算符号
                    if ("+".equals(c2) || "-".equals(c2)) {// 如果第二个运算符号级别低,那么进行计算
                        if(s2.trim().length()>0){
                            s1 = this.operation(s1, c1, s2);// 第一个和第二个数计算
                            c1 = c2;// 保存第二个运算符,其他为空
                            c2 = "";
                            s2 = "";
                        }else{//s2还没出现
                            s2=this.calculate(gs.substring(i));
                            s1 = this.operation(s1, c1, s2);
                            break;
                        }
                    }
                } else {// 上述都保存过
                    if ("+".equals(s) || "-".equals(s)) {// 如果第三个运算符级别低,进行运算
                        s2 = this.operation(s2, c2, s3);// 先算第二三个数,保存至第二个
                        s1 = this.operation(s1, c1, s2);// 再算第一二个,保存至第一个
                        c1 = s;// 保存当前运算符,其他为空
                        s2 = "";
                        c2 = "";
                        s3 = "";
                    } else {// 如果第三个运算符级别高
                        s2 = this.operation(s2, c2, s3);// 先算第二三个数,保存至第二个
                        c2 = s;// 前面不动,保存运算符
                        s3 = "";
                    }
                }
            } else if (s1.length() > 0 && c1.length() > 0 && c2.length() == 0) {// 如果第一个数,第一个运算符已保存,第二个运算符未保存,保存第二哥数
                s2 += s;
            } else if (c1.length() == 0) {// 如果没有运算符,保存第一个数
                s1 += s;
            } else if (s1.length() > 0 && s2.length() > 0 && c1.length() > 0
                && c2.length() > 0) {// 如果第一二个数和运算符都有,保存第三个数
                s3 += s;
            }
        }
        return s1;
    }
 
    /**
     * 基本四则运算
     *
     * @param c1
     *            运算数1
     * @param s1
     *            运算符(加减乘除)
     * @param c2
     *            运算数2
     * @return
     */
    private  String operation(String c1, String s1, String c2) {
        String reval = "0";
        String c22 = "";
        try {
            for (int i = 0; i < c2.length(); i++) {
                String s = String.valueOf(c2.charAt(i));
                if (lj.contains(s)) {
                    break;
                }
                c22 += s;
            }
            if (isNumber(c1) && isNumber(c22)) {
                BigDecimal ln = new BigDecimal(c1.trim());
                BigDecimal rn = new BigDecimal(c2.trim());
                if ("+".equals(s1)) {
                    return ln.add(rn).doubleValue() + "";
                } else if ("-".equals(s1)) {
                    return ln.subtract(rn).doubleValue() + "";
                } else if ("*".equals(s1)) {
                    return ln.multiply(rn).doubleValue() + "";
                } else if ("/".equals(s1)) {
                    if (rn.doubleValue() == 0) {
                        return reval;
                    }
                    else {
                        return ln.divide(rn, 10, BigDecimal.ROUND_HALF_UP) + "";
                    }
                }
            } else {
                this.formulaError();
                return c1+s1+c2;
            }
 
        } catch (Exception e) {
            this.formulaError();
            e.printStackTrace();
        } finally {
        }
 
        return reval;
    }
 
    private  Boolean isNumber(String str) {
        return StringUtils.isNotBlank(str) && str.matches("(-)?([1-9]+[0-9]*|0)(\\.[\\d]+)?");
    }
 
    private  String formulaError() {
        formulaBlag = false;
        //logger.debug("公式验证失败,请重新输入");
        return "fail";
    }
 
    public  String toChineseCurrency(String value) {
        String doubleValue = this.calculate("doubleround(" + value + ",2)");
        String fushu = "";
        if (doubleValue.indexOf("-") == 0) {
            fushu = "负";
            doubleValue = doubleValue.substring(1);
//            formulaError();
//            return "";
        }
        char[] hunit = { '拾', '佰', '仟' }; // 段内位置表示
        char[] vunit = { '万', '亿' }; // 段名表示
        char[] digit = { '零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖' }; // 数字表示
        //double midVal =  (Double.parseDouble(doubleValue) * 100); // 转化成整形
        //String valStr = String.valueOf(midVal); // 转化成字符串
        //String head = valStr.substring(0, valStr.length() - 2); // 取整数部分
        //String rail = valStr.substring(valStr.length() - 2); // 取小数部分
        String head = "";
        String rail = "00";
        if(doubleValue.indexOf(".")>-1){
            head = doubleValue.substring(0,doubleValue.indexOf("."));
            rail = doubleValue.substring(doubleValue.indexOf(".")+1);
            if(rail.trim().length() == 1) {
                rail += "0";//必须要保证有分
            }
        }
        else {
            head = doubleValue;
        }
        String prefix = ""; // 整数部分转化的结果
        String suffix = ""; // 小数部分转化的结果
        // 处理小数点后面的数
        if (rail.equals("00")) { // 如果小数部分为0
            suffix = "整";
        } else {
            suffix = digit[rail.charAt(0) - '0'] + "角"
                + digit[rail.charAt(1) - '0'] + "分"; // 否则把角分转化出来
        }
        // 处理小数点前面的数
        char[] chDig = head.toCharArray(); // 把整数部分转化成字符数组
        char zero = '0'; // 标志'0'表示出现过0
        byte zeroSerNum = 0; // 连续出现0的次数
        for (int i = 0; i < chDig.length; i++) { // 循环处理每个数字
            int idx = (chDig.length - i - 1) % 4; // 取段内位置
            int vidx = (chDig.length - i - 1) / 4; // 取段位置
            if (chDig[i] == '0') { // 如果当前字符是0
                zeroSerNum++; // 连续0次数递增
                if (zero == '0') { // 标志
                    zero = digit[0];
                } else if (idx == 0 && vidx > 0 && zeroSerNum < 4) {
                    prefix += vunit[vidx - 1];
                    zero = '0';
                }
                continue;
            }
            zeroSerNum = 0; // 连续0次数清零
            if (zero != '0') { // 如果标志不为0,则加上,例如万,亿什么的
                prefix += zero;
                zero = '0';
            }
            prefix += digit[chDig[i] - '0']; // 转化该数字表示
            if (idx > 0) {
                prefix += hunit[idx - 1];
            }
            if (idx == 0 && vidx > 0) {
                prefix += vunit[vidx - 1]; // 段结束位置应该加上段名如万,亿
            }
        }
 
        if (prefix.length() > 0) {
            prefix += '圆'; // 如果整数部分存在,则有圆的字样
        }
        return fushu + prefix + suffix; // 返回正确表示
    }
 
    private String toChinese(String value) {
        if (!isNumber(value)) {
            this.formulaError();
            return "";
        }
        String fu = "";
        // 如果是负数前面加负
        if (value.indexOf("-") == 0) {
            value = value.substring(1);
            fu += "负";
        }
        char[] hunit = { '拾', '佰', '仟' }; // 段内位置表示
        char[] vunit = { '万', '亿' }; // 段名表示
        char[] digit = { '零', '一', '二', '三', '四', '五', '六', '七', '八', '九' }; // 数字表示
        String head = "";
        String rail = "";
        String prefix = ""; // 整数部分转化的结果
        String suffix = ""; // 小数部分转化的结果
        if (value.indexOf(".") != -1 && value.indexOf(".") < value.length() - 1) {
            String[] number = value.split("\\.");
            head = number[0]; // 取整数部分
            rail = number[1];
            suffix += "点";
        } else {
            head = value;
        }
        // 处理小数点后面的数
        for (int i = 0; i < rail.length(); i++) {
            suffix += digit[rail.charAt(i) - '0'];
        }
 
        // 处理小数点前面的数
        char[] chDig = head.toCharArray(); // 把整数部分转化成字符数组
        char zero = '0'; // 标志'0'表示出现过0
        byte zeroSerNum = 0; // 连续出现0的次数
        for (int i = 0; i < chDig.length; i++) { // 循环处理每个数字
            int idx = (chDig.length - i - 1) % 4; // 取段内位置
            int vidx = (chDig.length - i - 1) / 4; // 取段位置
            if (chDig[i] == '0') { // 如果当前字符是0
                zeroSerNum++; // 连续0次数递增
                if (zero == '0') { // 标志
                    zero = digit[0];
                } else if (idx == 0 && vidx > 0 && zeroSerNum < 4) {
                    prefix += vunit[vidx - 1];
                    zero = '0';
                }
                continue;
            }
            zeroSerNum = 0; // 连续0次数清零
            if (zero != '0') { // 如果标志不为0,则加上,例如万,亿什么的
                prefix += zero;
                zero = '0';
            }
            prefix += digit[chDig[i] - '0']; // 转化该数字表示
            if (idx > 0) {
                prefix += hunit[idx - 1];
            }
            if (idx == 0 && vidx > 0) {
                prefix += vunit[vidx - 1]; // 段结束位置应该加上段名如万,亿
            }
        }
        return fu + prefix + suffix; // 返回正确表示
    }
 
    private  String getColValue(String servername, String tableName,
                                String fieldname, String pkfield, String pkvalue) {
        //暂时不支持server的方式
        String sql = "select " + fieldname.trim() + " from " +  tableName.trim() + " where " + pkfield + " = '" + pkvalue+"'";
//        Map<String,String> param = new HashMap<String, String>();
//        param.put(pkfield, pkvalue);
        String str = "";
        try{
            List data = commonsMapper.selectById(sql);
            if(data != null || data.size() > 0) {
                str = (String) ((HashMap) data.get(0)).get(fieldname.trim());
            }
        }catch(Exception e){
 
        }
        return str;
 
    }
 
    private String getValueByMethod(String serviceName,String methods,String paramsString){
        //暂时不支持通过方法来获取值
        return paramsString;
    }
 
//    public static void main(String[] args) {
//
//    }
 
}