nidapeng
2024-03-19 6c40e04eb7c2060feb2533735cd3089d438965e5
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
package com.doumee.service.business.impl.hksync;
 
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.doumee.biz.system.SystemDictDataBiz;
import com.doumee.core.constants.ResponseStatus;
import com.doumee.core.exception.BusinessException;
import com.doumee.core.haikang.model.HKConstants;
import com.doumee.core.haikang.model.param.BaseListPageResponse;
import com.doumee.core.haikang.model.param.BaseResponse;
import com.doumee.core.haikang.model.param.request.*;
import com.doumee.core.haikang.model.param.request.event.visit.EventVisitInfoRequest;
import com.doumee.core.haikang.model.param.respose.*;
import com.doumee.core.haikang.service.HKService;
import com.doumee.core.utils.Constants;
import com.doumee.core.utils.DESUtil;
import com.doumee.core.utils.DateUtil;
import com.doumee.core.utils.ImageBase64Util;
import com.doumee.core.wx.wxPlat.WxPlatNotice;
import com.doumee.dao.business.DeviceRoleMapper;
import com.doumee.dao.business.RetentionMapper;
import com.doumee.dao.business.join.VisitsJoinMapper;
import com.doumee.dao.business.model.DeviceRole;
import com.doumee.dao.business.model.Member;
import com.doumee.dao.business.model.Retention;
import com.doumee.dao.business.model.Visits;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import java.util.*;
 
/**
 * 海康访客业务Service实现
 * @author 江蹄蹄
 * @date 2023/11/30 15:33
 */
@Service
@Slf4j
public class HkSyncVisitServiceImpl extends HkSyncBaseServiceImpl {
    @Autowired
    private VisitsJoinMapper visitsMapper;
    @Autowired
    private RetentionMapper retentionMapper;
    @Autowired
    private SystemDictDataBiz systemDictDataBiz;
    @Autowired
    private DeviceRoleMapper deviceRoleMapper;
    @Autowired
    private WxPlatNotice wxPlatNotice;
    /**
     * 同步海康访客信息,根据erp同步组织结果,定时检查需要下发到海康的组织信息
     */
    @Override
    public void getOutTimeVisitRecord(){
        if(Constants.DEALING_HK_VISIT_EXPIRE){
            return   ;
        }
        Constants.DEALING_HK_VISIT_EXPIRE =true;
        try {
            //查询所有需要同步的数据
            List<Visits> list = getExpireVisitList();
            //按照父级申请分批处理每次申请数据
            if(list ==null || list.size()==0){
                return;
            }
            Date date = new Date();
            for(Visits c : list) {
                //发起海康预约接口(需要登记),根据预约返回接口封装申请记录更新字段
                AppointmentInfoResponse model =  getVisitRecord(c.getHkId());
                if(model == null){
                    Visits update = new Visits();
                    //已失效
                    update.setStatus(Constants.VisitStatus.invalid);
                    update.setEditDate(date);
                    update.setId(c.getId());
                    update.setRemark("预约已被清除");
                    visitsMapper.updateById(update);
                    continue;
                }
                /**
                 *      * 0:待审核(预约待审批)、
                 *      * 1:正常(预约成功或预约审批成功后<未登记>:当前时间未超过预计来访时间)、
                 *      * 2:迟到(预约成功或预约审批成功后<未登记>:当前时间超过预计来访时间,但未超过预计离开时间)、
                 *      * 3:失效(预约成功或预约审批成功后<未登记>:当前时间已超过预计离开时间)、
                 *      * 4:审核退回(预约待审批,审批人员审批退回)、
                 *      * 5:超期自动签离(超期未签离记录访客,由后台任务定时处理签离)、
                 *      * 6:已签离(访客签离)、
                 *      * 7:超期未签离(访客登记,当前时间已超过预计离开时间,还未进行签离)、
                 *      * 8:已到达;(访客登记,当前时间未超过预计离开时间)、
                 *      * 9:审核失效(预约待审批,一直到当前时间超过预计离开时间,还未审批通过)、
                 *      * 10:邀约中(员工发起邀约,访客还未应邀)、
                 *      * 11:邀约失效(员工发起邀约,一直到当前时间超过预计离开时间,访客还未应邀)
                 */
                if (model.getVisitorStatus()!=null && ",3,4,11,".contains( ","  +model.getVisitorStatus()+"," )){
                    //对相应状态下的数据进行【已失效】处理
                    Visits update = new Visits();
                    //已失效
                    update.setStatus(Constants.VisitStatus.invalid);
                    update.setEditDate(date);
                    update.setId(c.getId());
                    update.setInDate(DateUtil.getISO8601DateByStr2(model.getVisitStartTime()));
                    update.setOutDate(DateUtil.getISO8601DateByStr2(model.getVisitEndTime()));
                    update.setRemark("超时未登记");
                    visitsMapper.updateById(update);
                }
                if (model.getVisitorStatus()!=null && ",5,6,".contains( ","  +model.getVisitorStatus()+"," )){
                    // 对相应状态下的数据进行【已签离】处理
                    if(!Constants.equalsInteger(c.getStatus(),Constants.VisitStatus.signout)){
                        Visits update = new Visits();
                        //已失效
                        update.setStatus(Constants.VisitStatus.signout);
                        update.setEditDate(date);
                        update.setId(c.getId());
                        update.setInDate(DateUtil.getISO8601DateByStr2(model.getVisitStartTime()));
                        update.setOutDate(DateUtil.getISO8601DateByStr2(model.getVisitEndTime()));
                        update.setRemark("已签离");
                        visitsMapper.updateById(update);
 
                        //先删除原有的在场人员(普通访客)
                        retentionMapper.delete(new UpdateWrapper<Retention>().lambda()
                                .eq(Retention::getType,Constants.memberType.visitor)
                                .eq(Retention::getMemberId,c.getMemberId()));
                    }
                }
                if (model.getVisitorStatus()!=null&& ",7,8,".contains( ","  +model.getVisitorStatus()+"," )){
                    //如果已登记
                    if(!Constants.equalsInteger(c.getStatus(),Constants.VisitStatus.signin)){
                        Visits update = new Visits();
                        //已失效
                        update.setStatus(Constants.VisitStatus.signin);
                        update.setEditDate(date);
                        update.setId(c.getId());
                        update.setInDate(DateUtil.getISO8601DateByStr2(model.getVisitStartTime()));
                        update.setOutDate(DateUtil.getISO8601DateByStr2(model.getVisitEndTime()));
                        update.setRemark("超时未签到");
                        visitsMapper.updateById(update);
                        //先删除原有的在场人员(普通访客)
                        retentionMapper.delete(new UpdateWrapper<Retention>().lambda()
                                .eq(Retention::getType,Constants.memberType.visitor)
                                .eq(Retention::getMemberId,c.getMemberId()));
                        //再插入最新的在厂人员
                        retentionMapper.insert(getRetentionModelByVisitRequest(c,update.getInDate()));
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            Constants.DEALING_HK_VISIT_EXPIRE =false;
        }
    }
 
    private Retention getRetentionModelByVisitRequest(Visits visits,Date date) {
        Retention retention = new Retention();
        retention.setIsdeleted(Constants.ZERO);
        retention.setCreateDate(date);
        retention.setClasses(visits.getClasses());
        retention.setCode(visits.getCode());
        retention.setIdcardNo(visits.getIdcardNo());
        retention.setIdcardDecode(visits.getIdcardDecode());
        retention.setName(visits.getName());
        retention.setBirthday(visits.getBirthday());
        retention.setType(visits.getMemberType());
        retention.setCompanyId(visits.getCompanyId());
        retention.setCompanyName(visits.getCompanyName());
        retention.setEventDate(retention.getCreateDate());
        retention.setFaceImg(visits.getFaceImg());
        retention.setImgurl(visits.getImgurl());
        retention.setPhone(visits.getPhone());
        retention.setMemberId(visits.getMemberId());
 
        return retention;
    }
 
    public AppointmentInfoResponse getVisitRecord(String orderId){
        //分页遍历循环查询所有门禁设备数据
        if(StringUtils.isBlank(orderId)){
            return  null;
        }
        AppointmentListRequest param =  new AppointmentListRequest();
        param.setPageNo(1);
        param.setPageSize(1);
        param.setOrderId(orderId);
        BaseResponse<BaseListPageResponse<AppointmentInfoResponse>> response = HKService.appointmentRecords(param);
        if(response == null || !StringUtils.equals(response.getCode(), HKConstants.RESPONSE_SUCCEE)  ){
           return null;
        }
        if(response.getData() == null || response.getData().getList() == null|| response.getData().getList().size() ==0){
           return  null;
        }
        return response.getData().getList().get(0);
    }
    @Override
    public  void syncVisitData(){
        if(Constants.DEALING_HK_VISIT){
            return   ;
        }
        Constants.DEALING_HK_VISIT =true;
        String path = systemDictDataBiz.queryByCode(Constants.FTP,Constants.FTP_RESOURCE_PATH).getCode()
                +systemDictDataBiz.queryByCode(Constants.FTP,Constants.MEMBER_IMG).getCode();
        List<DeviceRole> roleList = deviceRoleMapper.selectList(new QueryWrapper<DeviceRole>().lambda()
                .eq(DeviceRole::getType, Constants.ONE));
        //标记是否走免登记预约
//        String applyType =systemDictDataBiz.queryByCode(Constants.SYSTEM,Constants.MDJ_VISIT_REQUIRED).getCode();
//        String applyLwType =systemDictDataBiz.queryByCode(Constants.SYSTEM,Constants.MDJ_LW_REQUIRED).getCode();
        try {
            //查询所有需要同步的数据
            List<Visits> list = getVisitList();
            //按照父级申请分批处理每次申请数据
//            List<Visits> list = getParentList(alllist);
            if(list ==null || list.size()==0){
                return;
            }
            Date date = new Date();
            for(Visits c : list) {
                //发起海康预约接口(需要登记),根据预约返回接口封装申请记录更新字段
                getUpdateModelByResponse(c,date,roleList,path);
                visitsMapper.updateById(c);
                if(Objects.isNull(c.getParentId())){
                    wxPlatNotice.sendVisitAuditTemplateNotice(c,
                            systemDictDataBiz.queryByCode(Constants.WX_PLATFORM,Constants.WX_PLATFORM_PREFIX).getCode(),
                            systemDictDataBiz.queryByCode(Constants.WX_PLATFORM,Constants.WX_PLATFORM_AUDIT_VISIT).getCode());
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            Constants.DEALING_HK_VISIT =false;
        }
    }
 
    private List<Visits> getParentList(List<Visits> alllist) {
        if(alllist ==null || alllist.size()==0){
            return null;
        }
        List<Visits> list = new ArrayList<>();
 
        for (Visits v : alllist){
            if(v.getParentId() == null){
                v.setVisitsList(getChildListByParentId(v.getId(),alllist));
                list.add(v);
            }
        }
        return  list;
    }
 
    private List<Visits> getChildListByParentId(Integer id, List<Visits> alllist) {
 
        List<Visits> list = new ArrayList<>();
 
        for (Visits v : alllist){
            if(Constants.equalsInteger(v.getParentId(),id)){
                list.add(v);
            }
        }
        return  list;
    }
 
    /**
     * 根据预约返回接口封装申请记录更新字段
     * @param c
     * @param date
     * @param date
     * @param type 0需要登记 1免登记
     */
    private void getUpdateModelByResponse(  Visits c,Date date, List<DeviceRole> roleList,String path ) {
        String code = null;
        String id = null;
        String qrcode = null;
        String reson = "";
        //发起海康预约接口
        if(Constants.equalsInteger(c.getVisitType(),Constants.ZERO)){
            //(需要登记)
            c.setVisitType(Constants.ZERO);
            VisitAppointmentRequest request =  getHkRequestPara(c,roleList,path);
            if(request == null){
                //海康下发成功
                c.setStatus(Constants.VisitStatus.xfFail);//下发海康失败
                c.setRemark("下发海康参数不正确!");
                c.setHkStatus(Constants.ONE);
                c.setHkDate(date);
                return;
            }
            BaseResponse<VisitAppointmentResponse> response =  HKService.visitAppiontment(request);
            code =response!=null ?response.getCode():null;
            if((response!=null && response.getData()!=null
                    && response.getData().getAppointmentInfoList() !=null
                    && response.getData().getAppointmentInfoList().size()>0)){
                id =response.getData().getAppointmentInfoList().get(0).getOrderId();
                qrcode =response.getData().getAppointmentInfoList().get(0).getQRCode();
            }
            reson = response!=null?JSONObject.toJSONString(response):"";
        }else{
            //免登记
            c.setVisitType(Constants.ONE);
            VisitAppointmentMDJRequest request =getHkMDJRequestPara(c,roleList,path);
            if(request == null){
                //海康下发成功
                c.setStatus(Constants.VisitStatus.xfFail);//下发海康失败
                c.setRemark("下发海康免登记参数不正确!");
                c.setHkStatus(Constants.ONE);
                c.setHkDate(date);
                return;
            }
            BaseResponse<VisitAppointmentMDJResponse> response = HKService.visitAppiontmentMDJ(request );
            code =response!=null ?response.getCode():null;
            if(response!=null && response.getData()!=null){
                id = response.getData().getOrderId();
                qrcode =response.getData().getQRCode();
            }
            reson = response!=null?JSONObject.toJSONString(response):"";
        }
 
        if (code!= null && id!=null) {
            //海康下发成功
            c.setHkId( id);//预约标识
            c.setQrcode(qrcode);
            c.setRemark("下发海康成功!");
            c.setStatus(Constants.VisitStatus.xfSuccess);//下发海康成功
        } else {
            //海康下发失败
            c.setRemark("下发海康失败,原因:"+ reson);
            c.setStatus(Constants.VisitStatus.xfFail);//下发海康失败
        }
        c.setHkStatus(Constants.ONE);
        c.setHkDate(date);
    }
 
    /**
     * 免登记接口参数
     * @param c
     * @return
     */
    private VisitAppointmentMDJRequest getHkMDJRequestPara(Visits c,List<DeviceRole> roleList,String path) {
        VisitAppointmentMDJRequest request = new VisitAppointmentMDJRequest();
        VisitAppointmentVistorRequest info =getRequestInfoByVisit(c,path);
        if(info == null ){
            //人脸为空,不能进行推送
            return  null;
        }
        request.setVisitStartTime(DateUtil.getISO8601Timestamp2(c.getStarttime()));
        request.setVisitEndTime(DateUtil.getISO8601Timestamp2(c.getEndtime()));
        request.setReceptionistId(c.getReceptMemberHkId());//被访人海康编码
        if(StringUtils.isNotBlank(c.getReason())){
            char[] charArray = c.getReason().toCharArray();
            int length = charArray.length;
            if(length>32){
                request.setVisitPurpose(c.getReason().substring(0,32));
            }else{
                request.setVisitPurpose(c.getReason());
            }
        }
        request.setVisitorInfo(info);
        request.setVisitorPermissionSet(getVisitPermissonRequest(roleList,c));
        return  request;
    }
 
    /**
     * 访客权限组
     * @param roleList
     * @param c
     * @return
     */
    private VisitAppointmentPermissonRequest getVisitPermissonRequest(List<DeviceRole> roleList, Visits c) {
        VisitAppointmentPermissonRequest p = new VisitAppointmentPermissonRequest();
        //获取权限组集合
        String[] roles = getHkRoles(c.getDoors(),roleList);
        if(roles==null || roles.length ==0){
            //使用默认访客权限组
            p.setDefaultPrivilegeGroupFlag(Constants.ONE+"");
        }else{
            //指定有效海康访客权限组数据
            p.setDefaultPrivilegeGroupFlag(Constants.ZERO+"");
            p.setPrivilegeGroupIds(roles);
        }
        return  p;
    }
 
    private VisitAppointmentRequest getHkRequestPara(Visits c,List<DeviceRole> roleList,String path ) {
        VisitAppointmentRequest request = new VisitAppointmentRequest();
        //申请人信息
        VisitAppointmentVistorRequest info =getRequestInfoByVisit(c,path);
        if(info == null ){
            //人脸为空,不能进行推送
            return  null;
        }
        request.setVisitStartTime(DateUtil.getISO8601Timestamp(c.getStarttime()));
        request.setVisitEndTime(DateUtil.getISO8601Timestamp(c.getEndtime()));
        request.setReceptionistId(c.getReceptMemberHkId());//被访人海康编码
 
        if(StringUtils.isNotBlank(c.getReason())){
            char[] charArray = c.getReason().toCharArray();
            int length = charArray.length;
            if(length>32){
                request.setVisitPurpose(c.getReason().substring(0,32));
            }else{
                request.setVisitPurpose(c.getReason());
            }
        }
        //获取权限组集合
        request.setVisitorPermissionSet(getVisitPermissonRequest(roleList,c));
        List<VisitAppointmentVistorRequest> infolist = new ArrayList<>();
        infolist.add(info);
        request.setVisitorInfoList(infolist);
        return  request;
    }
 
    private VisitAppointmentVistorRequest getRequestInfoByVisit(Visits c,String path) {
        VisitAppointmentVistorRequest info = new VisitAppointmentVistorRequest();
        //人脸数据
        if(StringUtils.isBlank(c.getName())
                ||StringUtils.isBlank(c.getPhone())
                || StringUtils.isBlank(c.getFaceImg()) ){
            return  null;
        }
        if(StringUtils.isNotBlank(c.getFaceImg())){
            info.setVisitorPhoto(ImageBase64Util.Image2Base64(path+c.getFaceImg()));
        }
        if(info.getVisitorPhoto() == null){
            return  null;
        }
        if(StringUtils.isNotBlank(c.getName())){
            char[] charArray = c.getName().toCharArray();
            int length = charArray.length;
            if(length>32){
                info.setVisitorName(c.getName().substring(0,32));
            }else{
                info.setVisitorName(c.getName());
            }
        }
 
        if(StringUtils.isNotBlank(c.getCompanyName())){
            char[] charArray = c.getCompanyName().toCharArray();
            int length = charArray.length;
            if(length>32){
                info.setVisitorWorkUnit(c.getCompanyName().substring(0,32));
            }else{
                info.setVisitorWorkUnit(c.getCompanyName());
            }
        }
        info.setPhoneNo(c.getPhone());
        info.setPlateNo(c.getCarNos());
        info.setGender(c.getSex()+"");
        if(Constants.equalsInteger(c.getIdcardType(),Constants.ZERO)){
            info.setCertificateType(HKConstants.CertificateType.SHENFENZHENG.getKey()+"");
            info.setCertificateNo(DESUtil.decrypt(Constants.EDS_PWD, c.getIdcardNo()));
        } else if(Constants.equalsInteger(c.getIdcardType(),Constants.TWO)){
            info.setCertificateType(HKConstants.CertificateType.HUZHAO.getKey()+"");
            info.setCertificateNo(DESUtil.decrypt(Constants.EDS_PWD,  c.getIdcardNo()));
        }
 
        return info;
    }
 
    private String[] getHkRoles(String doors, List<DeviceRole> roleList) {
        if(StringUtils.isBlank(doors) || roleList.size()==0|| roleList.size()==0){
            return null;
        }
        String[] ids = doors.split(",");
        List<String> roles = new ArrayList<>();
        for (String s : ids){
            for(DeviceRole r : roleList){
                if(StringUtils.isNotBlank(r.getHkId()) && StringUtils.equals(s,r.getId().toString())){
                    roles.add(r.getHkId());
                }
            }
        }
        return  roles.toArray(new String[]{});
    }
 
    /**
     * 查询所有需要同步的数据
     * @return
     */
    private List<Visits> getVisitList() {
        MPJLambdaWrapper<Visits> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(Visits.class);
        queryWrapper.selectAs(Member::getName,Visits::getReceptMemberName)
                .selectAs(Member::getHkId,Visits::getReceptMemberHkId)
                .leftJoin(Member.class,Member::getId,Visits::getReceptMemberId);
        queryWrapper.eq(Visits::getStatus,Constants.VisitStatus.pass)//审批通过
                .eq(Visits::getHkStatus,Constants.ZERO)//未同步到海康
                .orderByAsc(Visits::getCreateDate);
        List<Visits> list = visitsMapper.selectJoinList(Visits.class,queryWrapper);
        return list;
    }
    private List<Visits> getExpireVisitList() {
        MPJLambdaWrapper<Visits> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(Visits.class)
                .selectAs(Member::getType,Visits::getMemberType)
                .leftJoin(Member.class,Member::getId,Visits::getMemberId);
        queryWrapper.in(Visits::getStatus, Arrays.asList(new Integer[]{Constants.VisitStatus.xfSuccess,Constants.VisitStatus.signin}) );
        List<Visits> list = visitsMapper.selectJoinList(Visits.class,queryWrapper);
        return list;
    }
 
 
}