yangys
2024-04-04 ed4a5236bab800094be4a8378f5098eebe3de6ac
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
package com.qianwen.smartman.modules.sync.service.impl;
 
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
 
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
 
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dingtalkcontact_1_0.models.GetUserHeaders;
import com.aliyun.dingtalkcontact_1_0.models.GetUserResponseBody;
import com.aliyun.dingtalkoauth2_1_0.Client;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.request.OapiAuthScopesRequest;
import com.dingtalk.api.request.OapiRoleListRequest;
import com.dingtalk.api.request.OapiRoleSimplelistRequest;
import com.dingtalk.api.request.OapiSnsGetuserinfoBycodeRequest;
import com.dingtalk.api.request.OapiUserGetbyunionidRequest;
import com.dingtalk.api.request.OapiV2DepartmentGetRequest;
import com.dingtalk.api.request.OapiV2DepartmentListsubRequest;
import com.dingtalk.api.request.OapiV2UserGetRequest;
import com.dingtalk.api.request.OapiV2UserListRequest;
import com.dingtalk.api.response.OapiAuthScopesResponse;
import com.dingtalk.api.response.OapiRoleListResponse;
import com.dingtalk.api.response.OapiRoleSimplelistResponse;
import com.dingtalk.api.response.OapiSnsGetuserinfoBycodeResponse;
import com.dingtalk.api.response.OapiUserGetbyunionidResponse;
import com.dingtalk.api.response.OapiV2DepartmentGetResponse;
import com.dingtalk.api.response.OapiV2DepartmentListsubResponse;
import com.dingtalk.api.response.OapiV2UserGetResponse;
import com.dingtalk.api.response.OapiV2UserListResponse;
import com.qianwen.core.log.exception.ServiceException;
import com.qianwen.core.tool.utils.Func;
import com.qianwen.core.tool.utils.StringUtil;
import com.qianwen.smartman.common.constant.CommonConstant;
import com.qianwen.smartman.common.constant.CommonGroupConstant;
import com.qianwen.smartman.common.enums.CommonGroupTypeEnum;
import com.qianwen.smartman.common.utils.MessageUtils;
import com.qianwen.smartman.modules.cps.entity.CommonGroup;
import com.qianwen.smartman.modules.cps.entity.CommonGroupOfItem;
import com.qianwen.smartman.modules.cps.entity.Employee;
import com.qianwen.smartman.modules.cps.entity.EmployeePost;
import com.qianwen.smartman.modules.cps.mapper.CommonGroupMapper;
import com.qianwen.smartman.modules.cps.service.ICommonGroupOfItemService;
import com.qianwen.smartman.modules.cps.service.ICommonGroupService;
import com.qianwen.smartman.modules.cps.service.IEmployeePostService;
import com.qianwen.smartman.modules.cps.service.IEmployeeService;
import com.qianwen.smartman.modules.sync.constant.DingConstant;
import com.qianwen.smartman.modules.sync.constant.OuterAppConfigConstant;
import com.qianwen.smartman.modules.sync.constant.QyWechatConstant;
import com.qianwen.smartman.modules.sync.entity.DingOriDept;
import com.qianwen.smartman.modules.sync.entity.DingOriUser;
import com.qianwen.smartman.modules.sync.entity.OuterAppConfig;
import com.qianwen.smartman.modules.sync.service.IDingEventService;
import com.qianwen.smartman.modules.sync.service.IDingSyncService;
import com.qianwen.smartman.modules.sync.service.IOuterAppConfigService;
import com.qianwen.smartman.modules.sync.vo.SyncResultVO;
import com.qianwen.smartman.modules.system.entity.Post;
import com.qianwen.smartman.modules.system.entity.UserOauth;
import com.qianwen.smartman.modules.system.mapper.PostMapper;
import com.qianwen.smartman.modules.system.service.IParamService;
import com.qianwen.smartman.modules.system.service.IPostService;
import com.qianwen.smartman.modules.system.service.IUserOauthService;
import com.taobao.api.TaobaoRequest;
 
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
 
@Service
/* loaded from: blade-api.jar:BOOT-INF/classes/org/springblade/modules/sync/service/impl/DingSyncServiceImpl.class */
public class DingSyncServiceImpl implements IDingSyncService {
    private static final Logger log = LoggerFactory.getLogger(DingSyncServiceImpl.class);
    private final IUserOauthService userOauthService;
    private final IEmployeeService employeeService;
    private final IPostService postService;
    private final ICommonGroupService groupService;
    private final CommonGroupMapper commonGroupMapper;
    private final IDingEventService dingEventService;
    private final ICommonGroupOfItemService commonGroupOfItemService;
    private Map<String, Set<String>> userPostRelationMap;
    private final DataSourceTransactionManager dataSourceTransactionManager;
    private final PostMapper postMapper;
    private final IOuterAppConfigService outerAppConfigService;
    private final IParamService paramService;
    private final IEmployeePostService employeePostService;
 
 
    public DingSyncServiceImpl(final IUserOauthService userOauthService, final IEmployeeService employeeService, final IPostService postService, final ICommonGroupService groupService, final CommonGroupMapper commonGroupMapper, final IDingEventService dingEventService, final ICommonGroupOfItemService commonGroupOfItemService, final Map<String, Set<String>> userPostRelationMap, final DataSourceTransactionManager dataSourceTransactionManager, final PostMapper postMapper, final IOuterAppConfigService outerAppConfigService, final IParamService paramService, final IEmployeePostService employeePostService) {
        this.userOauthService = userOauthService;
        this.employeeService = employeeService;
        this.postService = postService;
        this.groupService = groupService;
        this.commonGroupMapper = commonGroupMapper;
        this.dingEventService = dingEventService;
        this.commonGroupOfItemService = commonGroupOfItemService;
        this.userPostRelationMap = userPostRelationMap;
        this.dataSourceTransactionManager = dataSourceTransactionManager;
        this.postMapper = postMapper;
        this.outerAppConfigService = outerAppConfigService;
        this.paramService = paramService;
        this.employeePostService = employeePostService;
    }
 
    @Override // org.springblade.modules.sync.service.IDingSyncService
    public SyncResultVO syncImmediately() {
        
        OuterAppConfig dingAppConfig = this.outerAppConfigService.getAppConfig(OuterAppConfigConstant.DING);
        String appKey = dingAppConfig.getDingAppKey();
        String appSecret = dingAppConfig.getDingAppSecret();
        DefaultTransactionDefinition transDefinition = new DefaultTransactionDefinition();
        
        List<Post> posts = new ArrayList<>();
        List<DingOriDept> oriGroups = new ArrayList<>();
        List<DingOriUser> oriUsers = new ArrayList<>();
        
        
        
        TransactionStatus transStatus = this.dataSourceTransactionManager.getTransaction(transDefinition);
        SyncResultVO syncResultVO = new SyncResultVO();
        try {
            getRoles(appKey, appSecret, posts, syncResultVO);
            
            List<Long> permissionGroups = getPermissionGroup(appKey, appSecret, syncResultVO);
            if (Func.isEmpty(permissionGroups)) {
                syncResultVO.setGroupResult(false);
                syncResultVO.setUserReason("未获取到权限范围内的组织机构!");
            }
            for (Long permissionGroup : permissionGroups) {
                SyncEmployee(permissionGroup, appKey, appSecret, oriUsers, syncResultVO);
                recursionGetGroup(permissionGroup, appKey, appSecret, oriGroups, oriUsers, syncResultVO, permissionGroups);
            }
           
            if (!syncResultVO.getGroupResult().booleanValue() || !syncResultVO.getPostResult().booleanValue() || !syncResultVO.getUserResult().booleanValue()) {
                this.userPostRelationMap.clear();
                return syncResultVO;
            }
            List<Employee> employees = new ArrayList<>();
            List<EmployeePost> employeePosts = new ArrayList<>();
            List<UserOauth> userOauths = new ArrayList<>();
            List<CommonGroupOfItem> commonGroupOfItems = new ArrayList<>();
            List<Employee> updateEmployees = new ArrayList<>();
            Boolean flag = true;
            try {
                this.postMapper.removePost();
                this.postService.saveBatch(posts);
            } catch (Exception e2) {
                flag = false;
                syncResultVO.setPostResult(false);
                syncResultVO.setPostReason("同步钉钉角色数据库部分报错:" + e2.toString());
            }
            try {
                this.commonGroupMapper.removeOrg();
                insertGroups(permissionGroups, oriGroups, appKey, appSecret);
            } catch (Exception e3) {
                flag = false;
                syncResultVO.setGroupResult(false);
                syncResultVO.setGroupReason("同步钉钉部门数据库部分报错:" + e3.toString());
            }
            try {
                this.userOauthService.remove(Wrappers.lambdaQuery());
                this.commonGroupMapper.removeOrgContact();
                this.employeePostService.remove(Wrappers.lambdaQuery());
                handleAuthAndEmployee(oriUsers, employees, userOauths, commonGroupOfItems, employeePosts, updateEmployees);
                this.employeeService.remove(Wrappers.<Employee>lambdaQuery().notIn(Func.isNotEmpty(updateEmployees), Employee::getId, updateEmployees.stream().map(Employee::getId).collect(Collectors.toList())));
                /*
                this.employeeService.remove(Wrappers.lambdaQuery().notIn(Func.isNotEmpty(updateEmployees), (v0) -> {
                    return v0.getId();
                }, (Collection) updateEmployees.stream().map((v0) -> {
                    return v0.getId();
                }).collect(Collectors.toList())));*/
                this.employeeService.saveBatch(employees);
                this.employeeService.updateBatchById(updateEmployees);
                this.userOauthService.saveOrUpdateBatch(userOauths);
                this.commonGroupOfItemService.saveBatch(commonGroupOfItems);
                if (Func.isNotEmpty(employeePosts)) {
                    this.employeePostService.saveBatch(employeePosts);
                }
            } catch (Exception e4) {
                flag = false;
                syncResultVO.setUserResult(false);
                syncResultVO.setUserReason("同步钉钉员工数据库部分报错:" + e4.toString());
            }
            if (syncResultVO.getGroupResult().booleanValue() && syncResultVO.getPostResult().booleanValue() && syncResultVO.getUserResult().booleanValue()) {
                this.outerAppConfigService.update(Wrappers.<OuterAppConfig>lambdaUpdate().eq(OuterAppConfig::getAppType, OuterAppConfigConstant.DING)
                        .set(OuterAppConfig::getLastSyncTime, new Date())); 
                /*
                this.outerAppConfigService.update((Wrapper) ((LambdaUpdateWrapper) Wrappers.lambdaUpdate().eq((v0) -> {
                    return v0.getAppType();
                }, OuterAppConfigConstant.DING)).set((v0) -> {
                    return v0.getLastSyncTime();
                }, new Date()));*/
            }
            if (flag.booleanValue()) {
                this.dataSourceTransactionManager.commit(transStatus);
            } else {
                this.dataSourceTransactionManager.rollback(transStatus);
            }
            this.userPostRelationMap.clear();
            return syncResultVO;
        } catch (Exception th) {
            log.error("同步钉钉通讯录异常,异常信息为:", th);
            this.dataSourceTransactionManager.rollback(transStatus);
            
            //throw th;
        }finally {
            this.userPostRelationMap.clear();
        }
        
        return syncResultVO;
    }
 
    private List<Long> getPermissionGroup(String appKey, String appSecret, SyncResultVO syncResultVO) {
        try {
            DefaultDingTalkClient defaultDingTalkClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/auth/scopes");
            OapiAuthScopesRequest req = new OapiAuthScopesRequest();
            req.setHttpMethod("GET");
            OapiAuthScopesResponse rsp = defaultDingTalkClient.execute(req, this.dingEventService.getDingAccessToken(appKey, appSecret));
            JSONObject jsonObject = JSONObject.parseObject(rsp.getBody());
            if (jsonObject.getInteger(QyWechatConstant.ERROR_CODE_KEY).equals(DingConstant.SUCCESS)) {
                JSONObject authInfo = jsonObject.getJSONObject("auth_org_scopes");
                JSONArray deptArray = authInfo.getJSONArray("authed_dept");
                return deptArray.toJavaList(Long.class);
            }
            syncResultVO.setUserResult(false);
            syncResultVO.setUserReason("获取权限下部门报错,结果为:" + jsonObject + "---------参数为:" + req);
            return null;
        } catch (Exception e) {
            syncResultVO.setGroupResult(false);
            syncResultVO.setUserReason("获取权限下部门报错:" + e.toString());
            return null;
        }
    }
 
    @Override // org.springblade.modules.sync.service.IDingSyncService
    @Transactional
    public Boolean scanCodeBind(String code, String state) {
        OuterAppConfig outerAppConfig = this.outerAppConfigService.getAppConfig(OuterAppConfigConstant.DING);
        String appKey = outerAppConfig.getDingAppKey();
        String appSecret = outerAppConfig.getDingAppSecret();
        JSONObject userObject = null;
        try {
            String userId = getUserIdByCode(code, appKey, appSecret);
            if (Func.isNotEmpty(userId)) {
                userObject = getDetailByUserId(userId, appKey, appSecret);
            }
            if (Func.isNotEmpty(userId) && Func.isNotEmpty(userObject)) {
                UserOauth userOauth = this.userOauthService.getOne(Wrappers.<UserOauth>lambdaQuery().eq(UserOauth::getUuid, userId), false);
                /*
                UserOauth userOauth = (UserOauth) this.userOauthService.getOne((Wrapper) Wrappers.lambdaQuery().eq((v0) -> {
                    return v0.getUuid();
                }, userId), false);*/
                if (Func.isEmpty(userOauth)) {
                    throw new ServiceException(MessageUtils.message("sys.outer.user.not.exist", new Object[0]));
                }
                if (Func.isEmpty(userOauth.getUserId())) {
                    relationScanUser(userObject, userOauth, state);
                    this.userOauthService.updateById(userOauth);
                    return true;
                }
                throw new ServiceException(MessageUtils.message("cps.employee.already.bind", new Object[0]));
            }
            throw new ServiceException(MessageUtils.message("sys.outer.user.not.exist", new Object[0]));
        } catch (Exception e) {
            log.error("扫码绑定员工异常,异常信息为:", e);
            return false;
        }
    }
 
    @Override // org.springblade.modules.sync.service.IDingSyncService
    public Boolean unbind(Long id, String source) {
        UserOauth userOauth = this.userOauthService.getOne(Wrappers.<UserOauth>lambdaQuery().eq(UserOauth::getUserId, id).eq(UserOauth::getSource, source));
        /*
        UserOauth userOauth = (UserOauth) this.userOauthService.getOne((Wrapper) ((LambdaQueryWrapper) Wrappers.lambdaQuery().eq((v0) -> {
            return v0.getUserId();
        }, id)).eq((v0) -> {
            return v0.getSource();
        }, source));*/
        if (Func.isEmpty(userOauth)) {
            throw new ServiceException(MessageUtils.message("cps.employee.not.band", new Object[0]));
        }
        
        return Boolean.valueOf(this.userOauthService.update(Wrappers.<UserOauth>lambdaUpdate()
                .set(UserOauth::getUserId, null).eq(UserOauth::getUserId, id).eq(UserOauth::getSource, source)));
        /*
        return Boolean.valueOf(this.userOauthService.update((Wrapper) ((LambdaUpdateWrapper) ((LambdaUpdateWrapper) Wrappers.lambdaUpdate().set((v0) -> {
            return v0.getUserId();
        }, (Object) null)).eq((v0) -> {
            return v0.getUserId();
        }, id)).eq((v0) -> {
            return v0.getSource();
        }, source)));*/
    }
 
    @Override // org.springblade.modules.sync.service.IDingSyncService
    public String getDingUserId(String code) {
        try {
            OuterAppConfig outerAppConfig = this.outerAppConfigService.getAppConfig(OuterAppConfigConstant.DING);
            String appKey = outerAppConfig.getDingAppKey();
            String appSecret = outerAppConfig.getDingAppSecret();
            String userId = getUserIdByCode(code, appKey, appSecret);
            return userId;
        } catch (Exception e) {
            log.error("获取钉钉userId异常,异常信息为:", e);
            return null;
        }
    }
 
    private String getUserIdByCode(String code, String appKey, String appSecret) throws Exception {
        DefaultDingTalkClient client2 = new DefaultDingTalkClient("https://oapi.dingtalk.com/sns/getuserinfo_bycode");
        OapiSnsGetuserinfoBycodeRequest reqBycodeRequest = new OapiSnsGetuserinfoBycodeRequest();
        reqBycodeRequest.setTmpAuthCode(code);
        OapiSnsGetuserinfoBycodeResponse bycodeResponse = client2.execute(reqBycodeRequest, appKey, appSecret);
        if (Func.isEmpty(bycodeResponse) || Func.isEmpty(bycodeResponse.getUserInfo())) {
            return null;
        }
        String unionid = bycodeResponse.getUserInfo().getUnionid();
        DefaultDingTalkClient defaultDingTalkClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/getbyunionid");
        OapiUserGetbyunionidRequest reqGetbyunionidRequest = new OapiUserGetbyunionidRequest();
        reqGetbyunionidRequest.setUnionid(unionid);
        OapiUserGetbyunionidResponse oapiUserGetbyunionidResponse = defaultDingTalkClient.execute(reqGetbyunionidRequest, this.dingEventService.getDingAccessToken(appKey, appSecret));
        if (Func.isEmpty(oapiUserGetbyunionidResponse) || Func.isEmpty(oapiUserGetbyunionidResponse.getResult()) || Func.isEmpty(oapiUserGetbyunionidResponse.getResult().getUserid())) {
            return null;
        }
        String userid = oapiUserGetbyunionidResponse.getResult().getUserid();
        return userid;
    }
 
    private void relationScanUser(JSONObject userObject, UserOauth userOauth, String state) {
        Employee employee = (Employee) this.employeeService.getById(state);
        if (Func.isNotEmpty(employee)) {
            if (!employee.getTel().equals(userObject.getString("mobile"))) {
                throw new ServiceException(MessageUtils.message("cps.employee.not.current.scan.user", new Object[0]));
            }
            userOauth.setUserId(employee.getId());
            return;
        }
        throw new ServiceException(MessageUtils.message("cps.employee.not.exist.by.mobile", new Object[0]));
    }
 
    private JSONObject getDetailByUserId(String userId, String appKey, String appSecret) throws Exception {
        DefaultDingTalkClient defaultDingTalkClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
        OapiV2UserGetRequest reqDetail = new OapiV2UserGetRequest();
        reqDetail.setUserid(userId);
        OapiV2UserGetResponse rspDetail = defaultDingTalkClient.execute(reqDetail, this.dingEventService.getDingAccessToken(appKey, appSecret));
        JSONObject jsonObject = JSONObject.parseObject(rspDetail.getBody());
        if (jsonObject.getInteger(QyWechatConstant.ERROR_CODE_KEY).equals(DingConstant.SUCCESS)) {
            return jsonObject.getJSONObject("result");
        }
        return null;
    }
 
    private String getUserIdByUnionId(GetUserResponseBody userBody, String appKey, String appSecret) throws Exception {
        DefaultDingTalkClient defaultDingTalkClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/getbyunionid");
        OapiUserGetbyunionidRequest req = new OapiUserGetbyunionidRequest();
        req.setUnionid(userBody.getUnionId());
        OapiUserGetbyunionidResponse rsp = defaultDingTalkClient.execute(req, this.dingEventService.getDingAccessToken(appKey, appSecret));
        if (Func.isEmpty(rsp) || Func.isEmpty(rsp.getBody())) {
            return null;
        }
        JSONObject userObject = JSONObject.parseObject(rsp.getBody()).getJSONObject("result");
        if (Func.isEmpty(userObject)) {
            return null;
        }
        return userObject.getString("userid");
    }
 
    private void handleAuthAndEmployee(List<DingOriUser> oriUsers, List<Employee> employees, List<UserOauth> userOauths, List<CommonGroupOfItem> commonGroupOfItems, List<EmployeePost> employeePosts, List<Employee> updateEmployees) {
        if (Func.isNotEmpty(oriUsers)) {
            String pinValue = this.paramService.getValue("employee.default.pin");
            List<Employee> dbEmployees = this.employeeService.list();
            
            
            Map<String, Employee> employeeMap = dbEmployees.parallelStream().filter(o -> {
                return Func.isNotEmpty(o.getTel());
            }).collect(Collectors.toMap((v0) -> {
                return v0.getTel();
            }, e -> {
                return e;
            }, (k1, k2) -> {
                return k1;
            }));
            Snowflake snowflake = IdUtil.createSnowflake(1L, 1L);
            Set<String> distinctUser = new HashSet<>();
            oriUsers.forEach(oriUser -> {
                if (!distinctUser.contains(oriUser.getUserid())) {
                    distinctUser.add(oriUser.getUserid());
                    Employee employee = handleEmployee(oriUser, employees, commonGroupOfItems, employeePosts, snowflake, pinValue, employeeMap, updateEmployees);
                    UserOauth userOauth = packageUserOauth(employee, oriUser);
                    userOauths.add(userOauth);
                }
            });
        }
    }
 
    @NotNull
    private Employee handleEmployee(DingOriUser oriUser, List<Employee> employees, List<CommonGroupOfItem> commonGroupOfItems, List<EmployeePost> employeePosts, Snowflake snowflake, String pin, Map<String, Employee> employeeMap, List<Employee> updateEmployees) {
        Employee employee = packageEmployee(oriUser, snowflake, pin, employeeMap);
        if (Func.isEmpty(employee.getTenantId())) {
            employees.add(employee);
        } else {
            updateEmployees.add(employee);
        }
        packageRelation(oriUser, employee, commonGroupOfItems, employeePosts);
        return employee;
    }
 
    private void packageRelation(DingOriUser oriUser, Employee employee, List<CommonGroupOfItem> commonGroupOfItems, List<EmployeePost> employeePosts) {
        if (this.userPostRelationMap.containsKey(oriUser.getUserid())) {
            employee.setPostId(StringUtil.join(this.userPostRelationMap.get(oriUser.getUserid()), ","));
            for (String postId : this.userPostRelationMap.get(oriUser.getUserid())) {
                EmployeePost employeePost = new EmployeePost();
                employeePost.setEmployeeId(employee.getId());
                employeePost.setPostId(Long.valueOf(postId));
                employeePosts.add(employeePost);
            }
        }
        commonGroupOfItems.add(CommonGroupOfItem.builder().groupId(Long.valueOf(oriUser.getDept_id_list().get(0).equals(1L) ? 3L : Long.valueOf(String.valueOf(oriUser.getDept_id_list().get(0))).longValue())).itemId(employee.getId()).groupType(CommonGroupTypeEnum.ORGANIZATION.getName()).groupCategory(CommonGroupConstant.DEFAULT_CATEGORY).build());
    }
 
    @NotNull
    private UserOauth packageUserOauth(Employee employee, DingOriUser dingOriUser) {
        UserOauth userOauth = new UserOauth();
        userOauth.setEmail(employee.getEmail());
        userOauth.setUserId(employee.getId());
        userOauth.setUsername(employee.getName());
        userOauth.setSource(DingConstant.DING_AUTH_KEY);
        userOauth.setUuid(dingOriUser.getUserid());
        userOauth.setAvatar(employee.getAvatar());
        return userOauth;
    }
 
    @NotNull
    private Employee packageEmployee(DingOriUser oriUser, Snowflake snowflake, String pin, Map<String, Employee> employeeMap) {
        Employee employee = new Employee();
        employee.setName(oriUser.getName());
        employee.setPinCode(pin);
        employee.setTel(oriUser.getMobile());
        if (Func.isNotEmpty(oriUser.getEmail())) {
            employee.setEmail(oriUser.getEmail());
        }
        if (Func.isNotEmpty(oriUser.getHired_date())) {
            employee.setHireDate(new Date(oriUser.getHired_date().longValue()));
        }
        if (Func.isNotEmpty(oriUser.getJob_number())) {
            employee.setJobNumber(oriUser.getJob_number());
        }
        if (Func.isNotEmpty(oriUser.getAvatar())) {
            employee.setAvatar(oriUser.getAvatar());
        }
        employee.setStatus(CommonConstant.ENABLE);
        employee.setOrganizationId(oriUser.getDept_id_list().get(0).equals(1L) ? "3" : String.valueOf(oriUser.getDept_id_list().get(0)));
        if (employeeMap.containsKey(oriUser.getMobile())) {
            Employee oriEmp = employeeMap.get(oriUser.getMobile());
            employee.setPinCode(oriEmp.getPinCode());
            employee.setUserId(oriEmp.getUserId());
            employee.setJobNumber(oriEmp.getJobNumber());
            employee.setId(oriEmp.getId());
            employee.setTenantId(oriEmp.getTenantId());
            employee.setCreateUser(oriEmp.getCreateUser());
            employee.setCreateDept(oriEmp.getCreateDept());
        } else {
            employee.setId(Long.valueOf(snowflake.nextId()));
        }
        return employee;
    }
 
    private void insertGroups(List<Long> permissionGroups, List<DingOriDept> oriGroups, String appKey, String appSecret) throws Exception {
        for (Long permissionGroup : permissionGroups) {
            DefaultDingTalkClient defaultDingTalkClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/get");
            OapiV2DepartmentGetRequest req = new OapiV2DepartmentGetRequest();
            req.setDeptId(permissionGroup);
            OapiV2DepartmentGetResponse rsp = defaultDingTalkClient.execute(req, this.dingEventService.getDingAccessToken(appKey, appSecret));
            JSONObject jsonObject = JSONObject.parseObject(rsp.getBody());
            if (jsonObject.getInteger(QyWechatConstant.ERROR_CODE_KEY).equals(DingConstant.SUCCESS)) {
                JSONObject resultMap = jsonObject.getJSONObject("result");
                this.groupService.insert(CommonGroup.builder().groupCategory(1).groupType(DingConstant.GROUPTYPE).parentId(Long.valueOf(permissionGroup.equals(1L) ? 0L : Long.valueOf(String.valueOf(resultMap.get("parent_id"))).longValue())).name(String.valueOf(resultMap.get("name"))).status(1).id(Long.valueOf(permissionGroup.equals(1L) ? 3L : permissionGroup.longValue())).build());
            }
        }
        if (Func.isNotEmpty(oriGroups)) {
            oriGroups.forEach(oriGroup -> {
                this.groupService.insert(CommonGroup.builder().groupCategory(1).groupType(DingConstant.GROUPTYPE).parentId(Long.valueOf(oriGroup.getParent_id().equals(1L) ? 3L : oriGroup.getParent_id().longValue())).name(oriGroup.getName()).status(1).id(oriGroup.getDept_id()).build());
            });
        }
    }
 
    private void getRoles(String appKey, String appSecret, List<Post> postList, SyncResultVO syncResultVO) {
        try {
          DefaultDingTalkClient defaultDingTalkClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/role/list");
          OapiRoleListRequest req = new OapiRoleListRequest();
          req.setSize(DingConstant.ROLE_SIZE);
          req.setOffset(DingConstant.START_OFFSET);
          while (true) {
            OapiRoleListResponse rsp = (OapiRoleListResponse)defaultDingTalkClient.execute((TaobaoRequest)req, this.dingEventService.getDingAccessToken(appKey, appSecret));
            JSONObject jsonObject = JSONObject.parseObject(rsp.getBody());
            if (jsonObject.getInteger("errcode").equals(DingConstant.SUCCESS)) {
              Map<String, Object> resultMap = (Map<String, Object>)jsonObject.get("result");
              List<Map<String, Object>> resultList = (List<Map<String, Object>>)resultMap.get("list");
              if (Func.isNotEmpty(resultList))
                for (Map<String, Object> roleGroupMap : resultList) {
                  List<Map<String, Object>> roleList = (List<Map<String, Object>>)roleGroupMap.get("roles");
                  if (Func.isNotEmpty(roleList))
                    for (Map<String, Object> role : roleList) {
                      Post post = new Post();
                      post.setPostCode(String.valueOf(role.get("id")));
                      post.setId(Long.valueOf(String.valueOf(role.get("id"))));
                      post.setPostName(String.valueOf(role.get("name")));
                      post.setStatus(CommonConstant.ENABLE);
                      postList.add(post);
                      getRoleContainsUser(post.getPostCode(), appKey, appSecret);
                    }  
                }  
              if (((Boolean)resultMap.get("hasMore")).booleanValue()) {
                req.setOffset(Long.valueOf(req.getOffset().longValue() + DingConstant.ROLE_SIZE.longValue()));
                continue;
              } 
              break;
            } 
            syncResultVO.setPostResult(Boolean.valueOf(false));
            syncResultVO.setPostReason("同步钉钉角色异常,结果为:" + jsonObject + "---------参数为:" + req);
            break;
          } 
        } catch (Exception e) {
          syncResultVO.setPostResult(Boolean.valueOf(false));
          syncResultVO.setPostReason("同步钉钉角色报错:" + e.toString());
        } 
      }
 
    private void getRoleContainsUser(String postCode, String appKey, String appSecret) throws Exception {
        DefaultDingTalkClient defaultDingTalkClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/role/simplelist");
        OapiRoleSimplelistRequest req = new OapiRoleSimplelistRequest();
        req.setRoleId(Long.valueOf(postCode));
        req.setOffset(DingConstant.START_OFFSET);
        req.setSize(DingConstant.SIZE);
        while (true) {
            OapiRoleSimplelistResponse rsp = defaultDingTalkClient.execute(req, this.dingEventService.getDingAccessToken(appKey, appSecret));
            JSONObject jsonObject = JSONObject.parseObject(rsp.getBody());
            if (jsonObject.getInteger(QyWechatConstant.ERROR_CODE_KEY).equals(DingConstant.SUCCESS)) {
                Map<String, Object> resultMap = (Map) jsonObject.get("result");
                List<Map<String, Object>> resultList = (List) resultMap.get("list");
                if (Func.isNotEmpty(resultList)) {
                    resultList.forEach(userMap -> {
                        if (this.userPostRelationMap.containsKey(String.valueOf(userMap.get("userid")))) {
                            Set<String> userRoleList = this.userPostRelationMap.get(String.valueOf(userMap.get("userid")));
                            userRoleList.add(postCode);
                            this.userPostRelationMap.put(String.valueOf(userMap.get("userid")), userRoleList);
                            return;
                        }
                        Set<String> userRoleList2 = new HashSet<>();
                        userRoleList2.add(postCode);
                        this.userPostRelationMap.put(String.valueOf(userMap.get("userid")), userRoleList2);
                    });
                }
                if (((Boolean) resultMap.get("hasMore")).booleanValue()) {
                    req.setOffset(Long.valueOf(req.getOffset().longValue() + DingConstant.SIZE.longValue()));
                } else {
                    return;
                }
            } else {
                log.error("同步钉钉用户异常,结果为:" + jsonObject + "---------参数为:" + req.toString());
                return;
            }
        }
    }
 
    private void recursionGetGroup(Long deptId, String appKey, String appSecret, List<DingOriDept> oriGroups, List<DingOriUser> oriUsers, SyncResultVO syncResultVO, List<Long> permissionGroups) {
        try {
            DefaultDingTalkClient defaultDingTalkClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsub");
            OapiV2DepartmentListsubRequest req = new OapiV2DepartmentListsubRequest();
            req.setDeptId(Long.valueOf(deptId.equals(3L) ? 1L : deptId.longValue()));
            OapiV2DepartmentListsubResponse rsp = defaultDingTalkClient.execute(req, this.dingEventService.getDingAccessToken(appKey, appSecret));
            JSONObject jsonObject = JSONObject.parseObject(rsp.getBody());
            if (jsonObject.getInteger(QyWechatConstant.ERROR_CODE_KEY).equals(DingConstant.SUCCESS)) {
                List<DingOriDept> resultList = jsonObject.getJSONArray("result").toJavaList(DingOriDept.class);
                if (Func.isNotEmpty(resultList)) {
                    resultList.forEach(dept -> {
                        Long childDeptId = dept.getDept_id();
                        if (!permissionGroups.contains(childDeptId)) {
                            try {
                                oriGroups.add(dept);
                            } catch (Exception e) {
                                log.error("同步钉钉部门入库时异常,部门为:" + dept);
                            }
                            SyncEmployee(childDeptId, appKey, appSecret, oriUsers, syncResultVO);
                            recursionGetGroup(childDeptId, appKey, appSecret, oriGroups, oriUsers, syncResultVO, permissionGroups);
                        }
                    });
                }
            } else {
                syncResultVO.setGroupResult(false);
                syncResultVO.setGroupReason("同步钉钉部门异常,结果为:" + jsonObject + "---------参数为:" + req.toString());
            }
        } catch (Exception e) {
            syncResultVO.setGroupResult(false);
            syncResultVO.setGroupReason("同步钉钉部门报错:" + e.toString());
        }
    }
 
    private void SyncEmployee(Long deptId, String appKey, String appSecret, List<DingOriUser> oriUsers, SyncResultVO syncResultVO) {
        try {
          DefaultDingTalkClient defaultDingTalkClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/list");
          OapiV2UserListRequest req = new OapiV2UserListRequest();
          req.setSize(DingConstant.SIZE);
          req.setDeptId(Long.valueOf(deptId.equals(Long.valueOf(3L)) ? 1L : deptId.longValue()));
          req.setCursor(DingConstant.START_OFFSET);
          while (true) {
            OapiV2UserListResponse rsp = (OapiV2UserListResponse)defaultDingTalkClient.execute((TaobaoRequest)req, this.dingEventService.getDingAccessToken(appKey, appSecret));
            JSONObject jsonObject = JSONObject.parseObject(rsp.getBody());
            if (jsonObject.getInteger("errcode").equals(DingConstant.SUCCESS)) {
              JSONObject resultMap = jsonObject.getJSONObject("result");
              List<DingOriUser> resultList = resultMap.getJSONArray("list").toJavaList(DingOriUser.class);
              if (Func.isNotEmpty(resultList))
                resultList.forEach(userMap -> oriUsers.add(userMap)); 
              if (((Boolean)resultMap.get("has_more")).booleanValue()) {
                req.setCursor(Long.valueOf(String.valueOf(resultMap.get("next_cursor"))));
                continue;
              } 
              break;
            } 
            syncResultVO.setUserResult(Boolean.valueOf(false));
            syncResultVO.setUserReason("同步钉钉用户异常,结果为:" + jsonObject + "---------参数为:" + req);
            break;
          } 
        } catch (Exception e) {
          syncResultVO.setUserResult(Boolean.valueOf(false));
          syncResultVO.setUserReason("同步钉钉用户报错:" + e.toString());
        } 
      }
 
    public static Client authClient() throws Exception {
        Config config = new Config();
        config.protocol = "https";
        config.regionId = "central";
        return new Client(config);
    }
 
    public static com.aliyun.dingtalkcontact_1_0.Client contactClient() throws Exception {
        Config config = new Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkcontact_1_0.Client(config);
    }
 
    public GetUserResponseBody getUserinfo(String accessToken) throws Exception {
        com.aliyun.dingtalkcontact_1_0.Client client = contactClient();
        GetUserHeaders getUserHeaders = new GetUserHeaders();
        getUserHeaders.xAcsDingtalkAccessToken = accessToken;
        GetUserResponseBody responseBody = client.getUserWithOptions("me", getUserHeaders, new RuntimeOptions()).getBody();
        return responseBody;
    }
}