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
package com.vci.web.service.impl;
 
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ZipUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.vci.constant.FrameWorkLangCodeConstant;
import com.vci.corba.common.PLException;
import com.vci.corba.omd.atm.AttributeDef;
import com.vci.corba.omd.btm.BizType;
import com.vci.corba.omd.data.BusinessObject;
import com.vci.corba.omd.ltm.LinkType;
import com.vci.corba.omd.ltm.LinkTypeServicePrx;
import com.vci.dto.OsAttributeDTO;
import com.vci.omd.constants.AttributeConstants;
import com.vci.omd.constants.LinkTypeConstants;
import com.vci.omd.utils.ObjectTool;
import com.vci.pagemodel.*;
import com.vci.po.OsAttributePO;
import com.vci.po.OsLinkTypePO;
import com.vci.starter.poi.bo.ReadExcelOption;
import com.vci.starter.poi.bo.WriteExcelData;
import com.vci.starter.poi.bo.WriteExcelOption;
import com.vci.starter.poi.constant.ExcelLangCodeConstant;
import com.vci.starter.poi.util.ExcelUtil;
import com.vci.starter.web.annotation.log.VciUnLog;
import com.vci.starter.web.enumpck.ResultCodeEnum;
import com.vci.starter.web.enumpck.VciFieldTypeEnum;
import com.vci.starter.web.exception.VciBaseException;
import com.vci.starter.web.pagemodel.BaseQueryObject;
import com.vci.starter.web.pagemodel.BaseResult;
import com.vci.starter.web.pagemodel.DataGrid;
import com.vci.starter.web.util.*;
import com.vci.model.OsLinkTypeDO;
import com.vci.web.service.*;
import com.vci.web.util.Func;
import com.vci.web.util.PlatformClientUtil;
import com.vci.web.util.WebUtil;
import javafx.scene.shape.HLineTo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * 链接类型服务
 * @author weidy
 * @date 2021-2-15
 */
@Service
public class OsLinkTypeServiceImpl implements OsLinkTypeServiceI {
 
    private static final String OID = "oid";
    private static final String NAME = "name";
    private static final String LABEL = "label";
    private static final String DESCRIPTION = "description";
    private static final String TS = "ts";
    private static final String CREATOR = "creator";
    private static final String CREATETIME = "createTime";
    private static final String MODIFIER = "modifier";
    private static final String MODIFYTIME = "modifyTime";
 
    /**
     * 日志
     */
    private Logger logger = LoggerFactory.getLogger(getClass());
 
 
    /**
     * 平台的调用工具类
     */
    @Autowired
    private PlatformClientUtil platformClientUtil;
 
    /**
     * 属性的服务
     */
    @Autowired
    private OsAttributeServiceI attributeService;
 
    /**
     * 枚举的服务
     */
    @Autowired
    private OsEnumServiceI enumService;
 
    /**
     * 业务类型服务
     */
    @Autowired
    private OsBtmServiceI btmService;
 
    /**
     * 业务数据查询服务
     */
    @Autowired
    private WebBoServiceI boService;
 
    /**
     * 加载自身
     */
    @Autowired(required = false)
    @Lazy
    private OsLinkTypeServiceI self;
 
    /**
     * 查询所有的链接类型
     *
     * @return 链接类型对象
     */
    @Override
    @VciUnLog
    public List<OsLinkTypeVO> selectAllLink() {
        try {
            return linkTypeDO2VOs(Arrays.stream(platformClientUtil.getLinkTypeService().getLinkTypes()).collect(Collectors.toList()));
        } catch (PLException vciError) {
           throw WebUtil.getVciBaseException(vciError);
        }
    }
 
    /**
     * 查询所有的业务类型映射
     *
     * @return key 是业务的英文名称的小写
     */
    @Override
    @VciUnLog
    public Map<String, OsLinkTypeVO> selectAllLinkMap() {
        return Optional.ofNullable(self.selectAllLink()).orElseGet(()->new ArrayList<>()).stream().collect(Collectors.toMap(s->s.getId().toLowerCase(),t->t,(o1,o2)->o1));
    }
 
    /**
     * 数据对象转换为显示对象
     *
     * @param linkTypes 数据对象
     * @return 显示对象
     */
    @Override
    public List<OsLinkTypeVO> linkTypeDO2VOs(Collection<LinkType> linkTypes) {
        List<OsLinkTypeVO> VOS = new ArrayList<>();
        Optional.ofNullable(linkTypes).orElseGet(()->new ArrayList<>()).stream().forEach(linkType -> {
            OsLinkTypeVO vo = linkTypeDO2VO(linkType);
            VOS.add(vo);
        });
        return VOS;
    }
 
    /**
     * 数据对象转换为显示对象
     *
     * @param linkType 数据对象
     * @return 显示对象
     */
    @Override
    public OsLinkTypeVO linkTypeDO2VO(LinkType linkType) {
        OsLinkTypeVO vo = new OsLinkTypeVO();
        if(linkType !=null){
            vo.setOid(linkType.oid);
            vo.setCreator(linkType.creator);
            vo.setLastModifier(linkType.modifier);
            try {
                vo.setCreateTime(VciDateUtil.long2Date(linkType.createTime));
                vo.setLastModifyTime(VciDateUtil.long2Date(linkType.modifyTime));
                vo.setTs(VciDateUtil.long2Date(linkType.ts));
            } catch (Exception e) {
                e.printStackTrace();
            }
            vo.setDescription(linkType.description);
            vo.setId(linkType.name);
            vo.setName(linkType.tag);
            vo.setFromBtmTypeVOS(btmService.listBtmByIds(Arrays.stream(linkType.btmItemsFrom).collect(Collectors.toSet())));
            if(!CollectionUtils.isEmpty(vo.getFromBtmTypeVOS())){
                vo.setFromBtmType(Arrays.stream(linkType.btmItemsFrom).collect(Collectors.joining(",")));
                vo.setFromBtmTypeName(vo.getFromBtmTypeVOS().stream().map(OsBtmTypeVO::getName).collect(Collectors.joining(",")));
            }
            vo.setToBtmTypeVOS(btmService.listBtmByIds(Arrays.stream(linkType.btmItemsTo).collect(Collectors.toSet())));
            if(!CollectionUtils.isEmpty(vo.getToBtmTypeVOS())){
                vo.setToBtmType(Arrays.stream(linkType.btmItemsTo).collect(Collectors.joining(",")));
                vo.setToBtmTypeName(vo.getToBtmTypeVOS().stream().map(OsBtmTypeVO::getName).collect(Collectors.joining(",")));
            }
            vo.setImplClass(linkType.implClass);
            vo.setShape(linkType.shape);
            List<OsAttributeVO> attributeVOS = attributeService.listAttrByIds(Arrays.stream(linkType.attributes).collect(Collectors.toList()));
            List<OsLinkTypeAttributeVO> linkTypeAttributeVOS = new ArrayList<>();
            Optional.ofNullable(attributeVOS).orElseGet(()->new ArrayList<>()).stream().forEach(attributeVO->{
                OsLinkTypeAttributeVO linkTypeAttributeVO = new OsLinkTypeAttributeVO();
                BeanUtil.convert(attributeVO,linkTypeAttributeVO);
                linkTypeAttributeVO.setPkLinkType(vo.getOid());
                if(StringUtils.isNotBlank(attributeVO.getBtmTypeId())){
                    linkTypeAttributeVO.setReferFlag(true);
                    linkTypeAttributeVO.setReferBtmTypeId(attributeVO.getBtmTypeId());
                }
                if(StringUtils.isNotBlank(attributeVO.getEnumId())){
                    linkTypeAttributeVO.setEnumFlag(true);
                    linkTypeAttributeVO.setEnumItemMap(enumService.getEnumValueMap(linkTypeAttributeVO.getEnumId()));
                }
                linkTypeAttributeVOS.add(linkTypeAttributeVO);
            });
            vo.setAttributes(linkTypeAttributeVOS);
        }
        return vo;
    }
 
    /**
     * 使用编号获取链接类型
     *
     * @param linkIds 编号
     * @return 链接类型
     */
    @Override
    public List<OsLinkTypeVO> listLinkTypeIds(Collection<String> linkIds) {
        if(CollectionUtils.isEmpty(linkIds)){
            return null;
        }
        Map<String, OsLinkTypeVO> linkTypeVOMap = self.selectAllLinkMap();
        List<OsLinkTypeVO> linkTypeVOS = new ArrayList<>();
        linkIds.stream().forEach(id->{
            if(linkTypeVOMap.containsKey(id.toLowerCase())){
                linkTypeVOS.add(linkTypeVOMap.get(id.toLowerCase()));
            }
        });
        return linkTypeVOS;
    }
 
    /**
     * 使用编号获取链接类型
     *
     * @param id 编号
     * @return 链接类型
     */
    @Override
    public OsLinkTypeVO getLinkTypeById(String id) {
        if(StringUtils.isBlank(id)){
            return null;
        }
        return self.selectAllLinkMap().getOrDefault(id.toLowerCase(),null);
    }
 
    /**
     * 获取链接类型的属性
     *
     * @param linkTypeId 链接类型的编号
     * @return 链接类型的属性
     */
    @Override
    public List<OsLinkTypeAttributeVO> listAttributeByLinkId(String linkTypeId) {
        OsLinkTypeVO linkTypeVO = getLinkTypeById(linkTypeId);
        return linkTypeVO.getAttributes();
    }
 
    /**
     * 链接类型的列表
     *
     * @param baseQueryObject 查询对象
     * @return 链接类型的显示对象
     */
    @Override
    public DataGrid<OsLinkTypeVO> gridLinkType(BaseQueryObject baseQueryObject) {
        return gridObject(baseQueryObject, OsLinkTypeDO.class,self.selectAllLinkMap(),OsLinkTypeVO.class);
    }
 
    /**
     * 使用主键获取显示对象
     *
     * @param linkTypeOid 链接类型的主键
     * @return 链接类型的显示对象
     */
    @Override
    public OsLinkTypeVO selectByOid(String linkTypeOid) {
        List<OsLinkTypeVO> linkTypeVOS = self.selectAllLinkMap().values().stream().collect(Collectors.toList());
        return Optional.ofNullable(linkTypeVOS).orElseGet(()->new ArrayList<>()).stream().filter(s->s.getOid().equalsIgnoreCase(linkTypeOid)).findFirst().orElseGet(()->null);
 
    }
 
    /**
     * 获取链接类型关联的所有业务类型中属性类型差异的信息
     *
     * @param linkTypeOid 链接类型的主键
     * @return 有错误的属性
     */
    @Override
    public List<OsBtmTypeAttributeVO> checkAttributeTypeDifferent(String linkTypeOid) {
        if(StringUtils.isBlank(linkTypeOid)){
            return new ArrayList<>();
        }
        OsLinkTypeVO linkTypeVO = selectByOid(linkTypeOid);
        List<OsBtmTypeVO> fromBtmTypeVOS = linkTypeVO.getFromBtmTypeVOS();
        List<OsBtmTypeVO> toBtmTypeVOS = linkTypeVO.getToBtmTypeVOS();
        List<OsBtmTypeVO> btmTypeVOS = new ArrayList<>();
        btmTypeVOS.addAll(fromBtmTypeVOS);
        btmTypeVOS.addAll(toBtmTypeVOS);
 
        List<OsBtmTypeAttributeVO> diffList = new ArrayList<>();
        btmTypeVOS.stream().forEach(btmTypeVO -> {
            //查询这个表的信息
            String sql = "select t.column_name,t.data_type,t.data_length,t.nullable,t.data_precision,t.data_scale,c.comments from user_tab_columns t " +
                    "inner JOIN user_col_comments c on t.TABLE_NAME  = c.table_name and t.COLUMN_NAME = c.column_name where " +
                    "t.table_name = '" + VciBaseUtil.getTableName(btmTypeVO.getId()).toUpperCase(Locale.ROOT) + "' order by t.column_name asc";
            Map<String, OsBtmTypeAttributeVO> attributeVOMap = btmTypeVO.getAttributes().stream().collect(Collectors.toMap(s -> s.getId().toLowerCase(Locale.ROOT), t -> t));
            List<BusinessObject> cbosList = boService.queryBySql(sql, new HashMap<>());
            if(!CollectionUtils.isEmpty(cbosList)){
                cbosList.stream().forEach(cbo->{
                    String attrId = ObjectTool.getBOAttributeValue(cbo,"column_name");
                    String dataType = ObjectTool.getBOAttributeValue(cbo,"data_type");
                    if(StringUtils.isNotBlank(dataType) && dataType.contains("(")){
                        dataType = dataType.substring(0,dataType.indexOf("("));
                    }
                    OsBtmTypeAttributeVO attributeVO = attributeVOMap.getOrDefault(attrId.toLowerCase(Locale.ROOT), null);
                    if(attributeVO!=null){
                        String vtType = attributeVO.getAttrDataType();
                        String attrType = "";
                        VciFieldTypeEnum fieldTypeEnum = VciFieldTypeEnum.forValue(vtType);
                        if(fieldTypeEnum == null) {
                            attrType = "VARCHAR2";
                        }else {
                            switch (fieldTypeEnum) {
                                case VTString:
                                case VTBoolean:
                                    attrType = "VARCHAR2";
                                    break;
                                case VTInteger:
                                case VTLong:
                                case VTDouble:
                                    attrType = "NUMBER";
                                    break;
                                case VTDate:
                                    attrType = "DATE";
                                    break;
                                case VTDateTime:
                                case VTTime:
                                    attrType = "TIMESTAMP";
                                    break;
                                default:
                                    attrType = "VARCHAR2";
                                    break;
                            }
                        }
                        if(!attrType.equalsIgnoreCase(dataType)) {
                            diffList.add(attributeVO);
                        }
                    }
                });
            }
        });
        return diffList;
    }
 
    /**
     * 链接类型的列表
     *
     * @return 链接类型的显示对象
     */
    @Override
    public BaseResult<List<LinkType>> gridLink() throws PLException {
 
        LinkType[] linkTypes = platformClientUtil.getLinkTypeService().getLinkTypes();
        return BaseResult.dataList(Arrays.asList(linkTypes));
    }
    /**
     * 链接类型保存
     * linkType 链接类型的保存对象
     * addFlag 是否为新增 true新增,false修改
     * @return 保存结果
     */
    @Override
    public BaseResult addAndEditLink(LinkType linkType, Boolean addFlag) throws PLException {
        VciBaseUtil.alertNotNull(linkType.name,"请输入链接类型名称",linkType.btmItemsFrom,"From端业务类型不能为空!",
                linkType.btmItemsTo,"To端类型均不能为空!");
        int maxLength = platformClientUtil.getLinkTypeService().getLTNameMaxLength();
        if(linkType.name.length() > maxLength){
            throw new PLException("500",new String[] {"链接类型名长度不能超过" + maxLength});
        }
        if(!linkType.name.matches("^[A-Za-z]+$")){
            throw new PLException("500",new String[] {"链接类型名称只能为英文字母"});
        }
        LinkType historyLink = platformClientUtil.getLinkTypeService().getLinkType(linkType.name);
        if(historyLink != null && !historyLink.name.equals("") && addFlag){
            throw new PLException("500",new String[] {"该链接类型名称已经存在"});
        }
        linkType.modifier = WebUtil.getCurrentUserId();
        if(addFlag){
            linkType.creator = WebUtil.getCurrentUserId();
            platformClientUtil.getLinkTypeService().addLinkType(linkType);
            return BaseResult.success(null,"保存成功!");
        }
        ArrayList<String> removeAbList = getRemovedApList(historyLink, linkType);
        if(removeAbList.size() > 0 && platformClientUtil.getLinkTypeService().hasData(linkType.name)){
            linkType.attributes = historyLink.attributes;
            platformClientUtil.getLinkTypeService().modifyLinkType(linkType);
            throw new PLException("500",new String[] {"类型已有实例, 不进行移除操作"});
        }
        platformClientUtil.getLinkTypeService().modifyLinkType(linkType);
        return BaseResult.success(null,"保存成功!");
    }
    /**
     * 链接类型删除
     * linkType 链接类型对象
     * @return 删除结果
     */
    @Override
    public BaseResult deleteLink(LinkType linkType) throws PLException {
        if(platformClientUtil.getLinkTypeService().hasData(linkType.name)){
            throw new PLException("500",new String[] {"类型已有实例, 不进行删除操作"});
        }
        boolean flag = platformClientUtil.getLinkTypeService().deleteLinkType(linkType);
        if(!flag){
            throw new PLException("500",new String[] {"删除失败"});
        }else{
            return BaseResult.success();
        }
    }
    /**
     * 一致性检查
     * @return 删除结果
     */
    @Override
    public BaseResult checkLinkType() throws PLException {
        String[] result = platformClientUtil.getLinkTypeService().linkTypeConsistencyCheck();
        Map<String, String> dbCheckMap = new HashMap<String, String>();
        for(int i = 0; i < result.length; i++){
            String info = result[i];
            if(info.equals("")){
                continue;
            }
            String[] infos = info.split("/DML");
            String typeName = infos[0];
            String dml = infos[1];
            dbCheckMap.put(typeName, dml);
        }
        Map<String, List<String>> btmCheckMap = usedBtmCheck();
        if(dbCheckMap.size() < 1 && (btmCheckMap == null || btmCheckMap.size() < 1)){
            return BaseResult.successMsg("数据库中的表结构与类型一致, 链接类型引用的业务类型全部正确存在,无需修复!!");
        }else{
            Map<String,Object> returnData = new HashMap<>();
            returnData.put("dbCheckMap",dbCheckMap);
            returnData.put("btmCheckMap",btmCheckMap);
            List<Map> list = new ArrayList<>();
            list.add(returnData);
            BaseResult<List<Map>> listBaseResult = BaseResult.dataList(200, list, "需要进行列的修复!!");
            listBaseResult.setSuccess(false);
            return listBaseResult;
        }
    }
 
    /**
     * 一致性检查修复数据库表
     * repairData 需要修复的数据
     * @return 修复结果
     */
    @Override
    public BaseResult repairTable(String repairData) throws PLException, IOException {
        Map<String, Object> map = new ObjectMapper().readValue(repairData, new TypeReference<Map<String,Object>>(){});
        HashMap<String,Object> dbCheckMap = (HashMap<String, Object>) map.get("dbCheckMap");
        HashMap<String,List<String>> btmCheckMap = (HashMap<String, List<String>>) map.get("btmCheckMap");
        List returnList = new ArrayList<>();
        Map returnMap = new HashMap();
        if(dbCheckMap.size() > 0){
            List<String> list = getRepairDML(dbCheckMap);
            if(list.size() < 1){
                return BaseResult.success();
            }
            String[] result = platformClientUtil.getLinkTypeService().executeRepair(list.toArray(new String[0]));
            List<String> resultList = Arrays.asList(result);
            for (String typeName : resultList) {
                if(dbCheckMap.containsKey(typeName)){
                    dbCheckMap.remove(typeName);
                }else if(dbCheckMap.containsKey(typeName + "_ADD")){
                    String sql = String.valueOf(dbCheckMap.get(typeName));
                    sql = sql.substring(sql.indexOf(";") + 1, sql.length());
                    dbCheckMap.put(typeName, sql);
                }else if(dbCheckMap.containsKey(typeName + "_DROP")){
                    String sql = String.valueOf(dbCheckMap.get(typeName));
                    sql = sql.substring(0, sql.indexOf(";"));
                    dbCheckMap.put(typeName, sql);
                }
            }
            if(!dbCheckMap.isEmpty()){
                returnMap.put("dbCheckMap",dbCheckMap);
            }
        }
 
        if(btmCheckMap.size() > 0){
            List<String> result = repairXml(btmCheckMap);
            for(int i = 0; i < result.size(); i++){
                String typeName = result.get(i);
                if(btmCheckMap.containsKey(typeName)){
                    btmCheckMap.remove(typeName);
                }
            }
            if(!btmCheckMap.isEmpty()){
                returnMap.put("btmCheckMap",btmCheckMap);
            }
        }
        returnList.add(returnMap);
        return BaseResult.success(returnList);
    }
    /**
     * 创建视图
     * @return 创建结果
     */
    @Override
    public BaseResult createView() throws PLException {
        boolean f = platformClientUtil.getLinkTypeService().createView();
        if(f){
            return BaseResult.success("创建视图成功");
        }else{
            return BaseResult.success("创建视图失败");
        }
    }
 
    /**
     * 导出链接类型
     * name 链接类型名称
     * @return 创建结果
     */
    @Override
    public void expData(String names, HttpServletResponse response) throws PLException, IOException {
        String defaultTempFolder = LocalFileUtil.getDefaultTempFolder();
        //写excel
        String excelPath = defaultTempFolder + File.separator + "lt.xls";
        //设置列名
        List<String> columns = new ArrayList<>(
                Arrays.asList("名称", "标签", "实现类", "形状", "From端类型列表", "From端主类型", "From端对应关系",
                        "To端类型列表", "To端主类型", "To端对应关系", "属性列表", "描述")
        );
        try {
            new File(excelPath).createNewFile();
            //设置列
            List<WriteExcelData> excelDataList = new ArrayList<>();
            //设置列头
            for (int index = 0; index < columns.size(); index++) {
                excelDataList.add(new WriteExcelData(0,index, columns.get(index)));
            }
            HashSet<String> attributes = new HashSet<>();
            int i = 0;
            for (String name : names.split(",")) {
                LinkType lt = platformClientUtil.getLinkTypeService().getLinkType(name);
                excelDataList.add(new WriteExcelData(i+1,0, lt.name));
                excelDataList.add(new WriteExcelData(i+1,1, lt.tag));
                excelDataList.add(new WriteExcelData(i+1,2, lt.implClass));
                excelDataList.add(new WriteExcelData(i+1,3, lt.shape));
                excelDataList.add(new WriteExcelData(i+1,4, String.join(",",lt.btmItemsFrom)));
                excelDataList.add(new WriteExcelData(i+1,5, lt.primitivesFrom));
                excelDataList.add(new WriteExcelData(i+1,6, lt.relationFrom));
                excelDataList.add(new WriteExcelData(i+1,7, String.join(",",lt.btmItemsTo)));
                excelDataList.add(new WriteExcelData(i+1,8, lt.primitivesTo));
                excelDataList.add(new WriteExcelData(i+1,9, lt.relationTo));
                excelDataList.add(new WriteExcelData(i+1,10, String.join(",",lt.attributes)));
                excelDataList.add(new WriteExcelData(i+1,11, lt.description));
                attributes.addAll(Arrays.asList(lt.attributes));
                i++;
            }
            WriteExcelOption excelOption = new WriteExcelOption(excelDataList);
            ExcelUtil.writeDataToFile(excelPath, excelOption);
            //导出属性
            String attrPath = attributeService.exportAttributes("attr",
                    String.valueOf(attributes.stream().collect(Collectors.joining(","))),true);
            //移动属性到链接类型文件夹里面去
            FileUtil.move(new File(attrPath), new File(defaultTempFolder),true);
            FileUtil.del(attrPath.substring(0,attrPath.lastIndexOf("\\")));
            //todo 导出业务类型还没有实现
//            List<BizType> bts = new ArrayList<BizType>();
//            for (String btName : btNameSet) {
//                BizType bt = BtmProvider.getBtmItemByName(btName);
//                bts.add(bt);
//            }
//            boolean btFlag = BtmProvider.expData(rootPath, bts.toArray(new BizType[0]));
        }catch (IOException e) {
            throw new RuntimeException(e);
        }
        File zip = ZipUtil.zip(defaultTempFolder);
        FileUtil.del(defaultTempFolder + File.separator);
        ControllerUtil.writeFileToResponse(response,zip.getAbsoluteFile());
    }
 
    /**
     * 导入链接类型
     * @param file 上传的文件
     * @return
     */
    @Override
    public BaseResult impData(MultipartFile file) throws Exception {
        String defaultTempFolder = LocalFileUtil.getDefaultTempFolder();
        String fileName = defaultTempFolder + File.separator + LocalFileUtil.getFileNameForIE(file.getOriginalFilename());
        file.transferTo(new File(fileName));
        if (file == null) {
            return BaseResult.fail(FrameWorkLangCodeConstant.IMPORT_FAIL, new String[]{"无导入的文件"});
        }
        if (!fileName.endsWith(".zip")) {
            throw new VciBaseException("仅能上传zip压缩文件,请重新上传!");
        }
        File unzip = ZipUtil.unzip(fileName);
        File ltExcel = new File(unzip.getAbsolutePath() + File.separator + "lt.xls");
        File attrExcel = new File(unzip.getAbsolutePath() + File.separator + "attr.xls");
        if (!attrExcel.exists()) {
            //增加解压的路径,看文件还在没有
            attrExcel = new File(unzip.getAbsolutePath() + File.separator + unzip.getName() + File.separator + "attr.xls");
            if (!attrExcel.exists()) {
                return BaseResult.fail(FrameWorkLangCodeConstant.IMPORT_FAIL, new String[]{"没有导入的属性文件。导入终止!"});
            }
        }
        BaseResult baseResult = attributeService.importAttributes(attrExcel);
        if(!baseResult.isSuccess()){
            //删除上传的文件夹
            FileUtil.del(defaultTempFolder + File.separator);
            return baseResult;
        }
        //todo 还需导入业务类型,等待功能实现
        if (!ltExcel.exists()) {
            //增加解压的路径,看文件还在没有
            ltExcel = new File(unzip.getAbsolutePath() + File.separator + unzip.getName() + File.separator + "lt.xls");
            if (!ltExcel.exists()) {
                //删除上传的文件夹
                FileUtil.del(defaultTempFolder + File.separator);
                return BaseResult.fail(FrameWorkLangCodeConstant.IMPORT_FAIL, new String[]{"没有导入的链接文件。导入终止!"});
            }
        }
        try{
            //1、读取excel中的数据,组成对象
            ReadExcelOption excelOption = new ReadExcelOption();
            List<OsLinkTypePO> poList = ExcelUtil.readDataObjectFromExcel(ltExcel, OsLinkTypePO.class,excelOption,(value, po, fieldName)->{});
            //去除都是空的情况
            if(CollectionUtils.isEmpty(poList)){
                return BaseResult.fail(ExcelLangCodeConstant.IMPORT_CONTENT_NULL,new String[]{});
            }
            //当前excel中是否重复用的判重Map:(key:判重属性,value:行号)
            Map<String, String> excelReapeat = new HashMap<>();
            int maxLength = platformClientUtil.getLinkTypeService().getLTNameMaxLength();
 
            //判断必填属性是否为空,用户是否已存在,以及部门是否填错等校验逻辑
            poList.stream().forEach(osLinkTypePO -> {
                if(Func.isBlank(osLinkTypePO.getName())){//属性名判空
                    throw new VciBaseException("第【"+osLinkTypePO.getRowIndex()+"】行,name");
                }else if(osLinkTypePO.getName().length() > maxLength){
                    throw new VciBaseException("第【"+osLinkTypePO.getRowIndex()+"】行,链接类型名长度不能超过" + maxLength);
                }else if(!osLinkTypePO.getName().matches("^[A-Za-z]+$")){
                    throw new VciBaseException("第【"+osLinkTypePO.getRowIndex()+"】行,链接类型名称只能为英文字母");
                }else if(excelReapeat.containsKey(osLinkTypePO.getName())){//属性名表格中判重
                    throw new VciBaseException("第【"+excelReapeat.get(osLinkTypePO.getName())+"】行和第【"+osLinkTypePO.getRowIndex()+"】行数据,属性名重复");
                }
                try {
                    LinkType historyLink = platformClientUtil.getLinkTypeService().getLinkType(osLinkTypePO.getName());
                    //已有此数据进行删除覆盖
                    if(historyLink != null && !historyLink.name.equals("")){
                        platformClientUtil.getLinkTypeService().deleteLinkType(historyLink);
                    }
                } catch (PLException e) {
                    throw new RuntimeException(e);
                }
 
                //属性名excel中判重处理
                excelReapeat.put(osLinkTypePO.getName(),osLinkTypePO.getRowIndex());
                LinkType linkType = new LinkType();
                linkType.name = osLinkTypePO.getName();
                linkType.attributes = osLinkTypePO.getAttributes().split(",");
                linkType.btmItemsFrom = osLinkTypePO.getBtmItemsFrom().split(",");
                linkType.primitivesFrom = osLinkTypePO.getPrimitivesFrom();
                linkType.relationFrom = osLinkTypePO.getRelationFrom();
                linkType.btmItemsTo = osLinkTypePO.getBtmItemsTo().split(",");
                linkType.primitivesTo = osLinkTypePO.getPrimitivesTo();
                linkType.relationTo = osLinkTypePO.getRelationTo();
                linkType.relation = osLinkTypePO.getRelationFrom() + ":" + osLinkTypePO.getRelationTo();
                linkType.description = osLinkTypePO.getDescription();
                linkType.tag = osLinkTypePO.getTag();
                linkType.shape = osLinkTypePO.getShape();
                linkType.implClass = osLinkTypePO.getImplClass();
                linkType.modifier = WebUtil.getCurrentUserId();
                linkType.creator = WebUtil.getCurrentUserId();
                try {
                    platformClientUtil.getLinkTypeService().addLinkType(linkType);
                } catch (PLException e) {
                    throw new RuntimeException(e);
                }
 
            });
        }catch (Exception e){
            if(logger.isErrorEnabled()){
                logger.error("读取excel内容时或保存用户信息时出现了错误,具体原因:",VciBaseUtil.getExceptionMessage(e));
            }
            e.printStackTrace();
            return BaseResult.fail(VciBaseUtil.getExceptionMessage(e),new String[]{},e);
        }
        //删除上传的文件夹
        FileUtil.del(defaultTempFolder + File.separator);
        return BaseResult.success("链接类型导入成功!");
    }
    /**
     * 获取链接类型包含的属性
     * @param name 链接类型的编号
     * @return 属性的信息
     */
    @Override
    public List<OsLinkTypeAttributeVO> getAllAttributeByLink(String name) throws PLException, ParseException {
        AttributeDef[] attributes = platformClientUtil.getLinkTypeService().getAttributes(name);
        AttributeDef[] sysAttributeDefs = platformClientUtil.getLinkTypeService().getSysAttributeDefs();
        List<OsLinkTypeAttributeVO> links = new ArrayList<>();
        for (AttributeDef sysAttributeDef : sysAttributeDefs) {
            OsLinkTypeAttributeVO vo = new OsLinkTypeAttributeVO();
            vo.setOid(sysAttributeDef.oid);
            vo.setAttrDataType(sysAttributeDef.vtDataType);
            vo.setPkLinkType(name);
            vo.setCreateTime(new Date(sysAttributeDef.createTime));
            vo.setCreator(sysAttributeDef.creator);
            vo.setDefaultValue(sysAttributeDef.defValue);
            vo.setDescription(sysAttributeDef.description);
            vo.setRange(sysAttributeDef.rage);
            vo.setId(sysAttributeDef.name);
            vo.setName(sysAttributeDef.label);
            vo.setLastModifier(sysAttributeDef.modifier);
            vo.setLastModifyTime(new Date(sysAttributeDef.modifyTime));
            links.add(vo);
        }
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (AttributeDef attribute : attributes) {
            OsLinkTypeAttributeVO vo = new OsLinkTypeAttributeVO();
            vo.setOid(attribute.oid);
            vo.setAttrDataType(attribute.vtDataType);
            vo.setPkLinkType(name);
            vo.setCreateTime(new Date(attribute.createTime));
            vo.setCreator(attribute.creator);
            vo.setDefaultValue(attribute.defValue);
            vo.setDescription(attribute.description);
            vo.setRange(attribute.rage);
            vo.setId(attribute.name);
            vo.setName(attribute.label);
            vo.setTs(formatter.parse(attribute.ts));
            vo.setLastModifier(attribute.modifier);
            vo.setOwner(attribute.creator);
            vo.setLastModifyTime(new Date(attribute.modifyTime));
            String maxLength = AttributeConstants.getOtherValueByType(attribute.other, AttributeConstants.LENGTH);
            if(StringUtils.isNotBlank(maxLength)){
                vo.setAttributeLength(Integer.valueOf(maxLength));
            }
            links.add(vo);
        }
        return links;
    }
 
    /**
     * 修复链接类型的xml文件
     * @return
     */
    private List<String> repairXml(HashMap<String, List<String>> btmCheckMap){
        List<String> result = new ArrayList<String>();
        for(Iterator<String> ite = btmCheckMap.keySet().iterator(); ite.hasNext();){
            String linkName = ite.next();
            List<String> list = btmCheckMap.get(linkName);
            LinkType link = null;
            try {
                link = platformClientUtil.getLinkTypeService().getLinkType(linkName);
            } catch (PLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
                continue;
            }
            //将list中包含的F_btm移除, 重新设置btmItemsFrom
            String[] btms_ = link.btmItemsFrom;
            List<String> btms = new ArrayList<String>();
            for(int i = 0; i < btms_.length; i++){
                if(!list.contains("F_" + btms_[i])){
                    btms.add(btms_[i]);
                }else{
                    if(link.primitivesFrom.equals(btms_[i])){
                        link.primitivesFrom = "";
                    }
                }
            }
            link.btmItemsFrom = btms.toArray(new String[0]);
 
            //将list中包含的T_btm移除, 重新设置btmItemsTo
            btms_ = link.btmItemsTo;
            btms = new ArrayList<String>();
            for(int i = 0; i < btms_.length; i++){
                if(!list.contains("T_" + btms_[i])){
                    btms.add(btms_[i]);
                }else{
                    if(link.primitivesTo.equals(btms_[i])){
                        link.primitivesTo = "";
                    }
                }
            }
            link.btmItemsTo = btms.toArray(new String[0]);
            link.id = link.name;
            try {
                if(platformClientUtil.getLinkTypeService().modifyLinkType(link)){
                    result.add(linkName);
                }
            } catch (PLException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
    /**
     * 获取需要修复的伪sql
     * @return
     */
    private List<String> getRepairDML(HashMap<String, Object> dbCheckMap) {
        List<String> list = new ArrayList<String>();
        for(Iterator<String> ite = dbCheckMap.keySet().iterator(); ite.hasNext();){
            String type = ite.next();
            String dml = String.valueOf(dbCheckMap.get(type));
            list.add(type + "/DML" + dml);
        }
        return list;
    }
    /**
     * 检查所有的链接类型, 当链接类型中引用的业务类型已经不存在时, 删除该链接类型中对业务类型的引用
     * @return
     */
    private Map<String, List<String>> usedBtmCheck(){
        try {
            Map<String, List<String>> map = new HashMap<String, List<String>>();
            LinkType[] links = platformClientUtil.getLinkTypeService().getLinkTypes();
            for(int i = 0; i < links.length; i++){
                LinkType link = links[i];
                String[] btms = link.btmItemsFrom;
                for(int k = 0; k < btms.length; k++){
                    String btmName = btms[k];
                    BizType btm = platformClientUtil.getBtmService().getBizTypeByName(btmName);
                    if(btm == null || btm.name.equals("")){
                        List<String> list = map.get(link.name);
                        if(list == null){
                            list = new ArrayList<String>();
                            list.add("F_" + btmName);
                        }else{
                            list.add("F_" + btmName);
                        }
                        map.put(link.name, list);
                    }
                }
                btms = link.btmItemsTo;
                for(int k = 0; k < btms.length; k++){
                    String btmName = btms[k];
                    BizType btm = platformClientUtil.getBtmService().getBizTypeByName(btmName);
                    if(btm == null || btm.name.equals("")){
                        List<String> list = map.get(link.name);
                        if(list == null){
                            list = new ArrayList<String>();
                            list.add("T_" + btmName);
                        }else{
                            list.add("T_" + btmName);
                        }
                        map.put(link.name, list);
                    }
                }
            }
            return map;
        } catch (PLException e) {
            e.printStackTrace();
        }
        return null;
    }
 
 
    /**
     * 获取修改链接类型时 减少的属性
     * @param oldLt
     * @param newLt
     * @return
     */
    private ArrayList<String> getRemovedApList(LinkType oldLt,
                                               LinkType newLt) {
        String[] oldAbInfo = oldLt.attributes;
        ArrayList<String> oldNameList = new ArrayList<String>();
        for(int i = 0; i < oldAbInfo.length; i++){
            oldNameList.add(oldAbInfo[i]);
        }
        String[] newAbInfo = newLt.attributes;
        ArrayList<String> newNameList = new ArrayList<String>();
        for(int i = 0; i < newAbInfo.length; i++){
            newNameList.add(newAbInfo[i]);
        }
 
        ArrayList<String> removedApList = new ArrayList<String>();
 
        for(Iterator<String> iterator = oldNameList.iterator(); iterator.hasNext();){
            String oldName = iterator.next();
            if(!newNameList.contains(oldName)){
                removedApList.add(oldName);
            }
        }
        return removedApList;
    }
 
    /**
     * 清除缓存
     */
    @Override
    public void clearCache() {
 
    }
 
    /**
     * 修改链接类型中对应属性名的属性
     * @param apName
     * @return
     * @throws PLException
     */
    @Override
    public boolean alterAp(String apName) throws PLException {
        String[] linkNames = null;
        List<String> linkNameList = new ArrayList<String>();
        AttributeDef abItem = null;
        try {
            abItem = platformClientUtil.getAttributeService().getAttributeDefByName(apName);
        } catch (PLException e1) {
            e1.printStackTrace();
        }
        if(abItem == null || abItem.equals("")){
            return true;
        }
        try {
            linkNames = platformClientUtil.getLinkTypeService().getLTNamesByAPName(apName);
        } catch (PLException e) {
            e.printStackTrace();
        }
        if(linkNames == null || linkNames.length <= 0){
            return true;
        }
 
        linkNameList = Arrays.asList(linkNames);
        for(Iterator<String> i = linkNameList.iterator(); i.hasNext();){
            String linkName = i.next();
            try {
                platformClientUtil.getLinkTypeService().modifyLTAttribute(linkName, apName);
            } catch (PLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                String erreMsg = "调整链接类型中【"+apName+"】属性时出现错误,原因:"+e.getMessage();
                logger.error(erreMsg);
                throw new PLException("500",new String[]{erreMsg});
            }
        }
        return false;
    }
 
    /**
     * 判断该属性是否已经在链接类型中产生了数据
     * @param abName
     * @return
     * @throws PLException
     */
    @Override
    public boolean hasInstance(String abName) throws PLException {
        String[] btmNames = platformClientUtil.getLinkTypeService().getLTNamesByAPName(abName);
        if(btmNames == null || btmNames.length == 0){
            return false;
        }
        for(int i = 0; i < btmNames.length; i++){
            String btmName = btmNames[i];
            boolean flag;
            flag = platformClientUtil.getLinkTypeService().hasData(btmName);
            if(flag){
                return flag;
            }
        }
        return false;
    }
 
    /**
     * 获取连接类型名称集合
     * @return
     */
    @Override
    public List<String> getAllLtName() throws PLException {
        LinkType[] linkTypes = platformClientUtil.getLinkTypeService().getLinkTypes();
        if(null != linkTypes && linkTypes.length > 0){
            return Arrays.stream(linkTypes).map(linkType -> linkType.name).collect(Collectors.toList());
        }
        return null;
    }
 
}