zm
2020-05-18 a18bfacbf56b401f6e0fdae8710fbca4df8cff77
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
package com.changhong.epc.form.service.data.impl;
 
 
import com.changhong.epc.bean.form.*;
import com.changhong.epc.bean.form.budget.addBudget.AddBudget;
import com.changhong.epc.bean.parsing.BillInfo;
import com.changhong.epc.bean.parsing.BillVerify;
import com.changhong.epc.bean.tenant.cost.CostFromMapping;
import com.changhong.epc.bean.tenant.cost.extend.CostTypeExtend;
import com.changhong.epc.bean.tenant.system.SystemConfig;
import com.changhong.epc.bean.tenant.system.SystemForm;
import com.changhong.epc.constter.base.BaseConst;
import com.changhong.epc.constter.base.Context;
import com.changhong.epc.constter.form.budget.BudgetMsg;
import com.changhong.epc.constter.operationLog.OperationLogConst;
import com.changhong.epc.constter.system.SystemClients;
import com.changhong.epc.constter.system.businesscode.BudgetBusinessMeaningCode;
import com.changhong.epc.constter.system.run.EpcRestInterface;
import com.changhong.epc.constter.tenant.TenantUrlConst;
import com.changhong.epc.form.mapper.tenant.FormDataMapper;
import com.changhong.epc.form.mapper.tenant.bill.BillInfoMapper;
import com.changhong.epc.form.service.budget.department.util.AddMoney;
import com.changhong.epc.form.service.budget.department.util.FormCheck;
import com.changhong.epc.form.service.budget.impl.GetConstant;
import com.changhong.epc.form.service.data.FormDataService;
import com.changhong.epc.form.tool.FormNameTool;
import com.changhong.epc.rely.api.epc.admin.InitCompanyApi;
import com.changhong.epc.rely.api.epc.tenant.SystemConfigApi;
import com.codingapi.tx.annotation.TxTransaction;
import com.iemsoft.framework.cloud.core.base.ResMsg;
import com.iemsoft.framework.cloud.core.thread.ThreadData;
import com.iemsoft.framework.cloud.core.tools.JSONTool;
import com.iemsoft.framework.cloud.core.tools.MsgTool;
import com.iemsoft.framework.cloud.core.tools.ObjectUtil;
import com.iemsoft.framework.cloud.core.tools.SpringUtil;
import com.iemsoft.framework.cloud.ribbon.RestInterface;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
 
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
 
 
@Service("formDataService")
@Slf4j
public class FormDataServiceImpl implements BudgetMsg, SystemClients, FormDataService, BudgetBusinessMeaningCode, BaseConst , OperationLogConst {
 
    @Resource
    private FormCheck formCheck;
    @Resource
    private FormDataMapper formDataMapper;
    @Resource
    private InitCompanyApi initCompanyApi;
 
    private static final String groupKey = "groupKey";
 
    //主表单维度
    private static final String ZORE = "0";
 
    //子表单维度
    private static final String ONE = "1";
 
    private static final String SOLIDIFICATION = "solidification";
 
    @Resource
    private BillInfoMapper billMapper;
 
    @Override
    public Integer deleteFormData(FormDataEntity formData) {
//        UserInfo userInfo = new UserInfo();  // 获取 tenantId
        String formName = FormNameTool.getSubFormTableName(formData.getTenantId(), formData.getFormId(), formData.getChildAlias());
        formData.setFormName(formName);
        log.debug("开始执行删除表单数据123>--------------------{}","gqy");
        int i = formDataMapper.deleteFormData(formData);
        if (i > 0) {
            try {
                log.debug("准备记录日志:---------->");
                initCompanyApi.addOperationLog(Objects.toString(formData.getFormId(),""),Objects.toString(formData.getDataIds().get(0),""),OperationLogConst.OPERATION_DELETE,formData.getUserName());
            }catch (Exception e){
                log.error("----------远程调用----------操作日志添加异常:{}",e.getMessage());
            }
        }
        return i;
    }
 
    @Override
    public List<Map<String, Object>> insertFormData(FormDataEntity formData) {
//        UserInfo userInfo = new UserInfo();
        String formName = FormNameTool.getSubFormTableName(formData.getTenantId(), formData.getFormId(), formData.getChildAlias());
        formData.setFormName(formName);
        List<Map<String, Object>> data = formData.getData();
        if (ObjectUtil.notEmpty(data)) {
            for (Map<String, Object> map : data) {
                Map<String, Object> maps = new HashMap<String, Object>();
                maps.put("DELETEFLG", 0);
                maps.put("TENANTID", formData.getTenantId());
                maps.put("CREATEUSER", "");
                maps.put("UPDATEDATETIME", new Date());
                maps.put("CREATEDATETIME", new Date());
                maps.putAll(map);
                formData.setMap(maps);
                Integer i = formDataMapper.insertFormData(formData);
                //----------→添加日志
                if (i > 0) {
                    try {
                        log.debug("准备记录添加日志guo:---------->");
                        initCompanyApi.addOperationLog(Objects.toString(formData.getFormId(),""),Objects.toString(formData.getDataRowNum(),""),OperationLogConst.OPERATION_ADD,formData.getUserName());
                    }catch (Exception e){
                        log.error("----------远程调用----------操作日志添加异常:{}",e.getMessage());
                    }
                }
                //----------→添加日志
                map.put("dataRowNum", formData.getDataRowNum());
            }
        }
        return formData.getData();
    }
 
    @Override
    @Transactional
    @SuppressWarnings("unchecked")
    public Integer updateFormData(FormDataEntity formData) {
//        UserInfo userInfo = new UserInfo();
        String formName = FormNameTool.getSubFormTableName(formData.getTenantId(), formData.getFormId(), formData.getChildAlias());
        formData.setFormName(formName);
        List<Map<String, Object>> data = formData.getData();
        if (ObjectUtil.notEmpty(data)) {
            for (Map<String, Object> map : data) {
                Map<String, Object> maps = new HashMap<String, Object>();
                maps.put("DELETEFLG", 0);
                maps.put("TENANTID", formData.getTenantId());
                maps.put("UPDATEDATETIME", new Date());
                maps.put("CREATEDATETIME", new Date());
                maps.putAll(map);
                formData.setMap(maps);
                formData.setParentDataRowNum((Integer) map.get("PARENTDATAROWNUM"));
                formData.setDataRowNum(formData.getDataRowNum());
                int i = formDataMapper.updateFormData(formData);
                if (i > 0) {
                    try {
                        log.debug("准备记录日志:---------->");
                        initCompanyApi.addOperationLog(Objects.toString(formData.getFormId(),""),Objects.toString(formData.getDataRowNum(),""),OperationLogConst.OPERATION_EDIT,formData.getUserName());
                    }catch (Exception e){
                        log.error("----------远程调用----------操作日志添加异常:{}",e.getMessage());
                    }
                }
                return i;
            }
        }
        return 0;
    }
 
    @Override
    public Map<String, Object> searchFormData(FormDataEntity formData) {
//        if(StringUtils.isBlank(formData.getFormId())){
//            formName = FormNameTool.getFormTableName("001", formData.getChildAlias());
//        }
        String formName = FormNameTool.getSubFormTableName(formData.getTenantId()
                , formData.getFormId(), formData.getChildAlias());
        formData.setFormName(formName);
        // System.err.println(JSONTool.toJson(formName));
        // System.err.println("查询表单数据:"+JSONTool.toJson(formData));
        return formDataMapper.searchFormData(formData);
    }
 
    @Override
    public List<Map<String, Object>> searchFormDataList(FormDataEntity formData) {
        String formName;
        if (formData.getChildAlias() != null)
            formName = FormNameTool.getSubFormTableName(formData.getTenantId(), formData.getFormId(), formData.getChildAlias());
        else
            formName = FormNameTool.getFormTableName(formData.getTenantId(), formData.getFormId());
        formData.setFormName(formName);
        return formDataMapper.searchFormDataList(formData);
    }
 
    @Override
    public Map<String, Object> searchFormInfo1(FormDataEntity formData) {
        // System.out.println("开始查询表单数据");
        String childAlias = formData.getChildAlias();
        String formName;
        List<Map<String, Object>> subData = new ArrayList<Map<String, Object>>();
        if (childAlias != null) {
            formName = FormNameTool.getSubFormTableName(formData.getTenantId(), formData.getFormId(), formData.getChildAlias());
            formData.setFormName(formName);
            subData = formDataMapper.searchFormDataLists(formData);
            if (ObjectUtil.notEmpty(subData)) {
                List<Integer> ids = formDataMapper.searchSubFormIds(formName, formData.getDataRowNum());
                if (ObjectUtil.notEmpty(ids)) {
                    subData.stream()
                            .forEach(sub -> {
                                Integer id = Integer.valueOf(Objects.toString(sub.get("DATAROWNUM"), "0"));
                                int index = Arrays.binarySearch(ids.stream().toArray(Integer[]::new), id);
                                sub.put("index", index);
                            });
                }
            }
        }
 
        formName = FormNameTool.getSubFormTableName(formData.getTenantId(), formData.getFormId());
        formData.setFormName(formName);
        formData.setChildAlias(null);
        Map<String, Object> searchFormData = formDataMapper.searchFormData1(formData);
        if (childAlias != null) {
            searchFormData.put(childAlias, subData);
        }
        return searchFormData;
    }
 
    @Override
    public List<Integer> selectRangeByIds(String formName,
                                          String formDate, String toData, String budType, String currency, String occupy, Integer pageNum, Integer pageSize, String budProject, String budDep) {
        return formDataMapper.selectRangeByIds(formName, formDate, toData, budType, currency, null, occupy, budProject, budDep, pageNum, pageSize);
    }
 
    @Override
    public List<Integer> selectMainIdBySubIds(String formId, String rowId) {
        return formDataMapper.selectMainIdBySubIds(formId, rowId);
    }
 
    @Override
    public List<AddMoney> searchExtendFormData(String formName, String parentDataRowNum, String dataRowNum) {
        return formDataMapper.searchExtendFormData(formName, parentDataRowNum, dataRowNum);
    }
 
    @Override
    public int updateItemBalance(AddMoney add, String formName) {
        return formDataMapper.updateItemBalance(add, formName);
    }
 
    @Override
    public int updaterepayment(String formName, Integer OutstandingAmount, Integer alreadyRepaid,
                               Integer dataRowNum) {
        return formDataMapper.updaterepayment(formName, OutstandingAmount, alreadyRepaid, dataRowNum);
    }
 
    /**
     * 根据groupKey查出对应组
     *
     * @param formId
     */
    private List<SystemConfig> getSysConfigCondition(String formId) {
        return SpringUtil.getBean(SystemConfigApi.class)
                .getSystemConfigs(SystemConfig.of(formId, "1"));
    }
 
 
    @Override
    public String checkBugetData(CheckBuget checkBuget) {
        //表单数据
        BugetData bud = checkBuget.getData();
        String key = null;
        //判断是部门预算还是项目预算
 
        if (GetConstant.getConstant(BUDGET_PROJECT).equals(bud.getBudget_type())) {
            key = BUDGET_PROJECT_CONFIGURATION;
        } else {
            key = BUDGET_CONFIGURATION;
        }
        //查询系统配置
        List<SystemConfig> configData = this.getSysConfigCondition(key);
        if (configData == null) {
            return "true";
        }
        BugetData da = null;
        //重写-----------------------重写-----------------------
 
        //最后匹配数据
        da = this.matchingData(configData, bud);
        // System.out.println("最终数据:"+JSONTool.toJson(da));
        BugetData data = checkBuget.getData();
        if (da == null) {
            return MsgTool.get(BUDGETINFO_DEFICLENCY);
        }
        if (Objects.isNull(data)) {
            return MsgTool.get(BUDGETINFO_NOTFOUND);
        }
        ;
        //主表单名。子表单名
        String formName = FormNameTool.getFormTableName(checkBuget.getTenantID(), checkBuget.getFormID());
        String subFormName = FormNameTool.getSubFormTableName(checkBuget.getTenantID(), checkBuget.getFormID(), BUDGET_SUB_FROM);
 
 
        //取出可用预算单主表datarownum
        List<Integer> selectRangeByIds = formDataMapper.selectRangeById(
                formName,//主表单表单名
                this.isNum(da.getBudgetStartDate()),//预算开始事件
                this.isNum(da.getBudgetEndDate()),//预算结束事件
                this.isNum(da.getBudget_type()),//预算类型
                this.isNum(da.getCurrency()),//币种
                this.isNum(da.getOccupy())
        );
        //
        List<Integer> selectRangeByIdsOnlyOne = formDataMapper.selectRangeByIdOnlyOne(
                formName,//主表单表单名
                subFormName,//子表单表名
                bud.getBudget_subFrom(),//行号
                this.isNum(da.getBudgetStartDate()),//预算开始事件
                this.isNum(da.getBudgetEndDate()),//预算结束事件
                this.isNum(da.getBudget_type()),//预算类型
                this.isNum(da.getCurrency()),//币种
                this.isNum(da.getOccupy())
        );
        //时间没有相同得直接让人return
 
        if (ObjectUtil.empty(selectRangeByIds)) {
            return "true";
        }
        if (this.isNum(checkBuget.getDataRowNum()) != null && selectRangeByIds.size() > 0) {
            int num = selectRangeByIds.indexOf(Integer.parseInt(checkBuget.getDataRowNum()));
            if (num >= 0) {
                selectRangeByIds.remove(num);
            }
        }
        if (selectRangeByIds.size() == 0) {
            return "true";
        }
        List<BugetSubForm> subs = da.getBudget_subFrom();
        String res = null;
        //循环查询子表单
        if (ObjectUtil.notEmpty(subs)) {
            for (BugetSubForm i : subs) {
                res = formDataMapper.selectRangeByNumber(this.isNum(i.getC_Type())
                        , this.isNum(i.getBudget_itemDepartment())
                        , this.isNum(i.getBudget_project())
                        , subFormName, selectRangeByIdsOnlyOne);
                String s = formDataMapper.selectByNumber(formName, res, NUMBER_BUDGET);
                if (res != null) {
                    return MsgTool.get(DEP_RETEPI) + s;
                }
            }
        }
 
//        if( !"".equals(checkBuget.getData().getToWriteBudget())){
//            Integer superDataRowNum = Integer.parseInt(checkBuget.getData().getToWriteBudget());
//            FormDataEntity superFormParam = new FormDataEntity();
//            superFormParam.setDataRowNum(superDataRowNum);
//            superFormParam.setFormId(checkBuget.getFormID());
//            superFormParam.setChildAlias(BUDGET_SUB_FROM);
//            List<Map<String, Object>> superSubFormData = this.searchFormDataList(superFormParam);
//            
//            for(Map<String, Object> ssfd: superSubFormData){
//                for(BugetSubForm busf:checkBuget.getData().getBudget_subFrom()){
//                    if(busf.getDATAROWNUM().equals(ssfd.get("DATAROWNUM").toString())){
//                        if(new BigDecimal(ssfd.get(BUDGET_ITEM_BALANCE).toString())
//                                .subtract(new BigDecimal(busf.getBudget_itemBalance())).compareTo(BigDecimal.ZERO) == -1)
//                        return "上级预算余额不足!";
//                    }
//                }
//            }
//        }
 
//        //检查部门
//        for(BugetSubForm bugetS :data.getBudget_subFrom()){
//            // System.err.println(bugetS.getBudget_itemDepartment());
//            if("".equals(bugetS.getBudget_itemDepartment()) || bugetS.getBudget_itemDepartment() == null){
//                return "当前部门为空";
//            }
////            if(!"".equals(bugetS.getBudget_superDepartement()) && bugetS.getBudget_superDepartement() != null){
////                if(!formCheck.isOrg(bugetS.getBudget_superDepartement(), bugetS.getBudget_itemDepartment()))
////                    return "部门非上下级!";
////            }
//            
//        }
 
        return "true";
    }
 
    /**
     * 查询相同币种的日期是否包含,交叉
     *
     * @return
     */
    private List<Integer> checkDate(String formName, String startDate, String endDate, String currency) {
        return formDataMapper.checkDate(formName, startDate, endDate, currency);
    }
 
    /**
     * 查询上级
     */
    @Override
    public Map<String, Object> selectBudget(String orgs, String budget_itemCostType, String formName) {
        return formDataMapper.selectBudget(orgs, budget_itemCostType, formName);
    }
 
    @Override
    public List<BugetSubForm> searchBudgetSubForm(FormDataEntity formData, HashSet<?> costType) {
        formData.setFormName(FormNameTool.getSubFormTableName(formData.getTenantId()
                , formData.getFormId()
                , formData.getChildAlias()));
        return formDataMapper.searchBudgetSubForm(formData, costType);
    }
 
    @Override
    public int updateExpendFormState(String voucherCode, String formId, int dataRowNum, Integer status, String tenantID) {
        String formName = FormNameTool.getFormTableName(tenantID, formId);
        return formDataMapper.updateExpendFormState(voucherCode, formName, dataRowNum, status);
    }
 
    @Override
    public int updateFormAndBillInfo(BillInfo billInfo) {
        // 临时解决主数据缺失
        billInfo.setVerify(BillVerify.BQS);
        int result = billMapper.updateBill(billInfo);
        if (result == 0) {
            result = billMapper.insert(billInfo);
        }
//        String formName = FormNameTool.getFormTableName(billInfo.getTenantID(), billInfo.getFormId());
        String formName = FormNameTool.getFormTableName(ThreadData.get(TENANT_ID), billInfo.getFormId());
        formDataMapper.updateExpendFormIfHaveOrderCode(formName, billInfo.getFormDataId(), billInfo.getOrderCode());
        return result;
    }
 
    @Override
    public int selectDataRowNum(Map<String, Object> map) {
        return formDataMapper.selectDataRowNum(map.get("formId"), map.get("tenantId"), map.get("orderCode"));
    }
 
    /**
     * 查询表单单条
     *
     * @param formDataEntity
     * @return
     */
    public Map<String, Object> selectFormDataOne(FormDataEntity formDataEntity) {
        formDataEntity.setFormName(FormNameTool.getFormTableName(formDataEntity.getTenantId(), formDataEntity.getFormId()));
        Map<String, Object> formDataInfo = formDataMapper.searchFormData(formDataEntity);
        if (ObjectUtil.empty(formDataEntity.getChildAliaList()))
            return formDataInfo;
        formDataEntity.setParentDataRowNum(formDataEntity.getDataRowNum());
        for (String childAlias : formDataEntity.getChildAliaList()) {
            formDataEntity.setFormName(FormNameTool.getSubFormTableName(formDataEntity.getTenantId(), formDataEntity.getFormId(), childAlias));
            formDataInfo.put(childAlias, formDataMapper.searchSubFormDataList(formDataEntity));
        }
        return formDataInfo;
    }
 
    @Override
    public int updateForm(FormDataEntity formData) {
        String tableName;
        if (ObjectUtil.notEmpty(formData.getChildAlias())) {
            tableName = "formdata_" + formData.getTenantId() + "_" + formData.getFormId() + "_" + formData.getChildAlias();
        } else {
            tableName = "formdata_" + formData.getTenantId() + "_" + formData.getFormId();
        }
        formData.setFormName(tableName);
        int i = formDataMapper.updateFormData(formData);
        if (i > 0) {
            try {
                log.debug("准备记录添加添加添加日志:---------->");
                initCompanyApi.addOperationLog(Objects.toString(formData.getFormId(),""),Objects.toString(formData.getDataRowNum(),""),OperationLogConst.OPERATION_ADD,formData.getUserName());
            }catch (Exception e){
                log.error("----------远程调用----------操作日志添加异常:{}",e.getMessage());
            }
        }
 
 
        return i;
    }
 
    @Override
    @TxTransaction
    @Transactional
    public Integer updateState(ProcessState process) {
        return formDataMapper.updateState(process);
    }
 
    @Override
    public ProcessState selectState(ProcessState process) {
        ProcessState pro = formDataMapper.selectState(process);
        if (ObjectUtil.empty(pro)) {
            return pro;
        }
        String formName = FormNameTool.getFormTableName(process.getTenantId(), process.getFormId());
        try {
            LinkedHashMap<String, Object> map = formDataMapper.selectNumber(formName, Objects.toString(process.getDataRowNum(), "0"));
            pro.setMainInfo(map);
            Set<String> set = map.keySet();
            int count = 0;
            for (String se : set) {
                if (se.indexOf("number_") == 0 && ObjectUtil.notEmpty(map.get(se))) {
                    count += 1;
                    if (!Objects.equals("number_budget", se)) {
                        pro.setNumber(Objects.toString(map.get(se), "-"));
                        return pro;
 
                    }
                }
            }
            //只有一个number_开头说明是预算单-----
            if (count == 1) {
                pro.setNumber(Objects.toString(map.get("number_budget"), "-"));
            }
        } catch (Exception e) {
            pro.setNumber("-");
            // System.err.println(e.getMessage());
        }
 
        return pro;
    }
 
    @Override
    public Object selectCountMoney(FormDataEntity formData) {
        String formName = FormNameTool.getSubFormTableName(formData.getTenantId(), formData.getFormId(), formData.getChildAlias());
 
        formData.setFormName(formName);
        formData.setMap(new ModelMap("stage", ""));
 
        return formDataMapper.searchFormData(formData);
    }
 
    @Override
    public Map<String, Object> searchFormInfo(FormDataEntity formData) {
        String childAlias = formData.getChildAlias();
        String formName;
        List<Map<String, Object>> subData = new ArrayList<Map<String, Object>>();
        if (childAlias != null) {
            formName = FormNameTool.getSubFormTableName(formData.getTenantId(), formData.getFormId(), formData.getChildAlias());
            formData.setFormName(formName);
            subData = formDataMapper.searchFormDataList(formData);
        }
 
        formName = FormNameTool.getSubFormTableName(formData.getTenantId(), formData.getFormId());
        formData.setFormName(formName);
        formData.setChildAlias(null);
        Map<String, Object> searchFormData = formDataMapper.searchFormData1(formData);
        if (childAlias != null) {
            searchFormData.put(childAlias, subData);
        }
        return searchFormData;
    }
 
    @Override
    public int updataFormByCustom(String formName, int dataRowNum, Map<String, Object> fields) {
        return formDataMapper.updataFormByCustom(formName, dataRowNum, fields);
    }
 
    @Override
    public Map<String, Object> searchFormData1(FormDataEntity formData) {
//        if(StringUtils.isBlank(formData.getFormId())){
//            formName = FormNameTool.getFormTableName("001", formData.getChildAlias());
//        }
        String formName = FormNameTool.getSubFormTableName(formData.getTenantId()
                , formData.getFormId(), formData.getChildAlias());
        formData.setFormName(formName);
        // System.err.println(JSONTool.toJson(formName));
        // System.err.println("查询表单数据:"+JSONTool.toJson(formData));
        return formDataMapper.searchFormData1(formData);
    }
 
    public String isNum(String o) {
        return o != null && !"".equals(o) ? o : null;
    }
 
    /**
     * 表单数据于维度匹配
     */
    @SuppressWarnings("unchecked")
    public BugetData matchingData(List<SystemConfig> config, BugetData bd) {
        //接受主表数据
        Map<String, Object> map = new HashMap<>();
        //接受子表单数据
        List<Map> subs = new ArrayList<>();
        //主表数据
        Map<String, String> da = JSONTool.toObj(JSONTool.toJson(bd), Map.class);
        //子表单数据
        List<Map> sub = JSONTool.toList(JSONTool.toJson(bd.getBudget_subFrom()), Map.class);
        // System.out.println("主表数据:"+JSONTool.toJson(da));
        if (ObjectUtil.empty(config)) {
            config = new ArrayList<>();
        }
        for (SystemConfig con : config) {
            // System.out.println("当前配置:"+JSONTool.toJson(con));
            // System.out.println("当前数据:"+da.get(con.getCkey()));
            if (ZORE.equals(con.getFlag())) {
                if (this.isNum(da.get(con.getCkey())) == null) {
                    return null;
                }
                map.put(con.getCkey(), da.get(con.getCkey()));
            }
        }
        if (ObjectUtil.empty(sub)) {
            sub = new ArrayList<>();
        }
        // System.out.println("预算子表单为:"+JSONTool.toJson(sub));
        for (Map m : sub) {
            m.put("C_Type", m.get("C_Type"));
            m.remove("c_Type");
            Map<String, Object> su = new HashMap<>();
            for (SystemConfig con : config) {
                if (ONE.equals(con.getFlag())) {
                    if (this.isNum(Objects.toString(m.get(con.getCkey()))) == null) {
                        return null;
                    }
                    su.put(con.getCkey(), m.get(con.getCkey()));
                }
            }
            subs.add(su);
        }
        map.put(BUDGET_SUB_FROM, subs);
 
 
        return JSONTool.toObj(JSONTool.toJson(map), BugetData.class);
    }
 
 
    @Override
    public Object checkSuperBudgetMoney(AddBudget addBudget) {
        Integer toWriteBudgetId = addBudget.getDataRowNum();
        Map<String, Object> result = new HashMap<String, Object>();//返回值集合
        String fromId = GetConstant.getFormIdGetConstant(YS_FORMID);//预算表id
        String budgetFormId2 = FormNameTool.getFormTableName(addBudget.getTenantId(), fromId);
        String budgetSubFormId = FormNameTool.getSubFormTableName(addBudget.getTenantId(), fromId, BUDGET_SUB_FROM);
 
        Map<String, Object> nowData2 = formDataMapper.searchFormData(new FormDataEntity(budgetFormId2, toWriteBudgetId));
 
 
        Object toW = null;
        if (nowData2 != null) {
            toW = nowData2.get(TO_WRITE_BUDGET);
        }
        if (toW == null) {
            result.put("notF", "T");
        } else {
            result.put("notF", "N");
            FormDataEntity formData = new FormDataEntity();
            formData.setFormName(budgetSubFormId);
            formData.setChildAlias(BUDGET_SUB_FROM);
            formData.setDataRowNum(toWriteBudgetId);
            List<Map<String, Object>> subperData1 = formDataMapper.searchFormDataList(formData);
 
            Integer toWBId = Integer.parseInt(toW.toString());
            FormDataEntity superFormData = new FormDataEntity();
            superFormData.setFormName(budgetSubFormId);
            superFormData.setChildAlias(BUDGET_SUB_FROM);
            superFormData.setDataRowNum(toWBId);
 
 
            List<Map<String, Object>> subperData = formDataMapper.searchFormDataList(superFormData);
            List<Map<String, Object>> listend = new ArrayList<Map<String, Object>>();
 
            for (Map<String, Object> ma : subperData1) {
                for (Map<String, Object> mae : subperData) {
                    if (ma.get("budget_superDepartement") != null && mae.get("budget_itemDepartment") != null && Objects.toString(ma.get("budget_superDepartement")).equals(mae.get("budget_itemDepartment"))) {
                        Map<String, Object> map1 = new HashMap<String, Object>();
                        map1.put("dep", ma.get("budget_itemDepartment"));
                        map1.put("C_Type", mae.get("C_Type"));
                        map1.put("balance", mae.get("budget_itemBalance"));
                        listend.add(map1);
                    }
                }
            }
 
//            subperData.stream().forEach( map ->{
//                Map<String,Object> map1 =new HashMap<String,Object>();
//                map1.put("dep", map.get("budget_itemDepartment"));
//                map1.put("C_Type", map.get("C_Type"));
//                map1.put("balance", map.get("budget_itemBalance"));
//                //if(null != (map.get("budget_itemBalance")) && map.get("budget_itemBalance") != null && ){
//                    //result.add(Double.parseDouble(map.get("budget_itemBalance").toString()));
//                    
//                //}
//                listend.add(map1);
//            });
            result.put("list", listend);
        }
        return result;
    }
 
    @Override
    public Object checkAsserFixedMoney(Map<String, String> map) {
        Map<String, Object> resMap = new HashMap<String, Object>();
        String tenantId = map.get("tenantID");
        String assetId = map.get("assetId");
        String dataRowNum = map.get("dataRowNum");
        String assetFromId = GetConstant.getFormIdGetConstant(SystemForm.ASSET_FORM_ID.name());
        Map<String, String> assetMap = formDataMapper.selectAssetOri(tenantId, assetFromId, assetId);
        String fromId = GetConstant.getFormIdGetConstant(YS_FORMID);
        String budgetSubFormId = FormNameTool.getSubFormTableName(tenantId, fromId, BUDGET_SUB_FROM);
        FormDataEntity superFormData = new FormDataEntity();
        superFormData.setFormName(budgetSubFormId);
        superFormData.setDataRowNum(Integer.parseInt(dataRowNum));
        List<Map<String, Object>> subperData = formDataMapper.searchFormDataList(superFormData);
        resMap.put("originalMoney", Double.parseDouble(Objects.toString(assetMap.get("originalMoney"))));
        for (Map<String, Object> m : subperData) {
            resMap.put("budgetItemBalance", Double.parseDouble(Objects.toString(m.get("budget_itemBalance"))));
        }
        return resMap;
    }
 
    /**
     * 返回每页数据、页数、总条数
     */
    @Override
    public Object selectDatasByUserName(Map<String, String> map) {
        Map<String, Object> endMap = new HashMap<String, Object>();
        List<Map<String, Object>> maps = null;
        int count = 0;
        int countPage = 0;
        String pageNum = map.get("pageNum");//页号
        String pageSize = map.get("pageSize");//页大小
        String costType = map.get("costType");
        //费用类型  前端写死 差旅费
        String formId = Objects.toString(formDataMapper.selectFormIdByCostTypeAndFormType(costType, SQ).get(FORM_ID));
        String bxFormId = Objects.toString(formDataMapper.selectFormIdByCostTypeAndFormType(costType, BX).get(FORM_ID));
        if (!"null".equals(formId) && !"".equals(formId)) {
            String tenantId = Objects.toString(ThreadData.get(TENANT_ID));
            String openId = Objects.toString(ThreadData.get(OPEN_ID));
            count = formDataMapper.selectDataCountByUser(tenantId, formId, openId, costType);
            countPage = count % Integer.parseInt(pageSize) > 0 ? count / Integer.parseInt(pageSize) + 1 : count / Integer.parseInt(pageSize);
            if (countPage > 0) {
                String begin = Objects.toString((Integer.parseInt(pageNum) - 1) * Integer.parseInt(pageSize));
                maps = formDataMapper.selectDataListByUser(tenantId, formId, openId, costType, begin, pageSize);
            }
        }
        endMap.put("list", maps);
        endMap.put("countPage", countPage);
        endMap.put("dataCount", count);
        endMap.put("sqFormId", formId);
        endMap.put("bxFormId", bxFormId);
        return endMap;
    }
 
    @Override
    public Object selectBXByRow(Map<String, String> map) {
        String tenantId = Objects.toString(ThreadData.get(TENANT_ID));
        return formDataMapper.selectDataBybussinessNumber(map.get("formId"), map.get("bussinessNumber"), tenantId);
    }
 
    @Transactional
    @Override
    public Integer updateSubFormDat(Map<String, Object> map) {
        //表单id
        String formId = Objects.toString(map.get("formID"));
        //主表dataRowNum
        Integer dataRowNum = Integer.parseInt(Objects.toString(map.get("dataRowNum")));
        //租户id
        String tenantID = Context.getTenantIdStr();
        //表单数据
        Map<String, Object> data = (Map<String, Object>) map.get("data");
        //用于主表存储
        Map<String, Object> datas = new HashMap<>();
        data.entrySet().stream()
                .forEach(entry -> {
                    if (entry.getValue() instanceof List) {
                        List<Map> list = (List<Map>) entry.getValue();
                        FormDataEntity formData = new FormDataEntity();
                        formData.setFormId(formId);
                        formData.setTenantId(tenantID);
                        for (Map ma : list) {
                            if (ma.get(DATAROWNUMBER) == null || "".equals(ma.get(DATAROWNUMBER))) {
                                continue;
                            }
                            Integer rowNum = Integer.parseInt(Objects.toString(ma.get(DATAROWNUMBER), ""));
                            formData.setDataRowNum(rowNum);
                            ma.remove(DATAROWNUMBER);
                            formData.setMap(ma);
                            formData.setChildAlias(entry.getKey());
                            // 修改子表单
                            this.updateForm(formData);
                        }
                    } else {
                        datas.put(entry.getKey(), entry.getValue());
                    }
                });
        FormDataEntity formData = new FormDataEntity();
        formData.setMap(datas);
        formData.setDataRowNum(dataRowNum);
        formData.setTenantId(tenantID);
        formData.setFormId(formId);
        // 修改主表单
        this.updateForm(formData);
        return 1;
    }
 
    @Override
    public String formSolidiFication(FormSolidiFication fs) {
        String formName = "formdata_" + fs.getTenantId() + "_" + fs.getFormId();
        FormDataEntity fd = new FormDataEntity();
        fd.setDataRowNum(fs.getDataRowNum());
        fd.setFormName(formName);
        //取出主表数据
        Map<String, Object> data = formDataMapper.searchFormData(fd);
        data.remove(SOLIDIFICATION);
        //取出子表数据
        Map<String, Object> subData = new HashMap<>();
        fs.getTableList().stream().forEach(o -> {
            fd.setFormName(o.getTableName());
            fd.setParentDataRowNum(fs.getDataRowNum());
            subData.put(Objects.toString(o.getFormdataNum(), "0"),
                    formDataMapper.searchSubFormDataList(fd));
        });
        Map<String, Object> soData = new ModelMap("main", data)
                .addAttribute("subs", subData);
        //添加固化数据
        return JSONTool.toJson(soData);
 
    }
 
    @Override
    public List<Map<String, Object>> selectApply(ApplyCostForm applyCostForm) {
        List<CostFromMapping> list = getApplyIds();
        List<Map<String, Object>> res = null;
        if (list == null || list.size() == 0) {
            return res;
        }
        list.stream().forEach(o -> o.setFormId(o.getFId()));
 
        Map<String, String> costs = getCostType(list);
        if (ObjectUtil.empty(list)) {
            return new ArrayList<>();
        }
        applyCostForm.setCostformMapping(list);
        res = formDataMapper.selectApply(applyCostForm);
        //人员主数据,转换业务类型
        Map<String, Object> users = getUserMaster();
        // System.out.println("业务类型:"+costs);
        res.stream().forEach(o -> {
            // System.out.println(Objects.toString(o.get(COST_TYPE)));
            // System.out.println(costs.get(Objects.toString(o.get(COST_TYPE))));
            o.put("C_Name", costs.get(Objects.toString(o.get(COST_TYPE))));
            o.put(REIMBURSE_MAN, users.get(Objects.toString(o.get(REIMBURSE_MAN))));
        });
        return res;
    }
 
    /**
     * 查询所有申请单id
     */
    public List<CostFromMapping> getApplyIds() {
        RestInterface restInterface = SpringUtil.getBean(SERVER_TENANT.getBeanName(), RestInterface.class);
        Object data = restInterface.post(TenantUrlConst.REST_TENANT_COST_FORMID, new ModelMap("type", "SQ"), ResMsg.class, EpcRestInterface.getEpcHeads()).getData();
        if (data != null) {
            List<CostFromMapping> list = JSONTool.toList(JSONTool.toJson(data), CostFromMapping.class);
            return list != null && list.size() > 0 ? list : null;
        }
        return null;
    }
 
    /**
     * 取出所有业务类型
     */
    public Map<String, String> getCostType(List<CostFromMapping> lists) {
        Map<Integer, String> formMapping = new HashMap<>();
        Map<String, String> map = new HashMap<>();
        RestInterface restInterface = SpringUtil.getBean(SERVER_TENANT.getBeanName(), RestInterface.class);
        Object data = restInterface.post(TenantUrlConst.REST_TENANT_COSTTYPE_SEACH, new ModelMap("type", "BX"), ResMsg.class, EpcRestInterface.getEpcHeads()).getData();
        List<CostTypeExtend> list = JSONTool.toList(JSONTool.toJson(data), CostTypeExtend.class);
        list.stream().forEach(o -> {
            map.put(Objects.toString(o.getId()), o.getNodeName());
            addExpenseFormId(o.getId(), o.getCostFromMapping(), formMapping);
            if (o.getChildren().size() > 0) {
                o.getChildren().stream().forEach(c -> {
                    map.put(Objects.toString(c.getId()), c.getNodeName());
                    addExpenseFormId(c.getId(), c.getCostFromMapping(), formMapping);
                });
            }
        });
        Iterator<CostFromMapping> iterator = lists.iterator();
        while (iterator.hasNext()) {
            CostFromMapping costFromMapping = iterator.next();
            String fId = formMapping.get(costFromMapping.getCtId());
            if (ObjectUtil.notEmpty(fId)) {
                costFromMapping.setExpenseFormId(fId);
            } else {
                iterator.remove();
            }
        }
 
        return map;
    }
//
//    public static void main(String... args){
//        Map<Integer,String> formMapping = new HashMap<>();
//        FormDataServiceImpl formDataService = new FormDataServiceImpl();
//        Map<String, String> map = new HashMap<>();
//        List<CostFromMapping> lists = JSONTool.toList("[{\"fId\":\"unlhUVmN\",\"ctId\":371,\"fName\":\"差旅申请单\",\"id\":1,\"type\":\"SQ\"},{\"fId\":\"f412933e70714f5297bfee0594b629d6\",\"ctId\":51,\"fName\":\"通用申请单\",\"id\":5,\"type\":\"SQ\"}]", CostFromMapping.class);
//        List<CostTypeExtend> list = JSONTool.toList("[{\"nodeName\":\"费用业务\",\"children\":[{\"nodeName\":\"差旅费\",\"children\":[],\"costFromMapping\":[{\"fId\":\"awvI3wti\",\"fName\":\"差旅报销单SQ\",\"type\":\"BX\"}],\"id\":371,\"type\":\"1\",\"parentId\":17},{\"nodeName\":\"办公费\",\"children\":[],\"costFromMapping\":[{\"fId\":\"LNEC3mFp\",\"fName\":\"报销单通用SQ\",\"type\":\"BX\"}],\"id\":51,\"type\":\"1\",\"parentId\":17}],\"costFromMapping\":[],\"id\":17,\"parentId\":0}]",CostTypeExtend.class);
//        list.stream().forEach(o-> {
//            map.put(Objects.toString(o.getId()),o.getNodeName());
//            formDataService.addExpenseFormId(o.getId(), o.getCostFromMapping(),formMapping);
//            if(o.getChildren().size()>0){
//                o.getChildren().stream().forEach(c->{
//                    map.put(Objects.toString(c.getId()),c.getNodeName());
//                    formDataService.addExpenseFormId(c.getId(), c.getCostFromMapping(),formMapping);
//                });
//            }
//        });
//        Iterator<CostFromMapping> iterator = lists.iterator();
//        while (iterator.hasNext()){
//            CostFromMapping costFromMapping = iterator.next();
//            String fId = formMapping.get(costFromMapping.getCtId());
//            if(ObjectUtil.notEmpty(fId)){
//                costFromMapping.setExpenseFormId(fId);
//            }else{
//                iterator.remove();
//            }
//        }
//
//        System.out.println(map);
//        System.out.println(JSONTool.toJson(lists));
//    }
 
    /**
     * 填充报销单formId,如果没有报销单,删除当前业务类型
     *
     * @return
     */
    public void addExpenseFormId(Integer ctId, List<CostFromMapping> cost, Map<Integer, String> map) {
        cost.stream().forEach(o -> map.put(ctId, o.getFId()));
    }
 
    public Map<String, Object> getUserMaster() {
 
        RestInterface restInterface = SpringUtil.getBean(SERVER_TENANT.getBeanName(), RestInterface.class);
        Object data = restInterface.post(TenantUrlConst.REST_TENANT_MASTERVALUE_SELECTVALUE, new ModelMap("defineCode", GetConstant.getConstant("personnel")), ResMsg.class, EpcRestInterface.getEpcHeads()).getData();
        Map<String, Object> m = new HashMap<>();
        if (data != null) {
            JSONTool.toList(JSONTool.toJson(data), Map.class).stream().forEach(o -> {
                m.put(Objects.toString(o.get("code")), o.get("value"));
            });
        }
        return m;
 
    }
 
 
}