DriverJob.java
29.3 KB
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
package com.ruoyi.job;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.ruoyi.common.SchedulerProperty;
import com.ruoyi.common.cache.NowSchedulingCache;
import com.ruoyi.common.cache.SchedulingCache;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.domain.scheduling.LinggangScheduling;
import com.ruoyi.driver.domain.Driver;
import com.ruoyi.driver.service.IDriverService;
import com.ruoyi.equipment.domain.Equipment;
import com.ruoyi.equipment.mapper.EquipmentMapper;
import com.ruoyi.expand.domain.DriverSchedulingExpand;
import com.ruoyi.expand.mapper.DriverSchedulingExpandMapper;
import com.ruoyi.framework.security.filter.JwtAuthenticationTokenFilter;
import com.ruoyi.pojo.request.PersonnelRequestVo;
import com.ruoyi.pojo.request.TokenRequestVo;
import com.ruoyi.pojo.response.ResponseSchedulingDto;
import com.ruoyi.pojo.response.personnel.*;
import com.ruoyi.pojo.vo.ExpandResponseVo;
import com.ruoyi.service.DriverSchedulingExpandSmartService;
import com.ruoyi.service.RuleAttendanceMainService;
import com.ruoyi.service.RuleNumSettingService;
import com.ruoyi.service.ThreadJobService;
import com.ruoyi.service.key.location.LinggangKeyWorkLocationService;
import com.ruoyi.service.scheduling.LinggangSchedulingService;
import com.ruoyi.utils.ConstDateUtil;
import com.ruoyi.utils.DateUtil;
import com.ruoyi.utils.ListUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import static com.ruoyi.common.ConstDriverProperties.*;
import static com.ruoyi.common.ConstEquipmentProperties.*;
import static com.ruoyi.common.redispre.GlobalRedisPreName.*;
/**
* 该定时任务用户获取驾驶员信息
*
* @author 20412
*/
@Component("driverJob")
@Slf4j
public class DriverJob implements InitializingBean {
@Resource
private NowSchedulingCache nowSchedulingCache;
@Autowired
private DriverSchedulingExpandMapper expandMapper;
@Autowired
private RedisCache redisCache;
@Resource
private SchedulingCache schedulingCache;
@Resource
EquipmentMapper equipmentMapper;
@Resource
private RestTemplate restTemplate;
@Resource
private ThreadJobService threadJobService;
@Autowired
private RuleNumSettingService ruleNumSettingService;
@Autowired
private DriverSchedulingExpandSmartService driverSchedulingExpandSmartService;
@Autowired
private IDriverService driverService;
@Autowired
private RuleAttendanceMainService attendanceMainService;
@Autowired
private LinggangSchedulingService schedulingService;
@Autowired
private LinggangKeyWorkLocationService keyWorkLocationService;
@Value("${api.url.getDriverInfo}")
private String getDriverInfoUrl;
@Value("${api.personnel.token.tokenUrl}")
private String tokenUrl;
@Value("${api.personnel.token.appKey}")
private String appKey;
@Value("${api.personnel.token.appSecret}")
private String appSecret;
@Value("${api.url.getSchedulingInfoNew}")
private String getSchedulingInfoUrl;
@Value("${api.url.getSchedulingInfoPlan}")
private String getSchedulingInfoPlan;
@Value("${api.config.password}")
private String password;
@Value("${api.config.nonce}")
private String nonce;
@Autowired
private SchedulerProperty property;
private static DriverSchedulingExpandMapper EXPAND_MAPPER;
private static DriverSchedulingExpandSmartService EXPAND_SMART_SERVICE;
private static RuleNumSettingService RULE_NUM_SETTING_SERVICE;
private static RuleAttendanceMainService ATTENDANCE_MAIN_SERVICE;
private static NowSchedulingCache NOW_SCHEDULING_CACHE;
private static ThreadJobService THREAD_JOB_SERVICE;
private static SchedulingCache SCHEDULING_CACHE;
private static EquipmentMapper EQUIPMENT_MAPPER;
private static String APP_KEY;
private static String TOKEN_URL;
private static String APP_SECRET;
private static IDriverService DRIVER_SERVICE;
private static RedisCache REDIS_CACHE;
private static RestTemplate RESTTEMPLATE;
private static String GET_SCHEDULING_INFO_URL;
private static String GET_DRIVER_INFO_URL;
private static String PASSWORD;
private static String NONCE;
/**
* 通过该定时任务获取驾驶员信息 并保存到数据库
*/
public void getDriverInfo(String params) throws Exception {
try {
// String getDriverInfoUrl = String.format(GET_DRIVER_INFO_URL, params);
//获取token
log.info("开始获取人事接口token");
TokenResponseVo tokenVo = getToken(TOKEN_URL);
log.info("获取人事接口token完毕");
// 获取驾驶员信息
log.info("开始获取驾驶员信息");
getDrivers(tokenVo.getAccessToken());
log.info("获取驾驶员信息结束");
} catch (Exception e) {
log.info("执行失败:" + e.getMessage());
}
log.info("执行结束");
}
private static void saveDrivers(List<Driver> drivers, String accessToken) {
// 多线程插入数据
log.info("开始插入");
THREAD_JOB_SERVICE.asyncUploadDriverWithUpdateImageUrl(drivers, accessToken);
// String downloadImage = getDownloadImage(url, accessToken, "");
}
// public static void main(String[] args) {
// String str = "[{\"previewUrl\":\"/ossFileHandle?appType=APP_HV8J7X8PFRXLJJW8JTZK&fileName=APP_HV8J7X8PFRXLJJW8JTZK_bWFuYWdlcjgxNF9QRTg2Nk1EMThYTUNaNkxVN002QTQ3N0hQV0E2MlNYMTMwQ0tMQTQ$.png&instId=&type=open&process=image/resize,m_fill,w_200,h_200,limit_0/quality,q_80\",\"size\":621992,\"name\":\"0332d25e3b9e80bca3d90daf0d5857d.png\",\"downloadUrl\":\"/ossFileHandle?appType=APP_HV8J7X8PFRXLJJW8JTZK&fileName=APP_HV8J7X8PFRXLJJW8JTZK_bWFuYWdlcjgxNF9QRTg2Nk1EMThYTUNaNkxVN002QTQ3N0hQV0E2MlNYMTMwQ0tMQTQ$.png&instId=&type=download\",\"fileUuid\":\"APP_HV8J7X8PFRXLJJW8JTZK_bWFuYWdlcjgxNF9QRTg2Nk1EMThYTUNaNkxVN002QTQ3N0hQV0E2MlNYMTMwQ0tMQTQ$.png\",\"url\":\"/ossFileHandle?appType=APP_HV8J7X8PFRXLJJW8JTZK&fileName=APP_HV8J7X8PFRXLJJW8JTZK_bWFuYWdlcjgxNF9QRTg2Nk1EMThYTUNaNkxVN002QTQ3N0hQV0E2MlNYMTMwQ0tMQTQ$.png&instId=&type=download\"}]";
//// List<List> lists = JSONArray.parseArray(str, List.class);
// List<ImageField_lk9mk228> lists = JSONArray.parseArray(str, ImageField_lk9mk228.class);
// System.out.println(lists);
// }
public static String getDownloadImageUrl(String accessToken, String preViewUrl) {
accessToken = REDIS_CACHE.getCacheObject(REDIS_PERSONNEL_TOKEN);
String url = "https://api.dingtalk.com/v1.0/yida/apps/temporaryUrls/APP_HV8J7X8PFRXLJJW8JTZK";
String fileUrl = "https://scroix.aliwork.com";
try {
fileUrl = URLEncoder.encode(fileUrl + preViewUrl, String.valueOf(StandardCharsets.UTF_8));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
url = url + "?userId=InterfaceManagement&timeout=7200000&fileUrl=" + fileUrl + "&systemToken=16A66291CHE9K5DPE1IDO9E63FOE2VWA09QFLV";
Map<String, Object> param = new HashMap<>();
param.put("userId", "InterfaceManagement");
param.put("timeout", 7200000L);
param.put("fileUrl", fileUrl);
param.put("systemToken", "16A66291CHE9K5DPE1IDO9E63FOE2VWA09QFLV");
Map<String, String> header = new HashMap<>();
header.put("x-acs-dingtalk-access-token", accessToken);
header.put("Content-Type", "application/json");
String result = "";
try {
String body = HttpUtil.createGet(url).addHeaders(header).form(new HashMap<>()).execute().body();
result = JSON.parseObject(body, ImageUrlResultResponseVo.class).getResult();
// 可能需要重新获取token
} catch (Exception e) {
String token = DriverJob.getToken(TOKEN_URL).getAccessToken();
header.put("x-acs-dingtalk-access-token", token);
String body = HttpUtil.createGet(url).addHeaders(header).form(new HashMap<>()).execute().body();
ImageUrlResultResponseVo vo = JSON.parseObject(body, ImageUrlResultResponseVo.class);
result = vo.getResult();
}
return result;
}
// 弃用 无用方法
@Deprecated
public void clearExceptionYesterdayRecord() {
// 获取当前日期时间
Calendar calendar = Calendar.getInstance();
// 将日期减去一天
calendar.add(Calendar.DAY_OF_MONTH, -1);
// 获取昨天的日期时间
Date yesterday = calendar.getTime();
String dateKey = REDIS_SIGN_IN_DRIVER_ALCOHOL_OVERFLOW + ConstDateUtil.formatDate(yesterday);
log.info("开始清除昨天的异常数据:{}", dateKey);
REDIS_CACHE.deleteObject(dateKey);
log.info("清除昨天的异常数据完成:{}", dateKey);
}
/**
* 获取排班任务请求
* 24小时执行一次
*/
@Transactional(rollbackFor = Exception.class)
public void getSchedulingInfo() {
Date date = new Date();
for (int i = 0; i < 2; i++) {
JwtAuthenticationTokenFilter.putMDC("job", JwtAuthenticationTokenFilter.getRandomValue());
runScheduling(DateUtils.addDays(date, i).getTime());
}
}
public void runScheduling(long timeLong) {
long timestamp = System.currentTimeMillis();
Date date = new Date(timeLong);
String formatDate = DateUtil.YYYY_MM_DD.format(date);
String timeOut = DateUtil.HH_MM_ss.format(date);
log.info("获取排班任务触发时间:{}", formatDate);
// 获取排班请求
String getSchedulingInfoUrl = null;
log.info("开始获取{}的排班数据", formatDate);
boolean isSameDay = DateUtils.isSameDay(new Date(), date);
String url = isSameDay ? GET_SCHEDULING_INFO_URL : getSchedulingInfoPlan;
int type = isSameDay ? 1 : 100;
LinggangScheduling scheduling = new LinggangScheduling();
scheduling.setStartScheduleDate(DateUtil.shortDate(date));
scheduling.setEndScheduleDate(DateUtils.addDays(scheduling.getStartScheduleDate(), 1));
Set<Long> idSets = null;
if (isSameDay) {
String key = "Scheduling:timeStr:" + formatDate;
long timestampValu = timestamp;
if (!redisCache.hasKey(key)) {
redisCache.setCacheObject(key, "1", 30, TimeUnit.HOURS);
timestampValu = 0;
}
scheduling.setType(100);
List<LinggangScheduling> linggangSchedulings = schedulingService.list(scheduling);
idSets = linggangSchedulings.stream().map(LinggangScheduling::getId).collect(Collectors.toSet());
try {
log.info("url:[{}];formatDate:[{}];timestamp:[{}]", url, formatDate, timestamp);
getSchedulingInfoUrl = String.format(url, "77", formatDate, timestampValu, timestamp, NONCE, PASSWORD, getSHA1(getStringStringMap(String.valueOf(timestamp))));
} catch (Exception e) {
throw new RuntimeException(e);
}
} else {
try {
log.info("url:[{}];formatDate:[{}];timestamp:[{}]", url, formatDate, timestamp);
getSchedulingInfoUrl = String.format(url, "77", formatDate, timestamp, NONCE, PASSWORD, getSHA1(getStringStringMap(String.valueOf(timestamp))));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// String url = getSchedulingInfoPlan;
String requestId = JwtAuthenticationTokenFilter.getRequestIdOfMDCValue();
// 获取排班信息并存入redis
saveSchedulingToRedis(getSchedulingInfoUrl, formatDate, timeOut, date, type, idSets, requestId);
// 删除两天前排班信息
if (isSameDay) {
deleteScheduling();
}
log.info("获取{}的排班数据完毕", formatDate);
}
private void deleteScheduling() {
String nowDate = ConstDateUtil.formatDate(new Date());
String yesterdayDate = ConstDateUtil.formatDate(ConstDateUtil.getTheSpecifiedNumberOfDaysOfTime(-1));
String nowKey = DRIVER_SCHEDULING_PRE + nowDate;
String yesterdayKey = DRIVER_SCHEDULING_PRE + yesterdayDate;
// 考情keys
List<String> nowKeys = NOW_SCHEDULING_CACHE.getKes();
// 实时keys
List<String> keys = SCHEDULING_CACHE.getKeys();
// 删除实时排班
for (int i = 0; i < keys.size(); i++) {
if (nowKey.equals(keys.get(i)) || yesterdayKey.equals(keys.get(i))) {
continue;
}
SCHEDULING_CACHE.removeCacheSchedulingByKey(keys.get(i));
}
// 删除考勤
for (int i = 0; i < nowKeys.size(); i++) {
if (nowDate.equals(nowKeys.get(i)) || yesterdayDate.equals(nowKeys.get(i))) {
continue;
}
NOW_SCHEDULING_CACHE.removeCacheSchedulingByKey(nowKeys.get(i));
}
}
/**
* 计算是否全部设备完成了对应的用户人脸注册
*/
public void computedFaceSignIn() {
DRIVER_SERVICE.updateDriverByComputed();
}
/**
* 计算异常班次 : 当前应当打卡但是未打卡人员
*/
public void computedExceptionScheduling() {
DRIVER_SERVICE.computedExceptionScheduling();
}
/**
* 计算灵活跟班
*/
public void computedExpandSmart() {
EXPAND_SMART_SERVICE.computedExpand();
}
/**
* 生成排班 每天早上在获取调度排班前生成
*/
public void createAttendance() {
RULE_NUM_SETTING_SERVICE.createAttendance();
}
/**
* 工具任务 手动把非司售人员的排班加入到签到报表缓存 可以把当天生成的排班明细没有来得及加入签到报表的员工手动加入
*/
public void manualAddBcCache() {
RULE_NUM_SETTING_SERVICE.manualAddBcCache();
}
/**
* 计算设备在线状态 5 分钟一次
*/
public void computedDeviceOnlineStatus(String date) throws IOException, ClassNotFoundException {
List<Equipment> list = EQUIPMENT_MAPPER.selectEquipmentList(null);
List<Equipment> original = ListUtils.deepCopy(list);
Long checkTime = StringUtils.isEmpty(date) ? DEVICE_OFFLINE_TIME : Long.parseLong(date);
for (Equipment equipment : list) {
if (Objects.isNull(equipment.getLastHeartRes())) {
equipment.setOnlineClient(DEVICE_OFFLINE);
} else {
LocalDateTime time = ConstDateUtil.getLocalDateTimeByLongTime(equipment.getLastHeartRes().getTime());
LocalDateTime nowTime = LocalDateTime.now();
long timeout = ChronoUnit.MINUTES.between(time, nowTime);
if (checkTime.compareTo(timeout) < 0) {
equipment.setOnlineClient(DEVICE_OFFLINE);
} else {
equipment.setOnlineClient(DEVICE_ONLINE);
}
}
}
// 更新日志
THREAD_JOB_SERVICE.asyncInsertEquipmentLog(list, original);
EQUIPMENT_MAPPER.updateEquipments(list);
}
public Map<String, List<ResponseSchedulingDto>> saveSchedulingToRedis(String getSchedulingInfoUrl, String dateKey, String timeOut, Date date, int type, Set<Long> idSets, String requestId) {
JwtAuthenticationTokenFilter.putMDC("job", requestId);
log.info("开始拉取排班:{};[{}]", dateKey, getSchedulingInfoUrl);
List<ResponseSchedulingDto> originSchedulingList = schedulingCache.requestScheduling(getSchedulingInfoUrl);
log.info("originSchedulingList:[{}]", JSON.toJSONString(originSchedulingList));
Map<String, List<ResponseSchedulingDto>> driverSchedulingMap = new HashMap<>(200);
// 以员工号为key存入排班集合
originSchedulingList.stream().forEach(item -> {
// 员工号为key
String[] infos = item.getJsy().split("/");
String driverJobCode = infos[0];
String driverName = infos[1];
String salePersonJobCode = item.getSpy().split("/").length > 0 ? item.getSpy().split("/")[0] : null;
String salePersonName = item.getSpy().split("/").length > 0 ? item.getSpy().split("/")[1] : null;
splitSaveScheduling(driverSchedulingMap, driverJobCode, driverName, item, PERSONNEL_POSTS_DRIVER);
splitSaveScheduling(driverSchedulingMap, salePersonJobCode, salePersonName, item, PERSONNEL_POSTS_SALES);
});
// 处理跟班
handlerBcCopy(driverSchedulingMap);
// 排序
List<String> keys = new ArrayList<>(driverSchedulingMap.keySet());
for (String key : keys) {
List<ResponseSchedulingDto> schedulingList = driverSchedulingMap.get(key);
if (CollectionUtils.isNotEmpty(schedulingList)) {
schedulingList = schedulingList.stream().map(s -> {
if (Objects.isNull(s.getFcsjT())) {
s.setFcsjT(0L);
}
if (Objects.isNull(s.getZdsjT())) {
s.setZdsjT(0L);
}
return s;
}).collect(Collectors.toList());
}
schedulingList.sort(Comparator.comparing(ResponseSchedulingDto::getFcsjT));
}
// 存入签到报表
THREAD_JOB_SERVICE.asyncComputedScheduling(driverSchedulingMap, timeOut, date, type, idSets, requestId);
// 实时排班直接存入缓存
SCHEDULING_CACHE.setCacheScheduling(DRIVER_SCHEDULING_PRE + dateKey, driverSchedulingMap);
log.info("拉取排班完毕:{}", dateKey);
return driverSchedulingMap;
}
private void handlerBcCopy(Map<String, List<ResponseSchedulingDto>> driverSchedulingMap) {
try {
LocalDate localDate = LocalDate.now();
DriverSchedulingExpand qwExpand = new DriverSchedulingExpand();
qwExpand.setStatus(STATUS_NORMAL.longValue());
List<ExpandResponseVo> expandList = EXPAND_MAPPER.queryExpandListByEntity(qwExpand);
for (ExpandResponseVo expand : expandList) {
List<ResponseSchedulingDto> dtoList = driverSchedulingMap.get(expand.getMasterJobCode());
if (CollectionUtil.isNotEmpty(dtoList) && localDate.compareTo(LocalDate.parse(ConstDateUtil.formatDate("yyyy-MM-dd", expand.getEndDate()))) <= 0) {
List<ResponseSchedulingDto> list = ListUtils.deepCopy(dtoList);
list = list.stream().peek(item -> {
item.setJobCode(expand.getSlaveJobCode());
item.setPosts(expand.getSlavePosts());
item.setName(expand.getSlaveName());
}).collect(Collectors.toList());
driverSchedulingMap.put(expand.getSlaveJobCode(), list);
}
}
} catch (Exception e) {
log.info("创建跟班失败原因:{}", e.getMessage());
}
}
private void splitSaveScheduling(Map<String, List<ResponseSchedulingDto>> driverSchedulingMap, String jobCode, String name, ResponseSchedulingDto item, String posts) {
if (!Objects.isNull(jobCode)) {
ResponseSchedulingDto scheduling = new ResponseSchedulingDto();
BeanUtils.copyProperties(item, scheduling);
scheduling.setPosts(posts);
scheduling.setJobCode(jobCode);
scheduling.setName(name);
if (Objects.isNull(driverSchedulingMap.get(jobCode))) {
List<ResponseSchedulingDto> oneDriverScheduling = new ArrayList<>();
oneDriverScheduling.add(scheduling);
driverSchedulingMap.put(jobCode, oneDriverScheduling);
} else {
driverSchedulingMap.get(jobCode).add(scheduling);
}
}
}
public static void getDrivers(String accessToken) throws Exception {
Date date = new Date();
int pageSize = 100;
PersonnelResultResponseVo vo = getPersonInfo(accessToken, pageSize, 1);
int countPage = vo.getTotalCount() / pageSize;
countPage = vo.getTotalCount() % pageSize == 0 ? countPage : countPage + 1;
List<Driver> drivers = handlerDrivers(date, vo);
for (int i = 2; i <= countPage; i++) {
drivers.addAll(handlerDrivers(date, getPersonInfo(accessToken, 100, i)));
}
List<String> jobList = drivers.stream().map(Driver::getJobCode).distinct().collect(Collectors.toList());
// 删除离职员工
handleNotEmptyJob(jobList);
// 更新人事人员信息 防止信息不匹配
updatePersonalInfo(drivers);
// 过滤已经存在的员工工号
drivers = filterEmptyJob(drivers, jobList);
List<List<Driver>> splitList = ListUtils.splitList(drivers, 200);
for (List<Driver> driverList : splitList) {
saveDrivers(driverList, accessToken);
}
}
private static void updatePersonalInfo(List<Driver> drivers) {
// 查询现有信息 用stream过滤 筛选出需要更新的drivers
List<Driver> allDriverList = DRIVER_SERVICE.selectDriverListAll();
Map<String, Driver> driverMap = new HashMap<>();
for (Driver driver : drivers) {
if (driverMap.get(driver.getJobCode()) == null) {
driverMap.put(driver.getJobCode(), driver);
} else {
System.out.println(driver);
}
}
// 过滤出需要更新的driver
List<Driver> updateDriverList = allDriverList.stream()
// 过滤暂时没有保存的人员
.filter(item -> driverMap.get(item.getJobCode()) != null)
// 过滤全部一致的人员信息
.filter(item -> !item.equals(driverMap.get(item.getJobCode())))
.map(item -> {
Driver driver = driverMap.get(item.getJobCode());
item.setLineName(driver.getLineName());
item.setPersonnelName(driver.getPersonnelName());
item.setFleetName(driver.getFleetName());
item.setPosts(driver.getPosts());
return item;
})
// 保留需要更新的driver
.collect(Collectors.toList());
// 更新表
ATTENDANCE_MAIN_SERVICE.updateAttendanceMainByJobCode(updateDriverList);
DRIVER_SERVICE.updateDrivers(updateDriverList);
}
private static List<Driver> filterEmptyJob(List<Driver> drivers, List<String> jobList) {
List<String> jobs = DRIVER_SERVICE.queryEmptyJob(jobList);
Map<String, String> jobMap = new HashMap<>(jobs.size());
for (String job : jobs) {
jobMap.put(job, job);
}
// 过滤
return drivers.stream().filter(item -> StringUtils.isEmpty(jobMap.get(item.getJobCode()))).collect(Collectors.toList());
}
private static void handleNotEmptyJob(List<String> jobList) {
DRIVER_SERVICE.deleteNotEmptyJob(jobList);
}
public static List<Driver> handlerDrivers(Date date, PersonnelResultResponseVo vo) {
List<Driver> drivers = vo.getData().stream().map(item -> {
Driver driver = new Driver();
FormData formData = item.getFormData();
driver.setUpdateTime(date);
driver.setJobCode(formData.getTextField_lk9mk222());
driver.setPersonnelName(formData.getTextField_lk9mk224());
driver.setPosts(formData.getTextField_lk9mk226());
// 解析JSON字符串
List<ImageField_lk9mk228> lists = JSONArray.parseArray(formData.getImageField_lk9mk228(), ImageField_lk9mk228.class);
driver.setImage(CollectionUtil.isNotEmpty(lists) ? lists.get(0).getPreviewUrl() : "");
driver.setLineName(formData.getTextField_lkmgdvnu());
driver.setFleetName(formData.getTextField_lkmgdvnv());
return driver;
}).collect(Collectors.toList());
return drivers;
}
public static PersonnelResultResponseVo getPersonInfo(String accessToken, Integer pageSize, Integer currentPage) {
RestTemplate restTemplate = new RestTemplate();
String url = "https://api.dingtalk.com/v1.0/yida/forms/instances/search";
PersonnelRequestVo vo = new PersonnelRequestVo();
vo.setAppType("APP_HV8J7X8PFRXLJJW8JTZK");
vo.setFormUuid("FORM-D2B665D1LQMCRRGS9WE6F54QTVYF25BXHM9KL4");
vo.setUserId("InterfaceManagement");
vo.setSystemToken("16A66291CHE9K5DPE1IDO9E63FOE2VWA09QFLV");
vo.setCurrentPage(currentPage);
vo.setPageSize(pageSize);
// 工号组件
// vo.setSearchFieldJson(" size = 4");
// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("x-acs-dingtalk-access-token", accessToken);
// 创建HttpEntity对象
HttpEntity<String> requestEntity = new HttpEntity<>(JSON.toJSONString(vo), headers);
// 发送POST请求
ResponseEntity<PersonnelResultResponseVo> result = restTemplate.postForEntity(url, requestEntity, PersonnelResultResponseVo.class);
PersonnelResultResponseVo body = result.getBody();
return body;
}
public static TokenResponseVo getToken(String url) {
TokenRequestVo request = new TokenRequestVo();
request.setAppKey(APP_KEY);
request.setAppSecret(APP_SECRET);
String requestBody = JSON.toJSONString(request);
// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
// 创建HttpEntity对象
HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);
// 发送POST请求
ResponseEntity<TokenResponseVo> responseEntity = RESTTEMPLATE.postForEntity(url, requestEntity, TokenResponseVo.class);
TokenResponseVo vo = responseEntity.getBody();
REDIS_CACHE.setCacheObject(REDIS_PERSONNEL_TOKEN, vo.getAccessToken(), vo.getExpireIn(), TimeUnit.SECONDS);
return vo;
}
public Map<String, String> getStringStringMap(String timestamp) {
Map<String, String> configMap = new HashMap<>(5);
configMap.put("timestamp", String.valueOf(timestamp));
configMap.put("nonce", NONCE);
configMap.put("password", PASSWORD);
return configMap;
}
/**
* 获取签名
*
* @param map
* @return
* @throws Exception
*/
public String getSHA1(Map<String, String> map) throws Exception {
try {
String[] array = new String[map.size()];
map.values().toArray(array);
StringBuffer sb = new StringBuffer();
// 字符串排序
Arrays.sort(array);
for (int i = 0; i < array.length; i++) {
sb.append(array[i]);
}
String str = sb.toString();
// SHA1签名生成
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(str.getBytes());
byte[] digest = md.digest();
StringBuffer hexstr = new StringBuffer();
String shaHex = "";
for (int i = 0; i < digest.length; i++) {
shaHex = Integer.toHexString(digest[i] & 0xFF);
if (shaHex.length() < 2) {
hexstr.append(0);
}
hexstr.append(shaHex);
}
return hexstr.toString();
} catch (Exception e) {
throw e;
}
}
@Override
public void afterPropertiesSet() throws Exception {
GET_DRIVER_INFO_URL = getDriverInfoUrl;
NONCE = nonce;
PASSWORD = password;
RESTTEMPLATE = restTemplate;
DRIVER_SERVICE = driverService;
REDIS_CACHE = redisCache;
GET_SCHEDULING_INFO_URL = getSchedulingInfoUrl;
THREAD_JOB_SERVICE = threadJobService;
TOKEN_URL = tokenUrl;
APP_KEY = appKey;
APP_SECRET = appSecret;
SCHEDULING_CACHE = schedulingCache;
EQUIPMENT_MAPPER = equipmentMapper;
NOW_SCHEDULING_CACHE = nowSchedulingCache;
RULE_NUM_SETTING_SERVICE = ruleNumSettingService;
EXPAND_MAPPER = expandMapper;
ATTENDANCE_MAIN_SERVICE = attendanceMainService;
EXPAND_SMART_SERVICE = driverSchedulingExpandSmartService;
}
}