yangys
2024-03-27 e48aa2ac8dea1be5db11c63edf0b912c4ad5ce65
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
package com.qianwen.smartman.modules.sync.service.impl;
 
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jeecg.qywx.api.department.vo.Department;
import java.io.File;
import java.lang.invoke.SerializedLambda;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.StringJoiner;
import java.util.concurrent.Callable;
import java.util.stream.Collectors;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.qianwen.smartman.common.cache.RegionCache;
import com.qianwen.smartman.common.constant.CommonConstant;
import com.qianwen.smartman.common.constant.DateConstant;
import com.qianwen.smartman.common.enums.CommonGroupTypeEnum;
import com.qianwen.smartman.common.utils.MessageUtils;
import com.qianwen.core.log.exception.ServiceException;
import com.qianwen.core.redis.cache.BladeRedis;
import com.qianwen.core.tool.api.R;
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.report.utils.ThreadPoolUtil;
import com.qianwen.smartman.modules.sync.api.QyWechatApi;
import com.qianwen.smartman.modules.sync.constant.OuterAppConfigConstant;
import com.qianwen.smartman.modules.sync.constant.QyWechatApiConstant;
import com.qianwen.smartman.modules.sync.constant.QyWechatConstant;
import com.qianwen.smartman.modules.sync.entity.OuterAppConfig;
import com.qianwen.smartman.modules.sync.entity.QyTag;
import com.qianwen.smartman.modules.sync.entity.QyUser;
import com.qianwen.smartman.modules.sync.entity.QyUserTicket;
import com.qianwen.smartman.modules.sync.enums.SseEventEnum;
import com.qianwen.smartman.modules.sync.enums.WechatResponseEnum;
import com.qianwen.smartman.modules.sync.message.sse.SseEmitterServer;
import com.qianwen.smartman.modules.sync.service.IWechatSyncService;
import com.qianwen.smartman.modules.sync.util.CodeUtil;
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 org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
 
@Service
/* loaded from: blade-api.jar:BOOT-INF/classes/org/springblade/modules/sync/service/impl/WechatSyncServiceImpl.class */
public class WechatSyncServiceImpl implements IWechatSyncService {
    private static final Logger log = LoggerFactory.getLogger(WechatSyncServiceImpl.class);
    private final IPostService iPostService;
    private final PostMapper postMapper;
    private final ICommonGroupService commonGroupService;
    private final ICommonGroupOfItemService commonGroupOfItemService;
    private final IEmployeeService iEmployeeService;
    private final IUserOauthService userOauthService;
    private final CommonGroupMapper commonGroupMapper;
    private final IEmployeePostService employeePostService;
    private final DataSourceTransactionManager dataSourceTransactionManager;
    private final RocketMQTemplate rocketMQTemplate;
    private final OuterAppConfigServiceImpl outerAppConfigService;
    private final SseEmitterServer sseEmitterServer;
    private final BladeRedis bladeRedis;
    private final IParamService paramService;
    private List<Department> departments;
    private final Map<WechatResponseEnum, QyWechatSync> syncMethod = new HashMap();
 
    /* JADX INFO: Access modifiers changed from: package-private */
    @FunctionalInterface
    /* loaded from: blade-api.jar:BOOT-INF/classes/org/springblade/modules/sync/service/impl/WechatSyncServiceImpl$QyWechatSync.class */
    public interface QyWechatSync {
        void sync() throws Exception;
    }
 
    private static /* synthetic */ Object $deserializeLambda$(SerializedLambda lambda) {
        String implMethodName = lambda.getImplMethodName();
        boolean z = true;
        switch (implMethodName.hashCode()) {
            case -1249349403:
                if (implMethodName.equals("getTel")) {
                    z = true;
                    break;
                }
                break;
            case -75080655:
                if (implMethodName.equals("getUuid")) {
                    z = true;
                    break;
                }
                break;
            case 98245393:
                if (implMethodName.equals("getId")) {
                    z = true;
                    break;
                }
                break;
            case 242925765:
                if (implMethodName.equals("getAppType")) {
                    z = true;
                    break;
                }
                break;
            case 799509265:
                if (implMethodName.equals("getSource")) {
                    z = false;
                    break;
                }
                break;
            case 1722789684:
                if (implMethodName.equals("getLastSyncTime")) {
                    z = true;
                    break;
                }
                break;
        }
        switch (z) {
            case false:
                if (lambda.getImplMethodKind() == 5 && lambda.getFunctionalInterfaceClass().equals("com/baomidou/mybatisplus/core/toolkit/support/SFunction") && lambda.getFunctionalInterfaceMethodName().equals("apply") && lambda.getFunctionalInterfaceMethodSignature().equals("(Ljava/lang/Object;)Ljava/lang/Object;") && lambda.getImplClass().equals("org/springblade/modules/system/entity/UserOauth") && lambda.getImplMethodSignature().equals("()Ljava/lang/String;")) {
                    return (v0) -> {
                        return v0.getSource();
                    };
                }
                if (lambda.getImplMethodKind() == 5 && lambda.getFunctionalInterfaceClass().equals("com/baomidou/mybatisplus/core/toolkit/support/SFunction") && lambda.getFunctionalInterfaceMethodName().equals("apply") && lambda.getFunctionalInterfaceMethodSignature().equals("(Ljava/lang/Object;)Ljava/lang/Object;") && lambda.getImplClass().equals("org/springblade/modules/system/entity/UserOauth") && lambda.getImplMethodSignature().equals("()Ljava/lang/String;")) {
                    return (v0) -> {
                        return v0.getSource();
                    };
                }
                break;
            case true:
                if (lambda.getImplMethodKind() == 5 && lambda.getFunctionalInterfaceClass().equals("com/baomidou/mybatisplus/core/toolkit/support/SFunction") && lambda.getFunctionalInterfaceMethodName().equals("apply") && lambda.getFunctionalInterfaceMethodSignature().equals("(Ljava/lang/Object;)Ljava/lang/Object;") && lambda.getImplClass().equals("org/springblade/modules/system/entity/UserOauth") && lambda.getImplMethodSignature().equals("()Ljava/lang/String;")) {
                    return (v0) -> {
                        return v0.getUuid();
                    };
                }
                if (lambda.getImplMethodKind() == 5 && lambda.getFunctionalInterfaceClass().equals("com/baomidou/mybatisplus/core/toolkit/support/SFunction") && lambda.getFunctionalInterfaceMethodName().equals("apply") && lambda.getFunctionalInterfaceMethodSignature().equals("(Ljava/lang/Object;)Ljava/lang/Object;") && lambda.getImplClass().equals("org/springblade/modules/system/entity/UserOauth") && lambda.getImplMethodSignature().equals("()Ljava/lang/String;")) {
                    return (v0) -> {
                        return v0.getUuid();
                    };
                }
                break;
            case true:
                if (lambda.getImplMethodKind() == 5 && lambda.getFunctionalInterfaceClass().equals("com/baomidou/mybatisplus/core/toolkit/support/SFunction") && lambda.getFunctionalInterfaceMethodName().equals("apply") && lambda.getFunctionalInterfaceMethodSignature().equals("(Ljava/lang/Object;)Ljava/lang/Object;") && lambda.getImplClass().equals("org/springblade/core/mp/base/BaseEntity") && lambda.getImplMethodSignature().equals("()Ljava/lang/Long;")) {
                    return (v0) -> {
                        return v0.getId();
                    };
                }
                if (lambda.getImplMethodKind() == 5 && lambda.getFunctionalInterfaceClass().equals("com/baomidou/mybatisplus/core/toolkit/support/SFunction") && lambda.getFunctionalInterfaceMethodName().equals("apply") && lambda.getFunctionalInterfaceMethodSignature().equals("(Ljava/lang/Object;)Ljava/lang/Object;") && lambda.getImplClass().equals("org/springblade/core/mp/base/BaseEntity") && lambda.getImplMethodSignature().equals("()Ljava/lang/Long;")) {
                    return (v0) -> {
                        return v0.getId();
                    };
                }
                if (lambda.getImplMethodKind() == 5 && lambda.getFunctionalInterfaceClass().equals("com/baomidou/mybatisplus/core/toolkit/support/SFunction") && lambda.getFunctionalInterfaceMethodName().equals("apply") && lambda.getFunctionalInterfaceMethodSignature().equals("(Ljava/lang/Object;)Ljava/lang/Object;") && lambda.getImplClass().equals("org/springblade/core/mp/base/BaseEntity") && lambda.getImplMethodSignature().equals("()Ljava/lang/Long;")) {
                    return (v0) -> {
                        return v0.getId();
                    };
                }
                if (lambda.getImplMethodKind() == 5 && lambda.getFunctionalInterfaceClass().equals("com/baomidou/mybatisplus/core/toolkit/support/SFunction") && lambda.getFunctionalInterfaceMethodName().equals("apply") && lambda.getFunctionalInterfaceMethodSignature().equals("(Ljava/lang/Object;)Ljava/lang/Object;") && lambda.getImplClass().equals("org/springblade/core/mp/base/BaseEntity") && lambda.getImplMethodSignature().equals("()Ljava/lang/Long;")) {
                    return (v0) -> {
                        return v0.getId();
                    };
                }
                break;
            case true:
                if (lambda.getImplMethodKind() == 5 && lambda.getFunctionalInterfaceClass().equals("com/baomidou/mybatisplus/core/toolkit/support/SFunction") && lambda.getFunctionalInterfaceMethodName().equals("apply") && lambda.getFunctionalInterfaceMethodSignature().equals("(Ljava/lang/Object;)Ljava/lang/Object;") && lambda.getImplClass().equals("org/springblade/modules/sync/entity/OuterAppConfig") && lambda.getImplMethodSignature().equals("()Ljava/util/Date;")) {
                    return (v0) -> {
                        return v0.getLastSyncTime();
                    };
                }
                break;
            case true:
                if (lambda.getImplMethodKind() == 5 && lambda.getFunctionalInterfaceClass().equals("com/baomidou/mybatisplus/core/toolkit/support/SFunction") && lambda.getFunctionalInterfaceMethodName().equals("apply") && lambda.getFunctionalInterfaceMethodSignature().equals("(Ljava/lang/Object;)Ljava/lang/Object;") && lambda.getImplClass().equals("org/springblade/modules/cps/entity/Employee") && lambda.getImplMethodSignature().equals("()Ljava/lang/String;")) {
                    return (v0) -> {
                        return v0.getTel();
                    };
                }
                if (lambda.getImplMethodKind() == 5 && lambda.getFunctionalInterfaceClass().equals("com/baomidou/mybatisplus/core/toolkit/support/SFunction") && lambda.getFunctionalInterfaceMethodName().equals("apply") && lambda.getFunctionalInterfaceMethodSignature().equals("(Ljava/lang/Object;)Ljava/lang/Object;") && lambda.getImplClass().equals("org/springblade/modules/cps/entity/Employee") && lambda.getImplMethodSignature().equals("()Ljava/lang/String;")) {
                    return (v0) -> {
                        return v0.getTel();
                    };
                }
                break;
            case RegionCache.VILLAGE_LEVEL /* 5 */:
                if (lambda.getImplMethodKind() == 5 && lambda.getFunctionalInterfaceClass().equals("com/baomidou/mybatisplus/core/toolkit/support/SFunction") && lambda.getFunctionalInterfaceMethodName().equals("apply") && lambda.getFunctionalInterfaceMethodSignature().equals("(Ljava/lang/Object;)Ljava/lang/Object;") && lambda.getImplClass().equals("org/springblade/modules/sync/entity/OuterAppConfig") && lambda.getImplMethodSignature().equals("()Ljava/lang/Integer;")) {
                    return (v0) -> {
                        return v0.getAppType();
                    };
                }
                break;
        }
        throw new IllegalArgumentException("Invalid lambda deserialization");
    }
 
    public WechatSyncServiceImpl(final IPostService iPostService, final PostMapper postMapper, final ICommonGroupService commonGroupService, final ICommonGroupOfItemService commonGroupOfItemService, final IEmployeeService iEmployeeService, final IUserOauthService userOauthService, final CommonGroupMapper commonGroupMapper, final IEmployeePostService employeePostService, final DataSourceTransactionManager dataSourceTransactionManager, final RocketMQTemplate rocketMQTemplate, final OuterAppConfigServiceImpl outerAppConfigService, final SseEmitterServer sseEmitterServer, final BladeRedis bladeRedis, final IParamService paramService, final List<Department> departments) {
        this.syncMethod.put(WechatResponseEnum.EMP, this::syncUser);
        this.syncMethod.put(WechatResponseEnum.DEPT, this::syncDeptData);
        this.syncMethod.put(WechatResponseEnum.POST, this::syncPosition);
        this.iPostService = iPostService;
        this.postMapper = postMapper;
        this.commonGroupService = commonGroupService;
        this.commonGroupOfItemService = commonGroupOfItemService;
        this.iEmployeeService = iEmployeeService;
        this.userOauthService = userOauthService;
        this.commonGroupMapper = commonGroupMapper;
        this.employeePostService = employeePostService;
        this.dataSourceTransactionManager = dataSourceTransactionManager;
        this.rocketMQTemplate = rocketMQTemplate;
        this.outerAppConfigService = outerAppConfigService;
        this.sseEmitterServer = sseEmitterServer;
        this.bladeRedis = bladeRedis;
        this.paramService = paramService;
        this.departments = departments;
    }
 
    private Boolean execSync() {
        WechatResponseEnum[] values;
        WechatResponseEnum.clean();
        boolean isExecSuccess = true;
        for (WechatResponseEnum responseEnum : WechatResponseEnum.values()) {
            QyWechatSync qyWechatSync = this.syncMethod.get(responseEnum);
            if (!Objects.isNull(qyWechatSync)) {
                try {
                    qyWechatSync.sync();
                    responseEnum.accept("");
                } catch (Exception e) {
                    responseEnum.accept(getErrMsg(responseEnum.getDesc(), e));
                    isExecSuccess = false;
                }
            }
        }
        return Boolean.valueOf(isExecSuccess);
    }
 
    @Override // org.springblade.modules.sync.service.IWechatSyncService
    public SyncResultVO syncOrganization() {
        TimeInterval timer = DateUtil.timer();
        log.info("[企业微信同步组织架构].[syncOrganization start ....]");
        DefaultTransactionDefinition transDefinition = new DefaultTransactionDefinition();
        TransactionStatus transStatus = this.dataSourceTransactionManager.getTransaction(transDefinition);
        try {
            try {
                Boolean isExecSuccess = execSync();
                if (isExecSuccess.booleanValue()) {
                    this.outerAppConfigService.update((Wrapper) ((LambdaUpdateWrapper) Wrappers.lambdaUpdate().eq((v0) -> {
                        return v0.getAppType();
                    }, OuterAppConfigConstant.QY_WECHAT)).set((v0) -> {
                        return v0.getLastSyncTime();
                    }, new Date()));
                    this.dataSourceTransactionManager.commit(transStatus);
                    log.info("[企业微信同步组织架构].[syncOrganization success consuming={}秒]", Long.valueOf(timer.intervalSecond()));
                } else {
                    this.dataSourceTransactionManager.rollback(transStatus);
                    log.error("[企业微信同步组织架构].[syncOrganization error]");
                }
                this.departments.clear();
            } catch (Exception e) {
                this.dataSourceTransactionManager.rollback(transStatus);
                log.error("[企业微信同步组织架构].[syncOrganization error]");
                this.departments.clear();
            }
            return WechatResponseEnum.getSyncResult();
        } catch (Throwable th) {
            this.departments.clear();
            throw th;
        }
    }
 
    private String getErrMsg(String desc, Exception e) {
        String methodName = ArrayUtil.isEmpty(e.getStackTrace()) ? "API" : e.getStackTrace()[0].getMethodName();
        return StrUtil.format("[企业微信同步{}].[{} error errMsg={}]", new Object[]{desc, methodName, e.getMessage()});
    }
 
    private void syncUser() {
        List<QyUser> userList = getUserList();
        if (CollectionUtil.isEmpty(userList)) {
            if (!WechatResponseEnum.getSyncResult().getGroupResult().booleanValue()) {
                throw new ServiceException("部门获取失败,无法拉取到用户信息");
            }
            return;
        }
        List<UserOauth> oauthList = getUserOauthByUuid(userList);
        Map<String, UserOauth> oauthMap = (Map) oauthList.parallelStream().collect(Collectors.toMap((v0) -> {
            return v0.getUuid();
        }, user -> {
            return user;
        }, old, newVal -> {
            return old;
        }));
        initEmpData(oauthList);
        List<Long> empIds = (List) oauthList.stream().map((v0) -> {
            return v0.getUserId();
        }).collect(Collectors.toList());
        List<Employee> employeeList = this.iEmployeeService.list(Wrappers.lambdaQuery().in(CollectionUtil.isNotEmpty(empIds), (v0) -> {
            return v0.getId();
        }, empIds));
        Map<String, Employee> syncEmp = convertEmpToMap(oauthList, employeeList);
        List<UserOauth> userOauthList = new ArrayList<>();
        userList.forEach(userDept -> {
            Employee employee = setEmpAttribute(userDept, (Employee) syncEmp.get(userDept.getUserid()));
            syncEmp.put(userDept.getUserid(), employee);
            UserOauth userOauth = (UserOauth) oauthMap.get(userDept.getUserid());
            if (Objects.isNull(userOauth)) {
                userOauth = new UserOauth();
                userOauth.setUuid(userDept.getUserid());
                userOauth.setSource(QyWechatConstant.QY_SOURCE);
            }
            userOauth.setUsername(userDept.getName());
            userOauthList.add(userOauth);
        });
        this.iEmployeeService.saveOrUpdateBatch(syncEmp.values());
        for (UserOauth userOauth : userOauthList) {
            Employee employee = syncEmp.get(userOauth.getUuid());
            if (!Objects.isNull(employee)) {
                userOauth.setUserId(employee.getId());
            }
        }
        this.userOauthService.saveOrUpdateBatch(userOauthList);
        syncConcat(syncEmp);
        log.info("[企业微信同步用户id列表].[syncUserIdList success userOauthList={}]", userOauthList);
    }
 
    private void initEmpData(List<UserOauth> userOauthList) {
        if (CollectionUtil.isEmpty(userOauthList)) {
            this.iEmployeeService.remove(null);
            return;
        }
        List<Long> empIds = (List) userOauthList.stream().map((v0) -> {
            return v0.getUserId();
        }).filter((v0) -> {
            return Objects.nonNull(v0);
        }).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(empIds)) {
            this.iEmployeeService.remove((Wrapper) Wrappers.lambdaQuery().notIn((v0) -> {
                return v0.getId();
            }, empIds));
        } else {
            this.iEmployeeService.remove(null);
        }
    }
 
    private List<UserOauth> getUserOauthByUuid(List<QyUser> qyUsers) {
        if (CollectionUtil.isEmpty(qyUsers)) {
            return new ArrayList();
        }
        List<String> qyUserIds = (List) qyUsers.stream().map((v0) -> {
            return v0.getUserid();
        }).collect(Collectors.toList());
        return this.userOauthService.list((Wrapper) ((LambdaQueryWrapper) Wrappers.lambdaQuery().eq((v0) -> {
            return v0.getSource();
        }, QyWechatConstant.QY_SOURCE)).in((v0) -> {
            return v0.getUuid();
        }, qyUserIds));
    }
 
    private Map<String, Employee> convertEmpToMap(List<UserOauth> userOauthList, List<Employee> employees) {
        Map<String, Employee> result = new HashMap<>(16);
        if (CollectionUtil.isEmpty(userOauthList) || CollectionUtil.isEmpty(employees)) {
            return result;
        }
        Map<Long, UserOauth> oauthMap = (Map) userOauthList.stream().collect(Collectors.toMap((v0) -> {
            return v0.getUserId();
        }, ua -> {
            return ua;
        }, old, newVal -> {
            return old;
        }));
        for (Employee employee : employees) {
            UserOauth userOauth = oauthMap.get(employee.getId());
            if (!Objects.isNull(userOauth)) {
                result.put(userOauth.getUuid(), employee);
            }
        }
        return result;
    }
 
    private void syncConcat(Map<String, Employee> employeeMap) {
        List<CommonGroupOfItem> commonGroupOfItems = new ArrayList<>();
        List<EmployeePost> employeePosts = new ArrayList<>();
        Map<String, StringJoiner> userTagMap = QyWechatApi.getUserTagMap();
        employeeMap.forEach(userId, employee -> {
            CommonGroupOfItem commonGroupOfItem = setItem(employee.getId(), Long.valueOf(employee.getOrganizationId()));
            commonGroupOfItems.add(commonGroupOfItem);
            employeePosts.addAll(employeePosts(employee, userId, userTagMap));
        });
        if (CollectionUtil.isNotEmpty(employeePosts)) {
            this.employeePostService.saveBatch(employeePosts);
            this.iEmployeeService.updateBatchById(employeeMap.values());
        }
        this.commonGroupOfItemService.saveBatch(commonGroupOfItems);
    }
 
    private List<QyUser> getUserList() {
        List<Callable<List<QyUser>>> taskList = new ArrayList<>();
        this.departments.forEach(d -> {
            taskList.add(() -> {
                return QyWechatApi.getUsersByDepartId(d.getId());
            });
        });
        List<QyUser> userList = ThreadPoolUtil.createTaskList(taskList);
        HashSet<QyUser> result = new HashSet<>(userList);
        return new ArrayList(result);
    }
 
    @Override // org.springblade.modules.sync.service.IWechatSyncService
    public R<Boolean> scanCodeBind(String code, String clientId, String empId) {
        if (CodeUtil.verifyBindCodeExpire(clientId, Long.valueOf(empId)).booleanValue()) {
            String codeFailMessage = MessageUtils.message("sync.qy.login.code.failure", new Object[0]);
            this.sseEmitterServer.sendMsg(clientId, codeFailMessage, SseEventEnum.ERROR_MSG_ID.getEventId());
            throw new ServiceException(codeFailMessage);
        } else if (StrUtil.isEmpty(code)) {
            String appUserMsg = MessageUtils.message("sys.outer.user.not.exist", new Object[0]);
            this.sseEmitterServer.sendMsg(clientId, appUserMsg, SseEventEnum.ERROR_MSG_ID.getEventId());
            throw new ServiceException(appUserMsg);
        } else {
            QyUser qyUser = getScanUser(code, clientId);
            singleUserBind(qyUser, Long.valueOf(empId), clientId);
            this.sseEmitterServer.sendMsg(clientId, Boolean.TRUE, SseEventEnum.BIND_SUCCESS.getEventId());
            String cacheKey = CodeUtil.getBindCodeCacheKey(clientId, Long.valueOf(empId));
            CodeUtil.failureCode(cacheKey);
            return R.data(Boolean.TRUE);
        }
    }
 
    public QyUser getScanUser(String code, String clientId) {
        try {
            QyUserTicket userTicket = QyWechatApi.getUserTicketByCode(code);
            QyUser qyUser = QyWechatApi.getUserDetailByTicket(userTicket.getUser_ticket());
            QyUser baseUserInfo = QyWechatApi.getUserById(qyUser.getUserid());
            qyUser.setName(baseUserInfo.getName());
            qyUser.setDepartment(baseUserInfo.getDepartment());
            qyUser.setMain_department(baseUserInfo.getMain_department());
            log.info("[企业微信扫码].[员工信息 username={},userId={},avatar={},email={}]", new Object[]{qyUser.getName(), qyUser.getUserid(), qyUser.getAvatar(), qyUser.getBiz_mail()});
            return qyUser;
        } catch (ServiceException e) {
            this.sseEmitterServer.sendMsg(clientId, e.getMessage(), SseEventEnum.ERROR_MSG_ID.getEventId());
            throw new ServiceException(e.getResultCode());
        }
    }
 
    @Override // org.springblade.modules.sync.service.IWechatSyncService
    public JSONObject generateCode(String clientId, Integer type, Long empId) {
        JSONObject result = new JSONObject();
        try {
            String cacheKey = type.equals(QyWechatConstant.QY_CODE_LOGIN_TYPE) ? CodeUtil.getLoginCodeCacheKey(clientId) : CodeUtil.getBindCodeCacheKey(clientId, empId);
            Object cacheObj = this.bladeRedis.get(cacheKey);
            if (!Objects.isNull(cacheObj)) {
                File codeFile = CodeUtil.generateCode((String) Convert.convert(String.class, cacheObj), CodeUtil.getCodeLocalFilePath(clientId));
                result.put("link", QyWechatConstant.BASE64_PREFIX + CodeUtil.codeFileToBase64(codeFile));
                FileUtil.del(CodeUtil.getCodeLocalFilePath(clientId));
                return result;
            }
            File tempDir = new File(QyWechatConstant.TEMP_PATH);
            if (!tempDir.exists()) {
                FileUtil.mkdir(QyWechatConstant.TEMP_PATH);
            }
            String authLink = buildAuthLink(clientId, type, empId);
            File codeFile2 = CodeUtil.generateCode(authLink, CodeUtil.getCodeLocalFilePath(clientId));
            JSONObject message = new JSONObject();
            message.put("clientId", clientId);
            message.put("type", type);
            message.put("empId", empId);
            SendResult sendResult = this.rocketMQTemplate.syncSend(QyWechatConstant.WECHAT_TOPIC, MessageBuilder.withPayload(message).build(), 3000L, 5);
            Logger logger = log;
            Object[] objArr = new Object[3];
            objArr[0] = Objects.equals(type, QyWechatConstant.QY_CODE_LOGIN_TYPE) ? "登录" : "绑定";
            objArr[1] = DateUtil.format(new Date(), DateConstant.PATTERN_DATE_TIME);
            objArr[2] = sendResult;
            logger.info("[生成企业微信{}二维码].[发送延时消息,时间:{}].[generateCode sendResult={}]", objArr);
            this.bladeRedis.setEx(cacheKey, authLink, 120L);
            result.put("link", QyWechatConstant.BASE64_PREFIX + CodeUtil.codeFileToBase64(codeFile2));
            FileUtil.del(CodeUtil.getCodeLocalFilePath(clientId));
            return result;
        } catch (Throwable th) {
            FileUtil.del(CodeUtil.getCodeLocalFilePath(clientId));
            throw th;
        }
    }
 
    private String buildAuthLink(String clientId, Integer type, Long empId) {
        String callbackApi;
        String state = "";
        OuterAppConfig appConfig = this.outerAppConfigService.getAppConfig(OuterAppConfigConstant.QY_WECHAT);
        if (Objects.isNull(appConfig) || !appConfig.getStatus().equals(CommonConstant.ENABLE)) {
            throw new ServiceException(MessageUtils.message("sync.qy.config.not.exist", new Object[0]));
        }
        String callbackApi2 = appConfig.getDomainUrl() + "{}?clientId={}";
        if (type.equals(QyWechatConstant.QY_CODE_LOGIN_TYPE)) {
            callbackApi = StrUtil.format(callbackApi2, new Object[]{"/scanLogin", clientId});
        } else {
            state = String.valueOf(empId);
            callbackApi = StrUtil.format(callbackApi2, new Object[]{"/scanBind", clientId});
        }
        return QyWechatApi.parseRequestUrl(QyWechatApiConstant.AUTH_URL, appConfig.getWxCorpId(), callbackApi, state, appConfig.getWxAgentId());
    }
 
    private Employee setEmpAttribute(QyUser user, Employee employee) {
        if (Objects.isNull(employee)) {
            employee = new Employee();
        }
        employee.setName(user.getName());
        employee.setEmail(user.getBiz_mail());
        employee.setTel(user.getMobile());
        employee.setHireDate(new Date());
        employee.setAvatar(user.getAvatar());
        employee.setPinCode(StrUtil.isEmpty(employee.getPinCode()) ? this.paramService.getValue("employee.default.pin") : employee.getPinCode());
        employee.setOrganizationId(user.getDepartment()[0].intValue() == 1 ? "3" : QyWechatConstant.ID_SALT + user.getDepartment()[0]);
        employee.setStatus(1);
        return employee;
    }
 
    private UserOauth setOauth(QyUser user, Employee employee, UserOauth userOauth) {
        if (Objects.isNull(userOauth)) {
            userOauth = new UserOauth();
        }
        userOauth.setEmail(user.getBiz_mail());
        userOauth.setUserId(employee.getId());
        userOauth.setUsername(employee.getName());
        userOauth.setSource(QyWechatConstant.QY_SOURCE);
        userOauth.setUuid(user.getUserid());
        userOauth.setAvatar(user.getAvatar());
        return userOauth;
    }
 
    public CommonGroupOfItem setItem(Long empId, Long deptId) {
        CommonGroupOfItem commonGroupOfItem = new CommonGroupOfItem();
        commonGroupOfItem.setGroupType(CommonGroupTypeEnum.ORGANIZATION.getName());
        commonGroupOfItem.setGroupCategory(1);
        commonGroupOfItem.setItemId(empId);
        commonGroupOfItem.setGroupId(deptId);
        return commonGroupOfItem;
    }
 
    private void syncPosition() {
        this.postMapper.removePost();
        this.employeePostService.remove(null);
        List<QyTag> tags = QyWechatApi.getTags();
        if (CollectionUtil.isEmpty(tags)) {
            return;
        }
        List<Post> posts = (List) tags.parallelStream().map(t -> {
            return setPost(t.getTagname(), t.getTagid());
        }).collect(Collectors.toList());
        this.iPostService.saveBatch(posts);
        log.info("[企业微信同步岗位].[syncPosition success,data={}]", tags);
    }
 
    public Post setPost(String postName, String postId) {
        Post post = new Post();
        post.setPostName(postName);
        post.setPostCode(IdUtil.simpleUUID());
        post.setId(Long.valueOf(postId));
        post.setStatus(1);
        return post;
    }
 
    private void syncDeptData() {
        this.commonGroupMapper.removeOrg();
        this.commonGroupMapper.removeOrgContact();
        List<Department> deptList = QyWechatApi.getDepartmentAll();
        this.departments = deptList;
        if (CollectionUtil.isEmpty(deptList)) {
            return;
        }
        for (Department department : deptList) {
            CommonGroup commonGroup = setCommonGroup(department);
            this.commonGroupService.insert(commonGroup);
        }
        log.info("[企业微信同步部门].[syncDeptData success depts={}]", deptList.parallelStream().map((v0) -> {
            return v0.getName();
        }).collect(Collectors.toList()));
    }
 
    public CommonGroup setCommonGroup(Department department) {
        CommonGroup commonGroup = new CommonGroup();
        if (Integer.parseInt(department.getId()) == 1) {
            commonGroup.setId(3L);
            commonGroup.setParentId(0L);
        } else if (Integer.parseInt(department.getParentid()) == 1) {
            commonGroup.setId(Long.valueOf(QyWechatConstant.ID_SALT + department.getId()));
            commonGroup.setParentId(3L);
        } else {
            commonGroup.setId(Long.valueOf(QyWechatConstant.ID_SALT + department.getId()));
            commonGroup.setParentId(Long.valueOf(QyWechatConstant.ID_SALT + department.getParentid()));
        }
        commonGroup.setName(department.getName());
        commonGroup.setGroupCategory(1);
        commonGroup.setGroupType(CommonGroupTypeEnum.ORGANIZATION.getName());
        return commonGroup;
    }
 
    @Transactional
    public void singleUserBind(QyUser user, Long empId, String clientId) {
        UserOauth userOauth = (UserOauth) this.userOauthService.getOne((Wrapper) ((LambdaQueryWrapper) Wrappers.lambdaQuery().eq((v0) -> {
            return v0.getUuid();
        }, user.getUserid())).eq((v0) -> {
            return v0.getSource();
        }, QyWechatConstant.QY_SOURCE), Boolean.TRUE.booleanValue());
        if (Objects.isNull(userOauth)) {
            this.sseEmitterServer.sendMsg(clientId, MessageUtils.message("sys.outer.user.not.exist", new Object[0]), SseEventEnum.ERROR_MSG_ID.getEventId());
            throw new ServiceException(MessageUtils.message("sys.outer.user.not.exist", new Object[0]));
        }
        Employee employee = (Employee) this.iEmployeeService.getOne((Wrapper) ((LambdaQueryWrapper) Wrappers.lambdaQuery().eq((v0) -> {
            return v0.getTel();
        }, user.getMobile())).eq((v0) -> {
            return v0.getId();
        }, empId));
        if (Objects.isNull(employee)) {
            this.sseEmitterServer.sendMsg(clientId, MessageUtils.message("cps.employee.outer.app.not.have.mobile", new Object[0]), SseEventEnum.ERROR_MSG_ID.getEventId());
            throw new ServiceException(MessageUtils.message("cps.employee.outer.app.not.have.mobile", new Object[0]));
        } else if (!employee.getTel().equals(user.getMobile())) {
            String message = MessageUtils.message("cps.employee.not.current.scan.user", new Object[0]);
            this.sseEmitterServer.sendMsg(clientId, message, SseEventEnum.ERROR_MSG_ID.getEventId());
            throw new ServiceException(message);
        } else if (userOauth.getUserId() == null) {
            userOauth.setUserId(employee.getId());
            this.userOauthService.updateById(userOauth);
        } else {
            this.sseEmitterServer.sendMsg(clientId, MessageUtils.message("cps.employee.already.bind", new Object[0]), SseEventEnum.ERROR_MSG_ID.getEventId());
            throw new ServiceException(MessageUtils.message("cps.employee.already.bind", new Object[0]));
        }
    }
 
    public Employee createOrModifyEmployee(QyUser qyUser, UserOauth userOauth) {
        Employee employee = null;
        if (!Objects.isNull(userOauth)) {
            employee = (Employee) this.iEmployeeService.getOne((Wrapper) Wrappers.lambdaQuery().eq((v0) -> {
                return v0.getId();
            }, userOauth.getUserId()));
        }
        if (Objects.isNull(employee)) {
            employee = (Employee) this.iEmployeeService.getOne((Wrapper) Wrappers.lambdaQuery().eq((v0) -> {
                return v0.getTel();
            }, qyUser.getMobile()), Boolean.TRUE.booleanValue());
        }
        Employee employee2 = setEmpAttribute(qyUser, employee);
        this.iEmployeeService.saveOrUpdate(employee2);
        bindConcat(qyUser, employee2);
        this.userOauthService.saveOrUpdate(setOauth(qyUser, employee2, userOauth));
        return employee2;
    }
 
    private void bindConcat(QyUser user, Employee employee) {
        CommonGroupOfItem commonGroupOfItem = setItem(employee.getId(), Long.valueOf(employee.getOrganizationId()));
        this.commonGroupOfItemService.save(commonGroupOfItem);
        Map<String, StringJoiner> userTagMap = QyWechatApi.getUserTagMap();
        List<EmployeePost> employeePosts = employeePosts(employee, user.getUserid(), userTagMap);
        if (CollectionUtil.isNotEmpty(employeePosts)) {
            this.employeePostService.saveBatch(employeePosts);
            this.iEmployeeService.updateById(employee);
        }
    }
 
    private List<EmployeePost> employeePosts(Employee employee, String userId, Map<String, StringJoiner> userTagMap) {
        List<EmployeePost> result = new ArrayList<>();
        if (CollectionUtil.isEmpty(userTagMap)) {
            return new ArrayList();
        }
        StringJoiner postIdJoiner = userTagMap.get(userId);
        if (Objects.isNull(postIdJoiner)) {
            return new ArrayList();
        }
        employee.setPostId(postIdJoiner.toString());
        String[] postIds = postIdJoiner.toString().split(",");
        Arrays.stream(postIds).forEach(id -> {
            EmployeePost employeePost = setEmployeePost(id, String.valueOf(employee.getId()));
            result.add(employeePost);
        });
        return result;
    }
 
    /* JADX INFO: Access modifiers changed from: protected */
    public EmployeePost setEmployeePost(String postId, String empId) {
        EmployeePost employeePost = new EmployeePost();
        employeePost.setEmployeeId(Long.valueOf(empId));
        employeePost.setPostId(Long.valueOf(postId));
        return employeePost;
    }
}