354798ggg
2023-08-29 fd0c7c174d7b7313aa49061df05350405a3c1bf1
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
package com.product.data.sync.service;
 
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.product.admin.service.CodeService;
import com.product.common.lang.StringUtils;
import com.product.core.config.Global;
import com.product.core.dao.BaseDao;
import com.product.core.entity.DataTableEntity;
import com.product.core.entity.FieldMetaEntity;
import com.product.core.entity.FieldSetEntity;
import com.product.core.entity.RequestParameterEntity;
import com.product.core.exception.BaseException;
import com.product.core.service.support.AbstractBaseService;
import com.product.core.spring.context.SpringMVCContextHolder;
import com.product.data.sync.config.CmnConst;
import com.product.data.sync.util.DataManipulationUtils;
import com.product.file.service.FileManagerService;
import com.product.module.sys.service.UserService;
import com.product.org.admin.service.SystemOrgLevelsService;
import com.product.org.admin.service.idel.ISystemOrgLevelsService;
import com.product.util.BaseDaoServiceImpl;
import com.product.util.BaseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
 
@Component
public class FeDataDSService extends AbstractBaseService {
 
    @Autowired
    public BaseDao baseDao;
    @Autowired
    private UserService userService;
    @Autowired
    private CodeService codeService;
    @Autowired
    private SystemOrgLevelsService systemOrgLevelsService;
 
    @Autowired
    public FunctionSynchrService functionSynchrService;
    @Autowired
    FileManagerService fileManagerService;
 
    //临时文件路径
    private static String TSPath = Global.getSystemConfig("new.filePackage","");
    private static String testString = "^(\\d{0,4}`)|(\\d{0,3}\\^\\d{0,4}`)";
    private static String startWith = "FE#ENC#";
    private int[] intPosition = new int[64];
    //我们产品的功能权限
    private String[] functionCode = {"001-004-000-000","001-004-000-001","001-004-000-002","001-004-000-003","001-004-000-004",
            "001-006-006-000","001-006-002-000","001-006-000-000","001-006-001-000",
            "001-006-001-001","001-006-000-001", "001-006-002-001" ,"001-006-002-002","001-006-004-000",
            "001-006-003-000","001-006-002-003","001-006-003-001","001-006-003-002","001-006-003-003",
            "001-006-004-001","001-006-003-004","001-006-003-005","001-006-003-006","001-006-006-001",
            "001-006-008-000","001-006-008-001","001-006-008-002", "001-006-008-003","001-006-008-004",
            "001-006-008-005","001-006-008-006", "001-006-000-003", "001-006-011-000","001-006-011-001",
            "001-008-001-001","001-008-001-000","001-008-001-003"};
 
    private Integer sort = 0;
    //公司和部门map   key 为公司或部门全称
    Map<String, FieldSetEntity> institutionMap = Maps.newHashMap();
    public Connection getJDBC() throws SQLException, ClassNotFoundException {
        //获取jdbc连接
//        String diver = "oracle.jdbc.driver.OracleDriver";
//        String url = "jdbc:oracle:thin:@10.0.0.21:1521:orcl";
//        return DataManipulationUtils.getConnection(diver, url, "FE_BASE5", "fe123");
        //获取jdbc连接
        String diver = Global.getSystemConfig("data.synchronism.function.jdbc.diver", "");
        String url = Global.getSystemConfig("data.synchronism.function.jdbc.url", "");
        String name = Global.getSystemConfig("data.synchronism.function.jdbc.name", "");
        String password = Global.getSystemConfig("data.synchronism.function.jdbc.password", "");
        return DataManipulationUtils.getConnection(diver, url, name, password);
    }
 
 
    public String FEDataMigration(){
        String clientUUID = "";
        try {
            //admin初始化客户及角色
            clientUUID = this.initializeClients();
            //同步公司部门
            this.syncDepartmentCompany();
            //封装公司部门map
            this.packInstitutionMap();
            //同步岗位等级和岗位
            this.synchronousPost();
            //同步角色
            this.synchronousRole();
            //同步管理员
            this.syncManager(clientUUID);
            //同步人员
            this.addEmployees(clientUUID);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return clientUUID;
    }
 
    /**
     *     初始化客户及客户角色(修改客户为FE的客户名称)
     * @return
     * @throws SQLException
     * @throws ClassNotFoundException
     */
    public String initializeClients() throws SQLException, ClassNotFoundException {
        FieldSetEntity grouoFs = null;
        Connection conn = this.getJDBC();
        try {
            grouoFs = BaseDaoServiceImpl.getFieldSet(conn, "fe_base5.SYS_GROUP", "SG10=1", new Object[]{});
        } catch (Exception e) {
            DataManipulationUtils.close(null, null, conn);
            throw e;
        }
        //查询原客户  改为西宁
        FieldSetEntity tableFs = baseDao.getFieldSetEntityByFilter("product_sys_clients", " client_code = ? ", new String[]{"001"},false);
        if (tableFs==null) {
            throw new BaseException("500", "客户表没有001的数据");
        }
        //原客户名称
        String clientName = tableFs.getString("client_name");
        tableFs.setValue("client_name", grouoFs.getString("sg01"));
        String clientUUID = tableFs.getUUID();
        //查询原客户的角色  改为西宁
        FieldSetEntity roleFs = baseDao.getFieldSetEntityByFilter("product_sys_role", " role_name = ? ", new String[]{clientName}, false);
        roleFs.setValue("role_name", grouoFs.getString("sg01"));
        //修改角色
        baseDao.update(roleFs);
        //修改客户
//        tableFs.setCodeFieldUpdateFlat("client_code", true);
        baseDao.update(tableFs);
        return clientUUID;
    }
 
    /**
     * 同步单位管理员
     */
    public void syncManager(String clientUUID) throws SQLException, ClassNotFoundException {
        Connection conn = this.getJDBC();
        DataTableEntity managerData;
        try {
            //获取岗位 修改/ 为> 方便适配我们数据表
            StringBuffer sql = new StringBuffer();
            sql.append(" SELECT A.*,REPLACE(REPLACE(REPLACE(A.SU03, '/西宁市住房保障和房产管理局', ''),  ")
                    .append(" '西宁市住房保障和房产管理局/局属各单位/','西宁市住房保障和房产管理局/'),'/','>') ASU03 FROM  ")
                    .append(" FE_BASE5.SYS_USERS A WHERE A.SU31 = 2 ");
            //人员数据
            managerData = BaseDaoServiceImpl.getDataTable(conn, sql.toString(), new Object[]{});
            this.syncManager(managerData, clientUUID);
        } catch (Exception e) {
            throw e;
        }
    }
 
    /**
     *  同步管理员
     * @param managerData 管理员用户数据
     */
    public void syncManager(DataTableEntity managerData,String clientUUID){
        if(!BaseUtil.dataTableIsEmpty(managerData)) {
            for (int i = 0; i < managerData.getRows(); i++) {
                FieldSetEntity userFs = new FieldSetEntity();
                FieldSetEntity fse = managerData.getFieldSetEntity(i);
                userFs.setTableName("product_sys_users");
                String su01 = fse.getString("su01");
                userFs.setValue("user_name", su01);
                userFs.setValue("user_account",su01);
                userFs.setValue("gender", 1);
                userFs.setValue("user_pwd", userService.createPassWord(su01, "123"));
                userFs.setValue("is_manager", 1);
                userFs.setValue("created_by", SpringMVCContextHolder.getCurrentUser().getUser_id());
                userFs.setValue("created_utc_datetime", new Date());
                userFs.setValue("status", 1);
 
                //新增管理员
                String usersUUID = baseDao.add(userFs);
                FieldSetEntity users = baseDao.getFieldSetEntity("product_sys_users", usersUUID, false);
                FieldSetEntity managerFs = new FieldSetEntity();
                managerFs.setTableName("product_sys_org_manager");
                managerFs.setValue("user_id", users.getString("user_id"));
                //企业管理员
                managerFs.setValue("manager_type", "2");
                managerFs.setValue("role_uuids", "eabb00f3-2118-4165-967b-a7d88f472f67-notchange");
                managerFs.setValue("is_used", 1);
                managerFs.setValue("clients_uuid", clientUUID);
                managerFs.setValue("created_by", SpringMVCContextHolder.getCurrentUser().getUser_id());
                managerFs.setValue("created_utc_datetime", new Date());
                //重新组装后的组织全称
                String uuid = this.getSuperiorCompanyUuid(fse.getString("asu03"));
                managerFs.setValue("org_level_uuid", uuid);
                baseDao.add(managerFs);
            }
 
        }
    }
 
 
    /**
     * 同步公司部门
     */
    public void syncDepartmentCompany() throws SQLException, ClassNotFoundException {
 
        //同步组织机构数据存放集合
        DataTableEntity groupLeadersFs;
        Connection conn = this.getJDBC();
        try {
            StringBuffer sql = new StringBuffer();
            sql.append("SELECT A.*,REPLACE(REPLACE(A.SG03, '/西宁市住房保障和房产管理局', ''), '西宁市住房保障和房产管理局/局属各单位/','西宁市住房保障和房产管理局/') ASG03 FROM ( ")
                   .append( "SELECT * FROM FE_BASE5.SYS_GROUP WHERE length(SG10) > 3 or SG10 = '001'  ORDER BY SG10) A ORDER BY SG10");
            //获取需要同步的组织机构
            groupLeadersFs = BaseDaoServiceImpl.getDataTable(conn, sql.toString(), new Object[]{});
        } catch (Exception e) {
            throw e;
        }
        DataManipulationUtils.close(null, null, conn);
        
        //创建顶级公司
        //获取FE顶级公司
        FieldSetEntity topCompanies = groupLeadersFs.getFieldSetEntity(0);
        //获取产品001顶级公司
        FieldSetEntity field = baseDao.getFieldSetEntityByFilter("product_sys_org_levels", " org_level_code = 001 ", null,false);
        //更新公司名称,公司短编码,公司排序
        field.setValue("org_level_name", topCompanies.getString("sg01"));
        field.setValue("org_level_shortcode",  topCompanies.getString("sg10"));
        field.setValue("sequence",  topCompanies.getString("sg00"));
//      field.setCodeFieldUpdateFlat("org_level_code", true);
        
        //事物调用,保存公司信息
        ISystemOrgLevelsService service=(ISystemOrgLevelsService) getProxyInstance(systemOrgLevelsService);
        service.updateCompany(field);
        
//        FieldSetEntity topField = this.addCompany(topCompanies,null, null);
        institutionMap.put(field.getString("org_level_all"),field);
        
        //遍历fe架构数据 存入组织架构信息表
        for (int i = 1; i < groupLeadersFs.getRows(); i++) {
            
            FieldSetEntity levelFs = groupLeadersFs.getFieldSetEntity(i);
            //获取FE表组织机构全称
            String asg03 = levelFs.getString("asg03");
            //截取为上级公司相同的全称
            String level_all = asg03.substring(0,asg03.lastIndexOf("/"));
            //替换为一样的符号方便对比
            level_all = level_all.replace("/", ">");
            //获取上级公司或部门
            FieldSetEntity fieldSet = institutionMap.get(level_all);
            //上级公司uuid
            String org_level_uuid = this.getSuperiorCompanyUuid(level_all);
            if(fieldSet == null){
                throw new BaseException("上级为空","无法获取上级code");
            }
            if(org_level_uuid == null){
                throw new BaseException("上级公司为空","上级公司uuid");
            }
            //上级公司code
            String org_level_code = fieldSet.getString("org_level_code");
            FieldSetEntity fse;
//            levelFs.setCodeFieldUpdateFlat("org_level_code", true);
            //进入新增公司方法
            if(levelFs.getInteger("sg14") == 1){
                fse = this.addCompany(levelFs,org_level_code,org_level_uuid);
            //进入新增部门方法
            }else {
                fse = this.addDepartment(levelFs, org_level_code, org_level_uuid);
            }
            institutionMap.put(fse.getString("org_level_all"), fse);
        }
 
//        //创建西宁市住房保障和房产管理局下部门(办公室)
//        FieldSetEntity fse = new FieldSetEntity();
//        //部门名称,,
//        fse.setValue("org_level_name", "办公室");
//        //部门编码
//        fse.setValue("org_level_shortcode",  "001002");
//        //获取上级公司或部门
//        FieldSetEntity fieldSet = institutionMap.get("西宁市住房保障和房产管理局");
//        FieldSetEntity fs = this.addDepartment(fse,fieldSet.getString("org_level_code"), fieldSet.getUUID());
//        institutionMap.put(fs.getString("org_level_all"), fs);
    }
 
    /**
     * 同步岗位和岗位等级
     */
    public void synchronousPost() throws SQLException, ClassNotFoundException {
 
        Connection conn = this.getJDBC();
        DataTableEntity groupLeadersFs;
        try {
            //获取岗位 修改/ 为> 方便适配我们数据表
            StringBuffer sql = new StringBuffer();
            sql.append(" SELECT SR00,SR01,SR02,SR10, SR15, ")
                    .append(" REPLACE(REPLACE(REPLACE(SR03, '/西宁市住房保障和房产管理局', ''),  ")
                    .append(" '西宁市住房保障和房产管理局/局属各单位/','西宁市住房保障和房产管理局/'),'/','>') ASR03 FROM fe_base5.SYS_ROLE  ");
            //1为公司
            groupLeadersFs = BaseDaoServiceImpl.getDataTable(conn, sql.toString(), new Object[]{});
        } catch (Exception e) {
 
            throw e;
        }
        DataManipulationUtils.close(null, null, conn);
        //同步岗位等级
        this.postGrades(groupLeadersFs);
        this.addPost(groupLeadersFs);
    }
 
    /**
     * 同步角色
     */
    public void synchronousRole()throws  SQLException, ClassNotFoundException{
        Connection conn = this.getJDBC();
        DataTableEntity roleData;
        try {
            //获取岗位 修改/ 为> 方便适配我们数据表
            StringBuffer sql = new StringBuffer();
            sql.append(" select * from fe_base5.SYS_POPEDOM_TEMPLET a left join fe_base5.SYS_POPEDOM_TEMP_SUB b on  a.SPT00=b.STS01 ");
            //人员数据
            roleData = BaseDaoServiceImpl.getDataTable(conn, sql.toString(), new Object[]{});
 
        } catch (Exception e) {
            throw e;
        }
        DataManipulationUtils.close(null, null, conn);
        this.synchronousRole(roleData);
 
    }
 
    /**
     * 初始化基本权限
     */
    public void packageButton(String role_uuid){
        StringBuffer sql = new StringBuffer();
        String tricodeIn = BaseUtil.buildQuestionMarkFilter("tricode", this.functionCode, true);
        sql.append(" SELECT function_uuid,group_concat(uuid SEPARATOR ',') button_uuid FROM  product_sys_function_buttons WHERE function_uuid IN ( ")
                .append(" SELECT uuid FROM product_sys_functions WHERE ")
                .append(tricodeIn).append(" ) GROUP BY function_uuid ");
        DataTableEntity dataTableEntity = baseDao.listTable(sql.toString(),new String[]{});
        for (int i = 0; i < dataTableEntity.getRows(); i++) {
            FieldSetEntity fieldSetEntity = new FieldSetEntity();
            fieldSetEntity.setTableName("product_sys_function_permission");
            fieldSetEntity.setValue("function_uuid", dataTableEntity.getString(i,"function_uuid"));
            fieldSetEntity.setValue("button_uuid", dataTableEntity.getString(i,"button_uuid"));
            fieldSetEntity.setValue("role_uuid", role_uuid);
            baseDao.add(fieldSetEntity);
        }
    }
 
    /**
     * 同步人员
     */
    public void addEmployees(String clientUUID) throws SQLException, ClassNotFoundException {
 
        Connection conn = this.getJDBC();
        DataTableEntity personnelData;
        try {
            //获取岗位 修改/ 为> 方便适配我们数据表
            StringBuffer sql = new StringBuffer();
//            sql.append(" SELECT A.*,REPLACE(REPLACE(REPLACE(A.SU03, '/西宁市住房保障和房产管理局', ''),  ")
//                    .append(" '西宁市住房保障和房产管理局/局属各单位/','西宁市住房保障和房产管理局/'),'/','>') ASU03 FROM  ")
//                    .append(" FE_BASE5.SYS_USERS A WHERE A.SU39 is not null and A.SU35 is not null AND A.SU03 IS NOT NULL ");
            sql.append(" SELECT A.*,REPLACE(REPLACE(REPLACE(A.SU03, '/西宁市住房保障和房产管理局', ''),  ")
            .append(" '西宁市住房保障和房产管理局/局属各单位/','西宁市住房保障和房产管理局/'),'/','>') ASU03 FROM  ")
            .append(" FE_BASE5.SYS_USERS A WHERE SU39 IS NOT NULL");
            //人员数据
            personnelData = BaseDaoServiceImpl.getDataTable(conn, sql.toString(), new Object[]{});
        } catch (Exception e) {
            throw e;
        }
        DataManipulationUtils.close(null, null, conn);
        this.addEmployees(personnelData,clientUUID);
    }
 
    /**
     * 递归获取上级公司uuid
     * @param level_all 上级公司全称
     * @return 保存后返回保存后的 fse
     */
    public String getSuperiorCompanyUuid(String level_all){
        FieldSetEntity fieldSet = institutionMap.get(level_all);
        if(fieldSet == null){
            return null;
        }
        //上级为公司
        if("0".equals(fieldSet.getString("org_level_type"))){
            return fieldSet.getUUID();
        }else {
            Integer index = level_all.lastIndexOf(">");
            if(index == -1){
                return null;
            }
            level_all = level_all.substring(0,index);
            return this.getSuperiorCompanyUuid(level_all);
        }
    }
 
 
    /**
     * 保存公司
     * @param fse 公司fes
     * @param code_parent 公司上级code
     * @return 保存后返回保存后的 fse
     */
    public FieldSetEntity addCompany(FieldSetEntity fse, String code_parent, String org_level_uuid){
        FieldSetEntity levelsFs = new FieldSetEntity();
        levelsFs.setTableName("product_sys_org_levels");
        //部门名称,,
        levelsFs.setValue("org_level_name", fse.getString("sg01"));
 
        //公司段编码
        levelsFs.setValue("org_level_shortcode",  fse.getString("sg10"));
        //公司排序
        levelsFs.setValue("sequence", ++sort);
        //放入上级code  生成code
        levelsFs.setValue("org_level_code_parent", code_parent);
        //上级公司uuid
        levelsFs.setValue("org_level_uuid", org_level_uuid);
        ISystemOrgLevelsService service=(ISystemOrgLevelsService) getProxyInstance(systemOrgLevelsService);
//        levelsFs.setCodeFieldUpdateFlat("org_level_code", true);
        service.addCompany(levelsFs);
        return levelsFs;
    }
 
    /**
     * 保存部门
     * @param fse 公司fes
     * @param code_parent 公司上级code
     * @return 保存后返回保存后的 fse
     */
    public FieldSetEntity addDepartment(FieldSetEntity fse, String code_parent, String org_level_uuid){
        FieldSetEntity levelsFs = new FieldSetEntity();
        levelsFs.setTableName("product_sys_org_levels");
        //部门名称,,
        levelsFs.setValue("org_level_name", fse.getString("sg01"));
        //部门编码
        levelsFs.setValue("org_level_shortcode",  fse.getString("sg10"));
        //公司排序
        levelsFs.setValue("sequence", fse.getString("sg00"));
        //放入上级code  生成code
        levelsFs.setValue("org_level_code_parent", code_parent);
        //上级公司uuid
        levelsFs.setValue("org_level_uuid", org_level_uuid);
        ISystemOrgLevelsService service=(ISystemOrgLevelsService) getProxyInstance(systemOrgLevelsService);
//        levelsFs.setCodeFieldUpdateFlat("org_level_code", true);
        service.addDepartment(levelsFs);
        return levelsFs;
    }
    /**
     * 封装公司部门全称 Map
     */
    public void packInstitutionMap()throws BaseException {
      DataTableEntity dataTableEntity = baseDao.listTable("SELECT * FROM product_sys_org_levels WHERE org_level_code like ? ", new String[]{"%001%"});
      if(!BaseUtil.dataTableIsEmpty(dataTableEntity)) {
          for (int i = 0; i < dataTableEntity.getRows(); i++) {
              FieldSetEntity fieldSetEntity = dataTableEntity.getFieldSetEntity(i);
              String org_level_all = fieldSetEntity.getString("org_level_all");
              institutionMap.put(org_level_all, fieldSetEntity);
          }
      }else {
          throw new BaseException("未查询到单位部门数据", "未查询到单位部门数据");
      }
    }
 
    /**
     * 同步角色
     */
    public void synchronousRole(DataTableEntity data){
        for (int i = 0; i < data.getRows(); i++) {
            FieldSetEntity rolesFs = data.getFieldSetEntity(i);
            String sts02s = rolesFs.getString("sts02");
            FieldSetEntity levelsField = baseDao.getFieldSetEntityByFilter("product_sys_org_levels", " org_level_shortcode = ? ", new String[]{sts02s}, false);
            //有些角色关联的单位或部门已经被删除掉,但是角色还保留他的编码   直接跳过
            if(levelsField == null){
                continue;
            }
            FieldSetEntity lxRoleFs = new FieldSetEntity();
            lxRoleFs.setTableName("product_sys_role");
            lxRoleFs.setValue("org_level_uuid",levelsField.getUUID());
            lxRoleFs.setValue("role_name", rolesFs.getString("spt01"));
            lxRoleFs.setValue("role_description", rolesFs.getString("spt02"));
            lxRoleFs.setValue("is_used", 1);
            lxRoleFs.setValue("sequence", rolesFs.getInteger("spt00"));
            this.userAndTime(lxRoleFs);
            String role_uuid = baseDao.add(lxRoleFs);
 
            //该角色初始化权限
            this.packageButton(role_uuid);
        }
    }
 
    /**
     * 添加用户和员工
     */
    public void addEmployees(DataTableEntity data,String clientUUID){
        //fe 人员id 对应  userid
        JSONObject idUserMap = new JSONObject();
        //获取客户uuid
        FieldSetEntity fieldSetEntity = baseDao.getFieldSetEntityByFilter("product_sys_org_levels", " org_level_code = ? ", new String[]{"001"}, false);
        String client_uuid = fieldSetEntity.getString("client_uuid");
 
        Map<String, FieldSetEntity> staffsMap = Maps.newHashMap();
        for (int i = 0; i < data.getRows(); i++) {
            FieldSetEntity userFs = data.getFieldSetEntity(i);
            FieldSetEntity usersFs = new FieldSetEntity();
            //创建 user 数据
            usersFs.setTableName("product_sys_users");
            //用户名
            usersFs.setValue("user_name", userFs.getString("su02"));
            //描述
            usersFs.setValue("user_account", userFs.getString("su01"));
            //邮箱
            usersFs.setValue("user_primary_email", userFs.getString("su11"));
            //性别转换
            String su16 = userFs.getString("su16");
            String sex = null;
            if (su16 != null) {
                sex = su16.equals("男") ? "0" : "1";
            }
            usersFs.setValue("gender", sex);
            //用户电话
            usersFs.setValue("user_mobile_number", userFs.getString("su10"));
            //内线电话
            usersFs.setValue("inside_phone", userFs.getString("su13"));
            //地址
            usersFs.setValue("contact_address", userFs.getString("su18"));
            //初始化用户密码
            usersFs.setValue("user_pwd", userService.createPassWord(userFs.getString("su01"), "123"));
            //是否是管理员 0:否 1:是
            usersFs.setValue("is_manager", 0);
            //办公电话
            usersFs.setValue("office_phone", userFs.getString("su09"));
            this.userAndTime(usersFs);
            //状态  0:禁用   1:正常
            usersFs.setValue("status",  userFs.getString("su08"));
            //签名
            String su23 = userFs.getString("su23");
            if (!BaseUtil.strIsNull(su23)) {
                    usersFs.setValue("user_signature", this.signatureAndThumbnail(su23, clientUUID,"user_signature"));
            }
            //头像
            String su28 = userFs.getString("su28");
            if (!BaseUtil.strIsNull(su28)) {
                usersFs.setValue("thumbnail_img", this.signatureAndThumbnail(su28, clientUUID,"thumbnail_img"));
            }
 
            String usersUUID = baseDao.add(usersFs);
            FieldSetEntity users = baseDao.getFieldSetEntity("product_sys_users", usersUUID, false);
            //fe用户id  关联系统表"product_sys_users)user_id
            idUserMap.put(userFs.getString("su00"), users.getString("user_id"));
 
            if (BaseUtil.strIsNull(userFs.getString("su03")) || BaseUtil.strIsNull(userFs.getString("su35")) || BaseUtil.strIsNull(userFs.getString("su39"))) {
                continue;
            }
            
            FieldSetEntity staffsFs = new FieldSetEntity();
            //员工表
            staffsFs.setTableName("product_sys_staffs");
            //用户表id
            staffsFs.setValue("user_id", users.getString("user_id"));
            //显示名称
            staffsFs.setValue("show_name", userFs.getString("su02"));
            //员工名
            staffsFs.setValue("given_name", userFs.getString("su02"));
            //员工姓
            staffsFs.setValue("family_name", userFs.getString("su02"));
            //邮箱
            staffsFs.setValue("email_address", userFs.getString("su11"));
            //移动电话
            staffsFs.setValue("mobile_phone", userFs.getString("su10"));
            //办公电话
            staffsFs.setValue("office_telephone", userFs.getString("su09"));
 
            //员工性别
            staffsFs.setValue("sex",  sex);
            //员工邮箱
            String su11 = userFs.getString("su11");
            //邮箱为空先覆1
            if(BaseUtil.strIsNull(su11)){
                su11 = "1";
            }
            staffsFs.setValue("staff_email", su11);
            //状态:0准备入职   1试用   2准备转正   3在职   4停职   5准备离职   6离职   7退休
            staffsFs.setValue("staff_status", 3);
 
            staffsFs.setValue("client_uuid", client_uuid);
            //重新组装后的组织全称
            FieldSetEntity fieldSet = institutionMap.get(userFs.getString("asu03"));
            String uuid = this.getSuperiorCompanyUuid(userFs.getString("asu03"));
            //公司uuid
            staffsFs.setValue("org_level_uuid", uuid);
            //部门uuid
            staffsFs.setValue("dept_uuid", fieldSet.getUUID());
            
            if (null == userFs.getString("su34")) {
                //岗位uuid
                staffsFs.setValue("job_post_uuid", 1);
                //岗位等级uuid
                staffsFs.setValue("job_post_grade_uuid",1);
            } else {
                //通过岗位id查询岗位
                String su34 = userFs.getString("su34");
                FieldSetEntity fsePosts = baseDao.getFieldSetEntityByFilter("product_sys_job_posts", " sequence = ? ", new Integer[]{Integer.parseInt(su34)}, false);
                if(fsePosts != null) {
                    staffsFs.setValue("job_post_uuid", fsePosts.getUUID());
                    staffsFs.setValue("job_post_grade_uuid", fsePosts.getString("job_post_grades_uuid"));
                }else {
                    throw new BaseException("未查询到岗位","未查询到岗位");
                }
            }
            //su35关联权限id,  关联多个逗号分隔
            String su35 = userFs.getString("su35");
            String[] su35s = null;
            if(!BaseUtil.strIsNull(su35)){
                su35s = su35.split(",");
                for (int j = 0; j < su35s.length; j++) {
                  FieldSetEntity fse = baseDao.getFieldSetEntityByFilter("product_sys_role", " sequence = ? ", new Integer[]{Integer.parseInt(su35s[j])}, false);
                    su35s[j] = fse.getUUID();
                }
            }
            //直属领导
            String su40 = userFs.getString("su40");
            //为空就放空
            if(BaseUtil.strIsNull(su40)){
                su40 = "";
            }else {
                //多个直属领导   就取第一个
                if(su40.contains(",")){
                    su40 = su40.substring(0,su40.indexOf(","));
                }
            }
            staffsFs.setValue("direct_leader_code",su40);
            if(su35s != null) {
                staffsFs.setValue("role_uuids", StringUtils.join(su35s, ","));
            }
            //员工上下级编码
            staffsFs.setValue("leader_tricode", codeService.createFixCode(CmnConst.PRODUCT_SYS_STAFFS, CmnConst.LEADER_TRICODE, ""));
            //员工编码  员工原本id   存为编码
            staffsFs.setValue("tricode",codeService.createFixCode(CmnConst.PRODUCT_SYS_STAFFS, CmnConst.TRICODE, fieldSet.getString("org_level_code")));
            String su00 = userFs.getString("su00");
            staffsFs.setValue("sequence", su00);
            staffsFs.setValue("remark", su00);
            this.userAndTime(staffsFs);
            baseDao.add(staffsFs);
            staffsMap.put(su00, staffsFs);
        }
        //sql修改直属领导
        baseDao.executeUpdate(" UPDATE product_sys_staffs a INNER JOIN product_sys_staffs b ON a.remark = b.direct_leader_code SET b.direct_leader_code = a.tricode ");
        //循环同步直属领导,  若有两个直属领导  只取第一个
//        for(String su00 : staffsMap.keySet()){
//            FieldSetEntity staffsFs = staffsMap.get(su00);
//            //获取直属领导
//            String direct_leader_code = staffsFs.getString("direct_leader_code");
//            if(!BaseUtil.strIsNull(direct_leader_code)){
//                FieldSetEntity staffs1;
//                if(direct_leader_code.contains(",")){
//                  String su001 = direct_leader_code.substring(0,direct_leader_code.indexOf(","));
//                    staffs1 = staffsMap.get(su001);
//                }else {
//                    staffs1 = staffsMap.get(direct_leader_code);
//                }
//                if(staffs1 != null){
//                  String tricode = staffs1.getString("tricode");
//                  if(!BaseUtil.strIsNull(tricode)){
//                      staffsFs.setValue("direct_leader_code",tricode);
//                      baseDao.update(staffsFs);
//                  }
//                }else {
//                    staffsFs.setValue("direct_leader_code","");
//                    baseDao.update(staffsFs);
//                }
//            }
//        }
    }
 
    public String signatureAndThumbnail(String su,String clientUUID, String field){
        try {
            String[] path = su.split("=");
            String filePath = path[1];
            String fileName = StringUtils.isEmpty(filePath) ? "" : filePath.substring(filePath.lastIndexOf("/") + 1);
            String newPath = this.TSPath + File.separator + fileName;
            File isField = new File(newPath);
            //如果已经有该文件   改变文件目录
            Integer fileNum = 0;
            while (isField.exists()) {
                fileNum++;
                newPath = this.TSPath + fileNum + File.separator + fileName;
                isField = new File(newPath);
            }
            //复制到临时目录下
            if (this.copyFile(filePath, newPath)) {
                RequestParameterEntity rpe = new RequestParameterEntity();
                Map<String, File> fileMap = Maps.newHashMap();
                //通过路径获取File
                File file = new File(newPath);
                //文件名  文件file
                fileMap.put(fileName, file);
                FieldSetEntity fieldSet = new FieldSetEntity();
                FieldMetaEntity f = new FieldMetaEntity();
                f.setTableName(new String[]{"product_sys_users"});
                fieldSet.setMeta(f);
                fieldSet.setValue(field, fileName);
                fieldSet.setValue("~field_name~", field);
                //放入客户uuid
                fieldSet.setValue("client_uuid", clientUUID);
                rpe.setFiles(fileMap);
                rpe.setFormData(fieldSet);
                try {
                    FieldSetEntity fileFse = fileManagerService.uploadFile(rpe);
                    return fileFse.getString(field);
                } catch (Exception e) {
                    e.getStackTrace();
                    SpringMVCContextHolder.getSystemLogger().error(e);
                }
            }
        }catch (Exception e){
            e.getStackTrace();
        }
        return null;
    }
 
    /**
     * 添加岗位
     */
    public void addPost(DataTableEntity data){
        DataTableEntity dataTableEntity = new DataTableEntity();
        dataTableEntity.getMeta().setTableName(new String[]{"product_sys_job_posts"});
        for (int i = 0; i < data.getRows(); i++) {
            FieldSetEntity fieldSetEntity = data.getFieldSetEntity(i);
            FieldSetEntity field = new FieldSetEntity();
            field.setTableName("product_sys_job_posts");
            field.setValue("is_used", 1);
            field.setValue("job_post_name", fieldSetEntity.getString("sr01"));
            field.setValue("job_post_description", fieldSetEntity.getString("sr02"));
            //通过全称获取单位和部门uuid
            String org_level_all = fieldSetEntity.getString("asr03");
            FieldSetEntity fieldSetEntity1 = institutionMap.get(org_level_all);
            //公司uuid
            String org_level_uuid = this.getSuperiorCompanyUuid(org_level_all);
            field.setValue("org_level_uuid",org_level_uuid);
            //机构类型  0 公司  1部门
            String orgLevelType = fieldSetEntity1.getString("org_level_type");
            //查询岗位等级
            String sr15 = fieldSetEntity.getString("sr15");
            FieldSetEntity fieldSet = baseDao.getFieldSetEntityByFilter("product_sys_job_post_grades", " org_level_uuid = ? and  job_grade_class = ? ", new String[]{org_level_uuid,sr15},false);
            //岗位等级
            String postGradesUuid = fieldSet.getUUID();
            field.setValue("job_post_grades_uuid", postGradesUuid);
            //排序暂时存岗位id  方便人员查询到岗位id
            Integer sequence = fieldSetEntity.getInteger("sr00");
            field.setValue("sequence",sequence);
            this.userAndTime(field);
            String org_uuid = fieldSetEntity1.getUUID();
            String code = fieldSetEntity1.getString("org_level_code");
            //0为公司  若为公司就创建多个相同岗位来关联公司下所有部门
            if("0".equals(orgLevelType)){
              DataTableEntity dataTable = baseDao.listTable("product_sys_org_levels", " org_level_type = 1 and org_level_uuid = ? ", new String[]{org_uuid});
              if(!BaseUtil.dataTableIsEmpty(dataTable)) {
                  for (int j = 0; j < dataTable.getRows(); j++) {
                      field.setValue("dept_uuid",dataTable.getString(j, "uuid"));
                      field.remove("uuid");
                      //通过新增方法添加岗位
                      String uuid = baseDao.add(field);
                      //添加岗位与岗位等级关系映射数据表
                      FieldSetEntity postsAndClass = new FieldSetEntity();
                      postsAndClass.setTableName("product_sys_job_posts_grades_mapping");
                      //岗位等级uuid
                      postsAndClass.setValue("job_grade_uuid", postGradesUuid);
                      //岗位uuid
                      postsAndClass.setValue("job_post_uuid", uuid);
                      this.userAndTime(postsAndClass);
                      baseDao.add(postsAndClass);
                  }
              }else {
                  //单位下若没有部门  创建一个虚拟部门
                  FieldSetEntity departmentFse = new FieldSetEntity();
                  departmentFse.setTableName("product_sys_org_levels");
                  //部门名称
                  departmentFse.setValue("sg01", fieldSetEntity1.getString("org_level_name") + "下部门");
                  //部门编码
                  departmentFse.setValue("sg10", fieldSetEntity1.getString("org_level_shortcode") + "01");
                  //排序
                  departmentFse.setValue("sg00", fieldSetEntity1.getString("sequence") + "01");
                  //保存后的部门
                  FieldSetEntity newDeptFse = this.addDepartment(departmentFse,code,org_uuid);
                  //放入部门uuid
                  field.setValue("dept_uuid",newDeptFse.getUUID());
                  //通过新增方法添加岗位
                  String uuid = baseDao.add(field);
                  //添加岗位与岗位等级关系映射数据表
                  FieldSetEntity postsAndClass = new FieldSetEntity();
                  postsAndClass.setTableName("product_sys_job_posts_grades_mapping");
                  //岗位等级uuid
                  postsAndClass.setValue("job_grade_uuid", postGradesUuid);
                  //岗位uuid
                  postsAndClass.setValue("job_post_uuid", uuid);
                  this.userAndTime(postsAndClass);
                  baseDao.add(postsAndClass);
              }
              //1为部门
            }else{
                field.setValue("dept_uuid",org_uuid);
                //通过新增方法添加岗位
                String uuid = baseDao.add(field);
                //添加岗位与岗位等级关系映射数据表
                FieldSetEntity postsAndClass = new FieldSetEntity();
                postsAndClass.setTableName("product_sys_job_posts_grades_mapping");
                //岗位等级uuid
                postsAndClass.setValue("job_grade_uuid", postGradesUuid);
                //岗位uuid
                postsAndClass.setValue("job_post_uuid", uuid);
                this.userAndTime(postsAndClass);
                baseDao.add(postsAndClass);
            }
        }
    }
 
    /**
     * 添加创建人和创建时间
     * @param fieldSetEntity
     */
    public void userAndTime(FieldSetEntity fieldSetEntity){
        fieldSetEntity.setValue("created_by",SpringMVCContextHolder.getCurrentUserId());
        fieldSetEntity.setValue("created_utc_datetime",new Date());
    }
    /**
     * 添加岗位等级
     */
    public void postGrades(DataTableEntity data){
        //公司uuid 岗位层级集
        Map<String,String> postHierarchyMap = Maps.newHashMap();
        //通过公司uuid来划分岗位等级
        for (int i = 0; i < data.getRows(); i++) {
           FieldSetEntity fieldSetEntity = data.getFieldSetEntity(i);
            FieldSetEntity field = new FieldSetEntity();
            field.setTableName("product_sys_job_post_grades");
            //岗位层级  越小等级越大
            String sr15 = fieldSetEntity.getString("sr15");
            //转换后部门或公司全称
            String dcName = fieldSetEntity.getString("asr03");
            //获取公司的uuid
            String companyUuid = this.getSuperiorCompanyUuid(dcName);
            String value = postHierarchyMap.get(companyUuid);
            if(!BaseUtil.strIsNull(value)){
                if(value.contains(sr15)) {
                    continue;
                }else {
                    postHierarchyMap.put(companyUuid, value+","+sr15);
                }
            }else {
                postHierarchyMap.put(companyUuid, sr15);
            }
            FieldSetEntity levelsSet = baseDao.getFieldSetEntity("product_sys_org_levels",companyUuid,false);
            //公司名称
            String levelName = levelsSet.getString("org_level_name");
            //上级公司uuid
            field.setValue("org_level_uuid",companyUuid);
            //岗位等级
            field.setValue("job_grade_class", sr15);
            field.setValue("is_used", 1);
            //名称
            field.setValue("job_grade_name",sr15+"级岗位");
            //级别短编码
            field.setValue("job_grade_shortcode", sr15);
            //说明
            field.setValue("remark", levelName+"下的"+sr15+"级岗位");
            field.setValue("sequence", sr15);
            this.userAndTime(field);
            baseDao.add(field);
        }
    }
    /** 复制单个文件
     * @param oldPath String 原文件路径 如:c:/fqf.txt
     * @param newPath String 复制后路径 如:f:/fqf.txt
     * @return boolean
     */
    public Boolean copyFile(String oldPath, String newPath) {
        Boolean status = false;
        try {
            BufferedInputStream in = FileUtil.getInputStream(oldPath);
            BufferedOutputStream out = FileUtil.getOutputStream(newPath);
            IoUtil.copy(in, out, IoUtil.DEFAULT_BUFFER_SIZE);
            status = true;
            out.close();
            in.close();
        }catch (Exception e){
            e.getStackTrace();
        }finally {
            return status;
        }
    }
 
    /** 删除单个文件
     * @param   fileName    被删除文件的文件名
     * @return 单个文件删除成功返回true,否则返回false
     */
    public Boolean deleteFile(String fileName){
        File file = new File(fileName);
        if(file.isFile()){
            file.delete();
            System.out.println("删除单个文件"+fileName+"成功!");
            return true;
        }else{
            System.out.println("删除单个文件"+fileName+"失败!");
            return false;
        }
    }
 
    public static void main(String[] args) {
//        File file = new File("D:\\filePackage\\西宁市住房保障和房屋管理局需求整理V1.0.docx");
//        File file2 = new File("D:\\filePackage\\西宁市住房保障和房屋管理.docx");
//        System.out.println(file.exists());
//        System.out.println(file2.exists());
//        FeDataDSService feDataDSService = new FeDataDSService();
//        feDataDSService.copyFile("D:\\OA\\FEGOV\\Media\\2021\\12\\15\\20211215401901\\1`FE#ENC#DA126AF35BB8E57F55C2429BDF7DC7240DF6CC6E227B0B8E", "D:\\filePackage\\????????????????????????.doc");
//        feDataDSService.getFilesFolder("D:\\OA\\FEGOV\\Media\\2021\\12\\15\\20211215401901");
    }
 
    /**
     * 获取文件名称  最新修改时间 map
     * @param path
     * @return
     */
    public Map<String, String> getFilesFolder(String path){
        File file = new File(path);        //获取其file对象
        File[] fs = file.listFiles();
        if(fs == null){
            logger.info("未找到附件直接返回null");
            return null;
        }
        Map<String, String> fileTimeName = Maps.newHashMap();
        for(File f:fs)
        {
            if(f.isFile())
            {
                String fileName = f.toString().replace(path+"\\","");
                fileTimeName.put(this.set_fileInfo(f.toString()),fileName);
            }
        }
        return fileTimeName;
    }
 
    /**
     * 获取文件最近修改时间
     * @param file_name 文件全路径
     * @return
     */
    public String set_fileInfo(String file_name)
    {
        Path path = Paths.get(file_name);
        BasicFileAttributeView basicview = Files.getFileAttributeView(path, BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
        BasicFileAttributes attr;
        String time = null;
        try
        {
 
            attr = basicview.readAttributes();
            //创建时间
            Date CreateTimeDate= new Date(attr.creationTime().toMillis());
            //上次修改时间 *
            Date lastmodfiyTimeDate=new Date(attr.lastModifiedTime().toMillis());
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            time = df.format(lastmodfiyTimeDate);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return time;
    }
 
    public void clearJobList(){
      DataTableEntity dataTableEntity = baseDao.listTable("product_sys_flow_node","  default_posts is not null AND default_posts != '' ",new String[]{});
        for (int i = 0; i < dataTableEntity.getRows(); i++) {
           FieldSetEntity fse = dataTableEntity.getFieldSetEntity(i);
           String default_posts = fse.getString("default_posts");
           if(!BaseUtil.strIsNull(default_posts)){
               String[] postUuids = default_posts.split(",");
               Set<String> postSet = Sets.newHashSet();
//             Set<String> postSet = Arrays.stream(postUuids).collect(Collectors.toSet());
               for (int j = 0; j < postUuids.length; j++) {
                 DataTableEntity staffsData = baseDao.listTable("product_sys_staffs","  job_post_uuid = ? ",new String[]{postUuids[j]});
                 //有人就保留岗位uuid
                   if(!BaseUtil.dataTableIsEmpty(staffsData)){
                       postSet.add(postUuids[j]);
                   }
               }
               if(postSet.size() > 0){
                   fse.setValue("default_posts", StringUtils.join(postSet, ","));
               }else {
                   fse.setValue("default_posts", null);
               }
               baseDao.update(fse);
           }
        }
        //清空多余的岗位数据
        baseDao.executeUpdate("DELETE FROM product_sys_job_posts WHERE uuid not in (SELECT job_post_uuid FROM product_sys_staffs);");
        //岗位关联
        baseDao.executeUpdate("DELETE FROM product_sys_job_posts_grades_mapping WHERE job_post_uuid not in (SELECT job_post_uuid FROM product_sys_staffs);");
    }
 
}