#939 门禁系统功能深化

Aberta
fanghuisheng desexa fusionar 4 achegas de uskycloud/fhs en uskycloud/master
Modificáronse 28 ficheiros con 863 adicións e 240 borrados
  1. 2 0
      service-eg/service-eg-api/src/main/java/com/usky/eg/RemoteEgService.java
  2. 5 1
      service-eg/service-eg-api/src/main/java/com/usky/eg/factory/RemoteEgFallbackFactory.java
  3. 17 0
      service-eg/service-eg-biz/src/main/java/com/usky/eg/controller/api/ServiceEgTaskApi.java
  4. 18 3
      service-eg/service-eg-biz/src/main/java/com/usky/eg/controller/web/EgDeviceController.java
  5. 41 0
      service-eg/service-eg-biz/src/main/java/com/usky/eg/controller/web/EgDeviceHeartbeatController.java
  6. 15 10
      service-eg/service-eg-biz/src/main/java/com/usky/eg/domain/EgDevice.java
  7. 84 0
      service-eg/service-eg-biz/src/main/java/com/usky/eg/domain/EgDeviceHeartbeat.java
  8. 34 0
      service-eg/service-eg-biz/src/main/java/com/usky/eg/domain/EgDevicePersonBind.java
  9. 1 1
      service-eg/service-eg-biz/src/main/java/com/usky/eg/domain/EgRecord.java
  10. 18 0
      service-eg/service-eg-biz/src/main/java/com/usky/eg/mapper/EgDeviceHeartbeatMapper.java
  11. 44 0
      service-eg/service-eg-biz/src/main/java/com/usky/eg/mapper/EgDevicePersonBindMapper.java
  12. 0 18
      service-eg/service-eg-biz/src/main/java/com/usky/eg/mapper/MeetingFaceDeviceMapper.java
  13. 0 18
      service-eg/service-eg-biz/src/main/java/com/usky/eg/mapper/MeetingFaceMapper.java
  14. 19 0
      service-eg/service-eg-biz/src/main/java/com/usky/eg/service/EgDeviceHeartbeatService.java
  15. 10 1
      service-eg/service-eg-biz/src/main/java/com/usky/eg/service/EgDeviceService.java
  16. 91 0
      service-eg/service-eg-biz/src/main/java/com/usky/eg/service/impl/EgDeviceHeartbeatServiceImpl.java
  17. 340 132
      service-eg/service-eg-biz/src/main/java/com/usky/eg/service/impl/EgDeviceServiceImpl.java
  18. 17 10
      service-eg/service-eg-biz/src/main/java/com/usky/eg/service/impl/EgRecordServiceImpl.java
  19. 9 0
      service-eg/service-eg-biz/src/main/java/com/usky/eg/service/vo/EgDeviceRequestVO.java
  20. 20 0
      service-eg/service-eg-biz/src/main/resources/mapper/eg/EgDeviceHeartbeatMapper.xml
  21. 1 2
      service-eg/service-eg-biz/src/main/resources/mapper/eg/EgDeviceMapper.xml
  22. 62 0
      service-eg/service-eg-biz/src/main/resources/mapper/eg/EgDevicePersonBindMapper.xml
  23. 0 11
      service-eg/service-eg-biz/src/main/resources/mapper/eg/MeetingFaceDeviceMapper.xml
  24. 0 21
      service-eg/service-eg-biz/src/main/resources/mapper/eg/MeetingFaceMapper.xml
  25. 6 0
      service-job/pom.xml
  26. 9 0
      service-job/src/main/java/com/ruoyi/job/task/RyTask.java
  27. 0 10
      service-meeting/service-meeting-biz/src/main/java/com/usky/meeting/domain/EgDevice.java
  28. 0 2
      service-meeting/service-meeting-biz/src/main/resources/mapper/meeting/EgDeviceMapper.xml

+ 2 - 0
service-eg/service-eg-api/src/main/java/com/usky/eg/RemoteEgService.java

@@ -13,4 +13,6 @@ import java.util.Map;
 @FeignClient(contextId = "remoteEgService", value = "service-eg", fallbackFactory = RemoteEgFallbackFactory.class)
 public interface RemoteEgService {
 
+    @GetMapping("/egDeviceStatus")
+    void egDeviceStatus();
 }

+ 5 - 1
service-eg/service-eg-api/src/main/java/com/usky/eg/factory/RemoteEgFallbackFactory.java

@@ -1,5 +1,6 @@
 package com.usky.eg.factory;
 
+import com.usky.common.core.exception.FeignBadRequestException;
 import com.usky.eg.RemoteEgService;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -23,7 +24,10 @@ public class RemoteEgFallbackFactory implements FallbackFactory<RemoteEgService>
     {
         log.error("用户服务调用失败:{}", throwable.getMessage());
         return new RemoteEgService() {
-
+            @Override
+            public void egDeviceStatus() {
+                throw new FeignBadRequestException(500,"同步门禁设备状态异常"+throwable.getMessage());
+            }
         };
     }
 }

+ 17 - 0
service-eg/service-eg-biz/src/main/java/com/usky/eg/controller/api/ServiceEgTaskApi.java

@@ -0,0 +1,17 @@
+package com.usky.eg.controller.api;
+
+import com.usky.eg.RemoteEgService;
+import com.usky.eg.service.EgDeviceHeartbeatService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+public class ServiceEgTaskApi implements RemoteEgService {
+    @Autowired
+    private EgDeviceHeartbeatService egDeviceHeartbeatService;
+
+    @Override
+    public void egDeviceStatus(){
+        egDeviceHeartbeatService.updateEgDeviceStatus();
+    }
+}

+ 18 - 3
service-eg/service-eg-biz/src/main/java/com/usky/eg/controller/web/EgDeviceController.java

@@ -81,6 +81,20 @@ public class EgDeviceController {
         return ApiResult.success();
     }
 
+    /**
+     * 设备绑定人员
+     * @param params 包含 deviceId, personIds, isLoginNotify 的参数对象
+     * @return
+     */
+    @PostMapping("/bindPerson")
+    public ApiResult<Void> bindPerson(@RequestBody Map<String, Object> params){
+        Integer deviceId = (Integer) params.get("deviceId");
+        String personIds = (String) params.get("personIds");
+        Integer isLoginNotify = params.get("isLoginNotify") != null ? (Integer) params.get("isLoginNotify") : 0;
+        egDeviceService.bindPerson(deviceId, personIds, isLoginNotify);
+        return ApiResult.success();
+    }
+
     /**
      * 下发设备控制命令
      */
@@ -90,12 +104,13 @@ public class EgDeviceController {
                                                  @RequestParam("deviceUuid") String deviceUuid,
                                                  @RequestParam("commandCode") String commandCode,
                                                  @RequestParam("commandValue") String commandValue,
-                                                 @RequestParam(value = "domain",required = false) String domain,
                                                  @RequestParam(value = "userId",required = false) Long userId,
                                                  @RequestParam(value = "userName",required = false) String userName,
                                                  @RequestParam(value = "categoryType",required = false , defaultValue = "1") Integer categoryType,
-                                                 @RequestParam(value = "gatewayUuid",required = false) String gatewayUuid){
-        return ApiResult.success(egDeviceService.control(productCode,deviceUuid,commandCode,commandValue,domain,userId,userName,categoryType,gatewayUuid));
+                                                 @RequestParam(value = "gatewayUuid",required = false) String gatewayUuid,
+                                                 @RequestParam(value = "skipCheck",required = false, defaultValue = "false") Boolean skipCheck,
+                                                 @RequestParam(value = "passType",required = false) Integer passType){
+        return ApiResult.success(egDeviceService.control(productCode,deviceUuid,commandCode,commandValue,userId,userName,categoryType,gatewayUuid,skipCheck,passType));
     }
 
 }

+ 41 - 0
service-eg/service-eg-biz/src/main/java/com/usky/eg/controller/web/EgDeviceHeartbeatController.java

@@ -0,0 +1,41 @@
+package com.usky.eg.controller.web;
+
+
+import com.usky.common.core.bean.ApiResult;
+import com.usky.eg.domain.EgDeviceHeartbeat;
+import com.usky.eg.service.EgDeviceHeartbeatService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+
+import org.springframework.web.bind.annotation.RestController;
+
+/**
+ * <p>
+ * 门禁设备心跳表 前端控制器
+ * </p>
+ *
+ * @author fhs
+ * @since 2026-02-03
+ */
+@RestController
+@RequestMapping("/egDeviceHeartbeat")
+public class EgDeviceHeartbeatController {
+    private static final Logger log = LoggerFactory.getLogger(EgDeviceHeartbeatController.class);
+    @Autowired
+    private EgDeviceHeartbeatService heartbeatService;
+
+    @PostMapping("/escalation")
+    public ApiResult<Void> heartbeatEscalation(@RequestBody EgDeviceHeartbeat heartbeat) {
+        try {
+            heartbeatService.heartbeatEscalation(heartbeat);
+        } catch (Exception e) {
+            log.error("设备心跳异常", e);
+            return ApiResult.error("设备心跳入库异常!");
+        }
+        return ApiResult.success();
+    }
+}

+ 15 - 10
service-eg/service-eg-biz/src/main/java/com/usky/eg/domain/EgDevice.java

@@ -62,16 +62,6 @@ public class EgDevice implements Serializable {
      */
     private String deviceIp;
 
-    /**
-     * 端口
-     */
-    private Integer devicePort;
-
-    /**
-     * 门禁号
-     */
-    private String egNumber;
-
     /**
      * 绑定人脸信息
      */
@@ -108,6 +98,12 @@ public class EgDevice implements Serializable {
      */
     private Integer tenantId;
 
+    /**
+     * 绑定人员信息(从 eg_device_person_bind 表汇总的 person_id 列表,以逗号分隔)
+     */
+    @TableField("bind_person")
+    private String bindPerson;
+
     /**
      * 屏保
      */
@@ -134,6 +130,15 @@ public class EgDevice implements Serializable {
     private String workStatus;
 
     /**
+     * 设备code
+     */
+    private String deviceCode;
+
+    /**
+     * 设备状态;1:在线,0:离线(从心跳表获取,不映射到数据库)
+     */
+    @TableField(exist = false)
+    private Integer deviceStatus;
 
     /**
      * 用户人脸信息记录

+ 84 - 0
service-eg/service-eg-biz/src/main/java/com/usky/eg/domain/EgDeviceHeartbeat.java

@@ -0,0 +1,84 @@
+package com.usky.eg.domain;
+
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableId;
+
+import java.time.LocalDateTime;
+import java.io.Serializable;
+
+import com.fasterxml.jackson.annotation.JsonFormat;
+import lombok.Data;
+import lombok.EqualsAndHashCode;
+
+/**
+ * <p>
+ * 门禁设备心跳表
+ * </p>
+ *
+ * @author fhs
+ * @since 2026-02-03
+ */
+@Data
+@EqualsAndHashCode(callSuper = false)
+public class EgDeviceHeartbeat implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    /**
+     * 门禁设备心跳表主键ID
+     */
+    @TableId(value = "id", type = IdType.AUTO)
+    private Integer id;
+
+    /**
+     * 设备code
+     */
+    private String deviceCode;
+
+    /**
+     * 设备ip地址
+     */
+    private String ipAddr;
+
+    /**
+     * 设备mac地址
+     */
+    private String macAddr;
+
+    /**
+     * 设备类型(1.会议屏 2.信息发布屏 3.综合屏)
+     */
+    private Boolean deviceType;
+
+    /**
+     * 创建日期
+     */
+    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
+    private LocalDateTime createTime;
+
+    /**
+     * 设备型号
+     */
+    private String model;
+
+    /**
+     *  设备厂商
+     */
+    private String manuFacturer;
+
+    /**
+     * 设备版本号
+     */
+    private String version;
+
+    /**
+     * 设备sdk
+     */
+    private String sdk;
+
+    /**
+     * 设备状态;1:在线,0:离线
+     */
+    private Integer deviceStatus;
+
+}

+ 34 - 0
service-eg/service-eg-biz/src/main/java/com/usky/eg/domain/EgDevicePersonBind.java

@@ -0,0 +1,34 @@
+package com.usky.eg.domain;
+
+import java.io.Serializable;
+
+import lombok.Data;
+import lombok.EqualsAndHashCode;
+
+/**
+ * <p>
+ * 门禁设备人员绑定表 eg_device_person_bind
+ * </p>
+ */
+@Data
+@EqualsAndHashCode(callSuper = false)
+public class EgDevicePersonBind implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    /**
+     * 设备主键ID
+     */
+    private Integer deviceId;
+
+    /**
+     * 人员ID
+     */
+    private Integer personId;
+
+    /**
+     * 是否打开登录通知(1 表示是,0 表示否,默认0)
+     */
+    private Integer isLoginNotify;
+}
+

+ 1 - 1
service-eg/service-eg-biz/src/main/java/com/usky/eg/domain/EgRecord.java

@@ -46,7 +46,7 @@ public class EgRecord implements Serializable {
     private Integer egDeviceId;
 
     /**
-     * 通行方式(1、人脸 2、刷卡 3、手机)
+     * 通行方式(0、其它 1、人脸 2、刷卡 3、手机 4、电脑)
      */
     private Integer passType;
 

+ 18 - 0
service-eg/service-eg-biz/src/main/java/com/usky/eg/mapper/EgDeviceHeartbeatMapper.java

@@ -0,0 +1,18 @@
+package com.usky.eg.mapper;
+
+import com.usky.eg.domain.EgDeviceHeartbeat;
+import com.usky.common.mybatis.core.CrudMapper;
+import org.springframework.stereotype.Repository;
+
+/**
+ * <p>
+ * 门禁设备心跳表 Mapper 接口
+ * </p>
+ *
+ * @author fhs
+ * @since 2026-02-03
+ */
+@Repository
+public interface EgDeviceHeartbeatMapper extends CrudMapper<EgDeviceHeartbeat> {
+
+}

+ 44 - 0
service-eg/service-eg-biz/src/main/java/com/usky/eg/mapper/EgDevicePersonBindMapper.java

@@ -0,0 +1,44 @@
+package com.usky.eg.mapper;
+
+import com.usky.eg.domain.EgDevicePersonBind;
+import org.apache.ibatis.annotations.Param;
+import org.springframework.stereotype.Repository;
+
+import java.util.List;
+
+@Repository
+public interface EgDevicePersonBindMapper {
+
+    /**
+     * 根据多个设备ID查询绑定关系
+     */
+    List<EgDevicePersonBind> selectByDeviceIds(@Param("deviceIds") List<Integer> deviceIds);
+
+    /**
+     * 统计某个设备下的绑定人数
+     */
+    Integer countByDeviceId(@Param("deviceId") Integer deviceId);
+
+    /**
+     * 根据用户ID和设备ID统计绑定关系
+     * 通过 sys_user_person -> sys_person -> eg_device_person_bind 进行关联
+     */
+    Integer countByUserIdAndDeviceId(@Param("userId") Long userId, @Param("deviceId") Integer deviceId);
+
+    /**
+     * 根据用户ID查询其绑定的设备ID列表
+     * 通过 sys_user_person -> sys_person -> eg_device_person_bind 进行关联
+     */
+    List<Integer> selectDeviceIdsByUserId(@Param("userId") Long userId);
+
+    /**
+     * 根据设备ID删除绑定关系
+     */
+    void deleteByDeviceId(@Param("deviceId") Integer deviceId);
+
+    /**
+     * 新增绑定关系
+     */
+    void insert(EgDevicePersonBind bind);
+}
+

+ 0 - 18
service-eg/service-eg-biz/src/main/java/com/usky/eg/mapper/MeetingFaceDeviceMapper.java

@@ -1,18 +0,0 @@
-package com.usky.eg.mapper;
-
-import com.usky.eg.domain.MeetingFaceDevice;
-import com.usky.common.mybatis.core.CrudMapper;
-import org.springframework.stereotype.Repository;
-
-/**
- * <p>
- * 人脸设备关联表 Mapper 接口
- * </p>
- *
- * @author zyj
- * @since 2024-11-27
- */
-@Repository
-public interface MeetingFaceDeviceMapper extends CrudMapper<MeetingFaceDevice> {
-
-}

+ 0 - 18
service-eg/service-eg-biz/src/main/java/com/usky/eg/mapper/MeetingFaceMapper.java

@@ -1,18 +0,0 @@
-package com.usky.eg.mapper;
-
-import com.usky.eg.domain.MeetingFace;
-import com.usky.common.mybatis.core.CrudMapper;
-import org.springframework.stereotype.Repository;
-
-/**
- * <p>
- *  Mapper 接口
- * </p>
- *
- * @author zyj
- * @since 2024-11-27
- */
-@Repository
-public interface MeetingFaceMapper extends CrudMapper<MeetingFace> {
-
-}

+ 19 - 0
service-eg/service-eg-biz/src/main/java/com/usky/eg/service/EgDeviceHeartbeatService.java

@@ -0,0 +1,19 @@
+package com.usky.eg.service;
+
+import com.usky.eg.domain.EgDeviceHeartbeat;
+import com.usky.common.mybatis.core.CrudService;
+
+/**
+ * <p>
+ * 门禁设备心跳表 服务类
+ * </p>
+ *
+ * @author fhs
+ * @since 2026-02-03
+ */
+public interface EgDeviceHeartbeatService extends CrudService<EgDeviceHeartbeat> {
+
+    void heartbeatEscalation(EgDeviceHeartbeat heartbeat);
+
+    void updateEgDeviceStatus();
+}

+ 10 - 1
service-eg/service-eg-biz/src/main/java/com/usky/eg/service/EgDeviceService.java

@@ -33,5 +33,14 @@ public interface EgDeviceService extends CrudService<EgDevice> {
 
     boolean checkDeviceNameUnique(EgDevice egDevice);
 
-    Map<String,Object> control(String productCode, String deviceUuid, String commandCode, String commandValue, String domain, Long userId, String userName, Integer categoryType, String gatewayUuid);
+    Map<String,Object> control(String productCode, String deviceUuid, String commandCode, String commandValue, Long userId, String userName, Integer categoryType, String gatewayUuid, Boolean skipCheck, Integer passType);
+
+    /**
+     * 设备与人员绑定
+     *
+     * @param deviceId      设备主键ID
+     * @param personIds     人员ID,多个以逗号分隔
+     * @param isLoginNotify 是否打开登录通知(1 表示是,0 表示否)
+     */
+    void bindPerson(Integer deviceId, String personIds, Integer isLoginNotify);
 }

+ 91 - 0
service-eg/service-eg-biz/src/main/java/com/usky/eg/service/impl/EgDeviceHeartbeatServiceImpl.java

@@ -0,0 +1,91 @@
+package com.usky.eg.service.impl;
+
+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.usky.common.core.exception.BusinessException;
+import com.usky.eg.domain.EgDeviceHeartbeat;
+import com.usky.eg.mapper.EgDeviceHeartbeatMapper;
+import com.usky.eg.service.EgDeviceHeartbeatService;
+import com.usky.common.mybatis.core.AbstractCrudService;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import java.time.LocalDateTime;
+import java.util.List;
+
+/**
+ * <p>
+ * 门禁设备心跳表 服务实现类
+ * </p>
+ *
+ * @author fhs
+ * @since 2026-02-03
+ */
+@Service
+public class EgDeviceHeartbeatServiceImpl extends AbstractCrudService<EgDeviceHeartbeatMapper, EgDeviceHeartbeat> implements EgDeviceHeartbeatService {
+
+    @Transactional(rollbackFor = Exception.class)
+    @Override
+    public void heartbeatEscalation(EgDeviceHeartbeat heartbeat) {
+        if (StringUtils.isBlank(heartbeat.getDeviceCode())) {
+            throw new BusinessException("设备编码不能为空!");
+        }
+        if (StringUtils.isBlank(heartbeat.getIpAddr())) {
+            throw new BusinessException("设备IP不能为空!");
+        }
+        if (heartbeat.getCreateTime() == null) {
+            heartbeat.setCreateTime(LocalDateTime.now());
+        }
+        if (heartbeat.getDeviceType() == null) {
+            throw new BusinessException("设备类型不能为空!");
+        }
+
+        // 查询是否存在该设备的心跳记录
+        LambdaQueryWrapper<EgDeviceHeartbeat> queryWrapper = Wrappers.lambdaQuery();
+        queryWrapper.eq(EgDeviceHeartbeat::getDeviceCode, heartbeat.getDeviceCode());
+        EgDeviceHeartbeat existingHeartbeat = baseMapper.selectOne(queryWrapper);
+        
+        if (existingHeartbeat != null) {
+            // 如果存在,更新记录
+            heartbeat.setId(existingHeartbeat.getId());
+            baseMapper.updateById(heartbeat);
+        } else {
+            // 如果不存在,插入新记录
+            baseMapper.insert(heartbeat);
+        }
+    }
+
+    /**
+     * 更新设备状态定时任务服务接口
+     * 从心跳表中获取设备状态并同步更新
+     */
+    @Override
+    @Transactional(rollbackFor = Exception.class)
+    public void updateEgDeviceStatus() {
+        try {
+            LocalDateTime now = LocalDateTime.now();
+            
+            // 1. 查询所有当前状态为在线的心跳记录
+            LambdaQueryWrapper<EgDeviceHeartbeat> heartbeatQueryWrapper = Wrappers.lambdaQuery();
+            heartbeatQueryWrapper.eq(EgDeviceHeartbeat::getDeviceStatus, 1);
+            List<EgDeviceHeartbeat> heartbeatList = baseMapper.selectList(heartbeatQueryWrapper);
+
+            // 2. 遍历在线记录,若心跳时间超过5分钟则更新为离线
+            for (EgDeviceHeartbeat heartbeat : heartbeatList) {
+                LocalDateTime heartbeatTime = heartbeat.getCreateTime();
+                if (heartbeatTime != null && !heartbeatTime.isAfter(now.minusMinutes(5))) {
+                    // 心跳超时,更新心跳表中的状态为离线
+                    LambdaUpdateWrapper<EgDeviceHeartbeat> updateWrapper = Wrappers.lambdaUpdate();
+                    updateWrapper.set(EgDeviceHeartbeat::getDeviceStatus, 0)
+                            .eq(EgDeviceHeartbeat::getId, heartbeat.getId());
+                    baseMapper.update(null, updateWrapper);
+                }
+            }
+        } catch (Exception e) {
+            // 定时任务失败不影响主流程,记录日志即可
+            throw new BusinessException("更新设备状态失败:" + (e.getMessage() != null ? e.getMessage() : "未知错误"));
+        }
+    }
+}

+ 340 - 132
service-eg/service-eg-biz/src/main/java/com/usky/eg/service/impl/EgDeviceServiceImpl.java

@@ -13,11 +13,13 @@ import com.usky.common.core.exception.BusinessException;
 import com.usky.common.core.util.UUIDUtils;
 import com.usky.common.security.utils.SecurityUtils;
 import com.usky.eg.domain.EgDevice;
-import com.usky.eg.domain.MeetingFace;
-import com.usky.eg.domain.MeetingFaceDevice;
+import com.usky.eg.domain.EgDeviceHeartbeat;
+import com.usky.eg.domain.EgDevicePersonBind;
+import com.usky.eg.domain.EgRecord;
 import com.usky.eg.mapper.EgDeviceMapper;
-import com.usky.eg.mapper.MeetingFaceDeviceMapper;
-import com.usky.eg.mapper.MeetingFaceMapper;
+import com.usky.eg.mapper.EgDeviceHeartbeatMapper;
+import com.usky.eg.mapper.EgDevicePersonBindMapper;
+import com.usky.eg.mapper.EgRecordMapper;
 import com.usky.eg.service.EgDeviceService;
 import com.usky.common.mybatis.core.AbstractCrudService;
 import com.usky.eg.service.vo.EgDeviceRequestVO;
@@ -29,6 +31,7 @@ import org.springframework.stereotype.Service;
 
 import java.time.LocalDateTime;
 import java.util.*;
+import java.util.concurrent.CompletableFuture;
 
 /**
  * <p>
@@ -40,25 +43,33 @@ import java.util.*;
  */
 @Service
 public class EgDeviceServiceImpl extends AbstractCrudService<EgDeviceMapper, EgDevice> implements EgDeviceService {
-    @Autowired
-    private MeetingFaceDeviceMapper meetingFaceDeviceMapper;
-    @Autowired
-    private MeetingFaceMapper meetingFaceMapper;
     @Autowired
     private EgDeviceMapper egDeviceMapper;
     @Autowired
+    private EgDeviceHeartbeatMapper egDeviceHeartbeatMapper;
+    @Autowired
     private RemoteIotTaskService remoteIotTaskService;
-
     @Autowired
     private RemoteTransferService remoteTransferService;
+    @Autowired
+    private EgDevicePersonBindMapper egDevicePersonBindMapper;
+    @Autowired
+    private EgRecordMapper egRecordMapper;
 
     @Override
     public CommonPage<EgDevice> page(EgDeviceRequestVO requestVO){
         IPage<EgDevice> page = new Page<>(requestVO.getCurrent(),requestVO.getSize());
-        Integer tenantId ;
+        Integer tenantId;
 
-        if(StringUtils.isNotBlank(requestVO.getDomain())){
-            tenantId = egDeviceMapper.sysTenantId(requestVO.getDomain());
+        if(StringUtils.isNotBlank(requestVO.getDeviceCode())){
+            LambdaQueryWrapper<EgDevice> tempQueryWrapper = new LambdaQueryWrapper<>();
+            tempQueryWrapper.eq(EgDevice::getDeviceCode, requestVO.getDeviceCode());
+            EgDevice tempDevice = egDeviceMapper.selectOne(tempQueryWrapper);
+            if(tempDevice == null){
+                // 未查询到数据,返回空数组
+                return new CommonPage<>(new ArrayList<>(), 0L, requestVO.getSize(), requestVO.getCurrent());
+            }
+            tenantId = tempDevice.getTenantId();
         }else{
             tenantId = SecurityUtils.getTenantId();
         }
@@ -69,34 +80,70 @@ public class EgDeviceServiceImpl extends AbstractCrudService<EgDeviceMapper, EgD
                 .eq(null != requestVO.getServiceStatus(),EgDevice::getServiceStatus,requestVO.getServiceStatus())
                 .eq(null != requestVO.getId(),EgDevice::getId,requestVO.getId())
                 .eq(null != requestVO.getDeviceUuid(),EgDevice::getDeviceUuid, requestVO.getDeviceUuid())
+                .eq(StringUtils.isNotBlank(requestVO.getDeviceCode()),EgDevice::getDeviceCode, requestVO.getDeviceCode())
                 .eq(EgDevice::getTenantId,tenantId)
                 .orderByDesc(EgDevice::getId);
         page = this.page(page,queryWrapper);
+
         if(!page.getRecords().isEmpty()){
+            // 检查设备心跳
+            List<String> validDeviceCodes = new ArrayList<>();
+            Map<String, EgDevice> deviceCodeMap = new HashMap<>();
+            for (EgDevice device : page.getRecords()) {
+                String deviceCode = device.getDeviceCode();
+                if (StringUtils.isNotBlank(deviceCode)) {
+                    validDeviceCodes.add(deviceCode);
+                    deviceCodeMap.put(deviceCode, device);
+                } else {
+                    // deviceCode为空,直接设置为离线
+                    device.setDeviceStatus(0);
+                }
+            }
 
-            LambdaQueryWrapper<MeetingFace> meetingFaceQuery = Wrappers.lambdaQuery();
-            meetingFaceQuery.select(MeetingFace::getFid,MeetingFace::getCreateTime,MeetingFace::getVefNum,MeetingFace::getFaceName,MeetingFace::getRemark,MeetingFace::getFaceStatus,MeetingFace::getCardNum,MeetingFace::getBindDevice,MeetingFace::getDeptId,MeetingFace::getTenantId,MeetingFace::getUserId)
-                    .eq(MeetingFace::getTenantId,tenantId);
-            List<MeetingFace> meetingAllFaceList = meetingFaceMapper.selectList(meetingFaceQuery);
-
-            for (int i = 0; i < page.getRecords().size(); i++) {
-                if(Objects.nonNull(page.getRecords().get(i).getBindFace()) ||StringUtils.isNotBlank(page.getRecords().get(i).getBindFace())){
-                    String[] fidListStr = page.getRecords().get(i).getBindFace().split(",");
-                    Integer[] fidList = Arrays.stream(fidListStr).map(Integer::parseInt).toArray(Integer[]::new);
-
-                    List<MeetingFace> meetingFaceList = new ArrayList<>();
-                    for (int j = 0; j < fidList.length; j++) {
-                        for (int k = 0; k < meetingAllFaceList.size(); k++) {
-                            if(fidList[j] == meetingAllFaceList.get(k).getFid()){
-                                meetingFaceList.add(meetingAllFaceList.get(k));
-                                break;
+            // 批量查询心跳数据
+            if (!validDeviceCodes.isEmpty()) {
+                LambdaQueryWrapper<EgDeviceHeartbeat> heartbeatQueryWrapper = Wrappers.lambdaQuery();
+                heartbeatQueryWrapper.in(EgDeviceHeartbeat::getDeviceCode, validDeviceCodes)
+                        .orderByDesc(EgDeviceHeartbeat::getCreateTime);
+                List<EgDeviceHeartbeat> heartbeatList = egDeviceHeartbeatMapper.selectList(heartbeatQueryWrapper);
+                
+                // 构建deviceCode到最新心跳记录的映射,并同时设置deviceStatus
+                Map<String, EgDeviceHeartbeat> deviceHeartbeatMap = new HashMap<>();
+                for (EgDeviceHeartbeat heartbeat : heartbeatList) {
+                    String deviceCode = heartbeat.getDeviceCode();
+                    if (StringUtils.isNotBlank(deviceCode)) {
+                        // 如果已存在,保留最新的(因为已按createTime降序排列)
+                        if (deviceHeartbeatMap.putIfAbsent(deviceCode, heartbeat) == null) {
+                            // 首次遇到该deviceCode,从心跳表直接获取deviceStatus并设置到EgDevice
+                            EgDevice device = deviceCodeMap.get(deviceCode);
+                            if (device != null && heartbeat.getDeviceStatus() != null) {
+                                device.setDeviceStatus(heartbeat.getDeviceStatus());
                             }
                         }
                     }
-                    page.getRecords().get(i).setMeetingFaceList(meetingFaceList);
                 }
-
+                
+                // 如果未找到对应的设备心跳记录,则设置DeviceStatus为0(离线)
+                for (String deviceCode : validDeviceCodes) {
+                    if (!deviceHeartbeatMap.containsKey(deviceCode)) {
+                        EgDevice device = deviceCodeMap.get(deviceCode);
+                        if (device != null) {
+                            device.setDeviceStatus(0);
+                        }
+                    }
+                }
+            } else {
+                // 如果没有有效的deviceCode,将所有设备的deviceStatus设置为0
+                for (EgDevice device : page.getRecords()) {
+                    device.setDeviceStatus(0);
+                }
             }
+
+        }
+
+        // 查询并填充绑定人员信息(来自 eg_device_person_bind,person_id 逗号分隔后写入 bindPerson 字段)
+        if (!page.getRecords().isEmpty()) {
+            fillBindPerson(page.getRecords());
         }
 
         return new CommonPage<>(page.getRecords(),page.getTotal(),requestVO.getSize(),requestVO.getCurrent());
@@ -105,86 +152,150 @@ public class EgDeviceServiceImpl extends AbstractCrudService<EgDeviceMapper, EgD
     @Override
     public CommonPage<EgDevice> wePage(EgDeviceRequestVO requestVO){
         long userId = SecurityUtils.getUserId();
-        //人员设备权限校验,校验通过,可以下发命令控制设备
-        Integer fid = baseMapper.getMeetingFaceData(userId);
-//        if(fid == null){
-//            throw new BusinessException("人脸卡号信息未注册");
-//        }
-        Integer[] deviceFid = baseMapper.getMeetingFaceDeviceList(fid);
-//        if(deviceFid.length == 0){
-//            throw new BusinessException("人员未绑定设备,请检查");
-//        }
+        // 通过 sys_user_person -> sys_person -> eg_device_person_bind -> eg_device 查询当前用户绑定的设备ID列表
+        List<Integer> deviceIds = egDevicePersonBindMapper.selectDeviceIdsByUserId(userId);
+        if (CollectionUtils.isEmpty(deviceIds)) {
+            // 未绑定任何设备,返回空分页
+            return new CommonPage<>(new ArrayList<>(), 0L, requestVO.getSize(), requestVO.getCurrent());
+        }
 
         IPage<EgDevice> page = new Page<>(requestVO.getCurrent(),requestVO.getSize());
-        if(deviceFid.length > 0){
-            LambdaQueryWrapper<EgDevice> queryWrapper = Wrappers.lambdaQuery();
-            queryWrapper.like(StringUtils.isNotBlank(requestVO.getDeviceName()),EgDevice::getDeviceName,requestVO.getDeviceName())
-                    .like(StringUtils.isNotBlank(requestVO.getInstallAddress()),EgDevice::getInstallAddress,requestVO.getInstallAddress())
-                    .eq(null != requestVO.getServiceStatus(),EgDevice::getServiceStatus,requestVO.getServiceStatus())
-                    .eq(null != requestVO.getId(),EgDevice::getId,requestVO.getId())
-                    .in(EgDevice::getId,deviceFid)
-                    .eq(EgDevice::getTenantId,SecurityUtils.getTenantId())
-                    .orderByDesc(EgDevice::getId);
-            page = this.page(page,queryWrapper);
-        }
+        LambdaQueryWrapper<EgDevice> queryWrapper = Wrappers.lambdaQuery();
+        queryWrapper.like(StringUtils.isNotBlank(requestVO.getDeviceName()),EgDevice::getDeviceName,requestVO.getDeviceName())
+                .like(StringUtils.isNotBlank(requestVO.getInstallAddress()),EgDevice::getInstallAddress,requestVO.getInstallAddress())
+                .eq(null != requestVO.getServiceStatus(),EgDevice::getServiceStatus,requestVO.getServiceStatus())
+                .eq(null != requestVO.getId(),EgDevice::getId,requestVO.getId())
+                .in(EgDevice::getId, deviceIds)
+                .eq(EgDevice::getTenantId,SecurityUtils.getTenantId())
+                .orderByDesc(EgDevice::getId);
+        page = this.page(page,queryWrapper);
 
+        // 查询并填充绑定人员信息
+        if (!page.getRecords().isEmpty()) {
+            fillBindPerson(page.getRecords());
+        }
 
         return new CommonPage<>(page.getRecords(),page.getTotal(),requestVO.getSize(),requestVO.getCurrent());
     }
 
     @Override
-    public void add(EgDevice egDevice){
-        if(checkNameUnique(egDevice)){
-            throw new BusinessException("新增门禁门号设备'"+egDevice.getDeviceId()+","+egDevice.getEgNumber()+"'失败,设备已存在");
+    public void add(EgDevice egDevice) {
+        LocalDateTime now = LocalDateTime.now();
+        
+        // 1. 校验设备名称唯一性
+        if (checkDeviceNameUnique(egDevice)) {
+            throw new BusinessException("新增门禁设备'" + egDevice.getDeviceName() + "'失败,设备已存在");
         }
-        if(checkDeviceNameUnique(egDevice)){
-            throw new BusinessException("新增门禁设备'"+egDevice.getDeviceName()+"'失败,设备已存在");
+
+        // 2. 校验设备IP是否已被绑定
+        if (StringUtils.isNotBlank(egDevice.getDeviceIp())) {
+            LambdaQueryWrapper<EgDevice> ipCheckWrapper = Wrappers.lambdaQuery();
+            ipCheckWrapper.eq(EgDevice::getDeviceIp, egDevice.getDeviceIp())
+                    .eq(EgDevice::getTenantId, SecurityUtils.getTenantId());
+            EgDevice existingDeviceByIp = this.getOne(ipCheckWrapper);
+            if (existingDeviceByIp != null) {
+                throw new BusinessException("设备IP'" + egDevice.getDeviceIp() + "'已被设备'" 
+                        + existingDeviceByIp.getDeviceName() + "'绑定,请更换IP或检查设备配置!");
+            }
+        }
+
+        // 3. 若未传deviceCode但传了deviceIp,尝试从心跳表中获取deviceCode
+        if (StringUtils.isBlank(egDevice.getDeviceCode()) && StringUtils.isNotBlank(egDevice.getDeviceIp())) {
+            LambdaQueryWrapper<EgDeviceHeartbeat> heartbeatCheckWrapper = Wrappers.lambdaQuery();
+            heartbeatCheckWrapper.eq(EgDeviceHeartbeat::getIpAddr, egDevice.getDeviceIp())
+                    .eq(EgDeviceHeartbeat::getDeviceStatus, 1);
+            EgDeviceHeartbeat heartbeat = egDeviceHeartbeatMapper.selectOne(heartbeatCheckWrapper);
+            if (heartbeat != null && StringUtils.isNotBlank(heartbeat.getDeviceCode())) {
+                egDevice.setDeviceCode(heartbeat.getDeviceCode());
+            }
         }
 
+        // 4. 校验设备编码是否已被绑定
+        if (StringUtils.isNotBlank(egDevice.getDeviceCode())) {
+            LambdaQueryWrapper<EgDevice> codeCheckWrapper = Wrappers.lambdaQuery();
+            codeCheckWrapper.eq(EgDevice::getDeviceCode, egDevice.getDeviceCode())
+                    .eq(EgDevice::getTenantId, SecurityUtils.getTenantId());
+            EgDevice existingDeviceByCode = this.getOne(codeCheckWrapper);
+            if (existingDeviceByCode != null) {
+                throw new BusinessException("设备编码'" + egDevice.getDeviceCode() + "'已被设备'" 
+                        + existingDeviceByCode.getDeviceName() + "'绑定,请更换设备编码或检查设备配置!");
+            }
+        }
+
+        // 5. 设置设备基本信息
         egDevice.setDeviceUuid(UUIDUtils.uuid());
         egDevice.setCreateBy(SecurityUtils.getUsername());
-        egDevice.setCreateTime(LocalDateTime.now());
+        egDevice.setCreateTime(now);
         egDevice.setTenantId(SecurityUtils.getTenantId());
+        egDevice.setOpenMode("人脸");
+        egDevice.setWorkStatus("4");
 
+        // 6. 保存设备
         this.save(egDevice);
 
-        String[] fids = new String[0];
-        if(Objects.nonNull(egDevice.getBindFace()) || StringUtils.isNotBlank(egDevice.getBindFace())){
-            fids = egDevice.getBindFace().split(",");
-        }
-        if(fids.length > 0){
-            for (int i = 0; i < fids.length; i++) {
-                egDeviceMapper.insertMeetingFaceDevice(Integer.parseInt(fids[i]),egDevice.getId());
-            }
+        // 7. 异步调用远程服务添加设备信息,静默处理异常,不影响设备保存成功
+        String deviceUuid = egDevice.getDeviceUuid();
+        String deviceName = egDevice.getDeviceName();
+        if (StringUtils.isNotBlank(deviceUuid) && StringUtils.isNotBlank(deviceName)) {
+            String installAddress = StringUtils.isNotBlank(egDevice.getInstallAddress()) 
+                    ? egDevice.getInstallAddress() 
+                    : "";
+            Integer serviceStatus = egDevice.getServiceStatus() != null 
+                    ? egDevice.getServiceStatus() 
+                    : 1;
+            
+            CompletableFuture.runAsync(() -> {
+                try {
+                    remoteIotTaskService.addDeviceInfo("502_USKY", deviceUuid, deviceUuid, 
+                            deviceName, installAddress, serviceStatus);
+                } catch (Exception e) {
+                    // 远程服务调用失败,静默处理,不影响设备保存成功
+                }
+            });
         }
-
-        remoteIotTaskService.addDeviceInfo("502_USKY", egDevice.getDeviceUuid(),egDevice.getDeviceId()+egDevice.getEgNumber(),egDevice.getDeviceName(),egDevice.getInstallAddress(),egDevice.getServiceStatus());
     }
 
     @Override
     public void update(EgDevice egDevice) {
-
-        String[] fids = new String[0];
-        if(Objects.nonNull(egDevice.getBindFace()) || StringUtils.isNotBlank(egDevice.getBindFace())){
-            fids = egDevice.getBindFace().split(",");
-
-            egDeviceMapper.deleteMeetingFaceDevice(egDevice.getId());
-        }else{
-            EgDevice one = this.getById(egDevice.getId());
-            egDevice.setBindFace(one.getBindFace());
+        if(checkDeviceNameUnique(egDevice)){
+            throw new BusinessException("修改门禁设备'"+egDevice.getDeviceName()+"'失败,设备名称已存在");
         }
-        if(fids.length > 0){
-            for (int i = 0; i < fids.length; i++) {
-                egDeviceMapper.insertMeetingFaceDevice(Integer.parseInt(fids[i]),egDevice.getId());
+
+        // 校验设备IP是否已被其他设备绑定(排除当前设备)
+        if (StringUtils.isNotBlank(egDevice.getDeviceIp())) {
+            LambdaQueryWrapper<EgDevice> ipCheckWrapper = Wrappers.lambdaQuery();
+            ipCheckWrapper.eq(EgDevice::getDeviceIp, egDevice.getDeviceIp())
+                    .eq(EgDevice::getTenantId, SecurityUtils.getTenantId())
+                    .ne(EgDevice::getId, egDevice.getId());
+            EgDevice existingDeviceByIp = this.getOne(ipCheckWrapper);
+            if (existingDeviceByIp != null) {
+                throw new BusinessException("设备IP'" + egDevice.getDeviceIp() + "'已被设备'" 
+                        + existingDeviceByIp.getDeviceName() + "'绑定,请更换IP或检查设备配置!");
             }
         }
 
-
-        if(checkNameUnique(egDevice)){
-            throw new BusinessException("修改门禁门号设备'"+egDevice.getDeviceId()+","+egDevice.getEgNumber()+"'失败,设备已存在");
+        // 若未传deviceCode但传了deviceIp,尝试从心跳表中获取deviceCode
+        if (StringUtils.isBlank(egDevice.getDeviceCode()) && StringUtils.isNotBlank(egDevice.getDeviceIp())) {
+            LambdaQueryWrapper<EgDeviceHeartbeat> heartbeatCheckWrapper = Wrappers.lambdaQuery();
+            heartbeatCheckWrapper.eq(EgDeviceHeartbeat::getIpAddr, egDevice.getDeviceIp())
+                    .eq(EgDeviceHeartbeat::getDeviceStatus, 1);
+            EgDeviceHeartbeat heartbeat = egDeviceHeartbeatMapper.selectOne(heartbeatCheckWrapper);
+            if (heartbeat != null && StringUtils.isNotBlank(heartbeat.getDeviceCode())) {
+                egDevice.setDeviceCode(heartbeat.getDeviceCode());
+            }
         }
-        if(checkDeviceNameUnique(egDevice)){
-            throw new BusinessException("新增门禁设备'"+egDevice.getDeviceName()+"'失败,设备已存在");
+
+        // 校验设备编码是否已被其他设备绑定(排除当前设备)
+        if (StringUtils.isNotBlank(egDevice.getDeviceCode())) {
+            LambdaQueryWrapper<EgDevice> codeCheckWrapper = Wrappers.lambdaQuery();
+            codeCheckWrapper.eq(EgDevice::getDeviceCode, egDevice.getDeviceCode())
+                    .eq(EgDevice::getTenantId, SecurityUtils.getTenantId())
+                    .ne(EgDevice::getId, egDevice.getId());
+            EgDevice existingDeviceByCode = this.getOne(codeCheckWrapper);
+            if (existingDeviceByCode != null) {
+                throw new BusinessException("设备编码'" + egDevice.getDeviceCode() + "'已被设备'" 
+                        + existingDeviceByCode.getDeviceName() + "'绑定,请更换设备编码或检查设备配置!");
+            }
         }
 
         egDevice.setUpdateBy(SecurityUtils.getUsername());
@@ -199,9 +310,7 @@ public class EgDeviceServiceImpl extends AbstractCrudService<EgDeviceMapper, EgD
         EgDevice one = this.getById(egDevice.getId());
         egDevice.setBindFace(one.getBindFace());
 
-        if(checkNameUnique(egDevice)){
-            throw new BusinessException("更新门禁设备附加功能'"+egDevice.getDeviceId()+"'失败,设备已存在");
-        }
+
         if(checkDeviceNameUnique(egDevice)){
             throw new BusinessException("新增门禁设备'"+egDevice.getDeviceName()+"'失败,设备已存在");
         }
@@ -217,16 +326,72 @@ public class EgDeviceServiceImpl extends AbstractCrudService<EgDeviceMapper, EgD
         EgDevice egDevice = this.getById(id);
         Optional.ofNullable(egDevice).orElseThrow(() -> new BusinessException("门禁设备信息不存在"));
 
-        LambdaQueryWrapper<MeetingFaceDevice> queryWrapper = Wrappers.lambdaQuery();
-        queryWrapper.eq(MeetingFaceDevice::getDeviceId,id);
-        Integer count = meetingFaceDeviceMapper.selectCount(queryWrapper);
-        if(count > 0){
+        // 校验 eg_device_person_bind 是否存在绑定人员
+        Integer personBindCount = egDevicePersonBindMapper.countByDeviceId(id);
+        if (personBindCount != null && personBindCount > 0) {
             throw new BusinessException("已绑定人员不能删除");
         }
 
         this.removeById(id);
 
-        remoteIotTaskService.deleteDeviceInfo(egDevice.getDeviceUuid());
+        // 异步调用远程服务删除设备信息,静默处理异常,不影响设备删除
+        String deviceUuid = egDevice.getDeviceUuid();
+        if (StringUtils.isNotBlank(deviceUuid)) {
+            CompletableFuture.runAsync(() -> {
+                try {
+                    remoteIotTaskService.deleteDeviceInfo(deviceUuid);
+                } catch (Exception e) {
+                    // 远程服务调用失败,静默处理,不影响设备删除
+                }
+            });
+        }
+    }
+
+    /**
+     * 根据设备ID集合查询 eg_device_person_bind,将 person_id 按逗号拼接后写入设备的 bindPerson 字段
+     */
+    private void fillBindPerson(List<EgDevice> devices) {
+        if (CollectionUtils.isEmpty(devices)) {
+            return;
+        }
+
+        List<Integer> deviceIds = new ArrayList<>();
+        for (EgDevice device : devices) {
+            if (device != null && device.getId() != null) {
+                deviceIds.add(device.getId());
+            }
+        }
+
+        if (deviceIds.isEmpty()) {
+            return;
+        }
+
+        List<EgDevicePersonBind> bindList = egDevicePersonBindMapper.selectByDeviceIds(deviceIds);
+        if (CollectionUtils.isEmpty(bindList)) {
+            return;
+        }
+
+        Map<Integer, List<String>> devicePersonMap = new HashMap<>();
+        for (EgDevicePersonBind bind : bindList) {
+            if (bind.getDeviceId() == null || bind.getPersonId() == null) {
+                continue;
+            }
+            devicePersonMap
+                    .computeIfAbsent(bind.getDeviceId(), k -> new ArrayList<>())
+                    .add(String.valueOf(bind.getPersonId()));
+        }
+
+        for (EgDevice device : devices) {
+            if (device == null || device.getId() == null) {
+                continue;
+            }
+            List<String> personIds = devicePersonMap.get(device.getId());
+            if (personIds != null && !personIds.isEmpty()) {
+                device.setBindPerson(String.join(",", personIds));
+            } else {
+                device.setBindPerson(null);
+            }
+        }
     }
 
     @Override
@@ -234,7 +399,6 @@ public class EgDeviceServiceImpl extends AbstractCrudService<EgDeviceMapper, EgD
         Integer id = null == egDevice.getId() ? -1 : egDevice.getId();
         LambdaQueryWrapper<EgDevice> queryWrapper = Wrappers.lambdaQuery();
         queryWrapper.eq(EgDevice::getDeviceId,egDevice.getDeviceId())
-                .eq(EgDevice::getEgNumber,egDevice.getEgNumber())
                 .eq(EgDevice::getTenantId, SecurityUtils.getTenantId());
         EgDevice one = this.getOne(queryWrapper);
         return null != one && !Objects.equals(one.getId(),id);
@@ -251,56 +415,100 @@ public class EgDeviceServiceImpl extends AbstractCrudService<EgDeviceMapper, EgD
     }
 
     @Override
-    public Map<String,Object> control(String productCode, String deviceUuid, String commandCode, String commandValue, String domain, Long userId, String userName, Integer categoryType, String gatewayUuid){
-        Integer tenantId;
-        long commandUserId;
-        String commandUserName;
-        if(StringUtils.isNotBlank(domain)){
-            tenantId = baseMapper.sysTenantId(domain);
-            commandUserId = userId;
-            commandUserName = userName;
-        }else{
-            tenantId = SecurityUtils.getTenantId();
-            commandUserId = SecurityUtils.getUserId();
-            commandUserName = SecurityUtils.getUsername();
+    public Map<String,Object> control(String productCode, String deviceUuid, String commandCode, String commandValue, Long userId, String userName, Integer categoryType, String gatewayUuid, Boolean skipCheck, Integer passType){
+        // 1. 查询设备
+        EgDevice device = this.getOne(Wrappers.<EgDevice>lambdaQuery()
+                .select(EgDevice::getId, EgDevice::getTenantId)
+                .eq(EgDevice::getDeviceUuid, deviceUuid));
+        if (device == null) {
+            throw new BusinessException("设备未注册,请先注册");
         }
 
-        //人员设备权限校验,校验通过,可以下发命令控制设备
-        Integer fid = baseMapper.getMeetingFaceData(commandUserId);
-        if(fid == null){
-            throw new BusinessException("人脸卡号信息未注册");
-        }
-        Integer[] deviceFid = baseMapper.getMeetingFaceDeviceList(fid);
-        if(deviceFid.length == 0){
-            throw new BusinessException("人员未绑定设备,请检查");
-        }
+        Integer tenantId = device.getTenantId();
+        long commandUserId = userId != null ? userId : SecurityUtils.getUserId();
+        String commandUserName = userName != null ? userName : SecurityUtils.getUsername();
 
-        LambdaQueryWrapper<EgDevice> queryWrapper = Wrappers.lambdaQuery();
-        queryWrapper.select(EgDevice::getId)
-                .eq(EgDevice::getDeviceUuid,deviceUuid);
-        EgDevice one = this.getOne(queryWrapper);
-        if(one != null){
-            boolean exist = Arrays.asList(deviceFid).contains(one.getId());
-            if(!exist){
+        // 2. 权限校验
+        if (!Boolean.TRUE.equals(skipCheck)) {
+            Integer bindCount = egDevicePersonBindMapper.countByUserIdAndDeviceId(commandUserId, device.getId());
+            if (bindCount == null || bindCount == 0) {
+                saveRecord(device.getId(), tenantId, commandUserName, passType, "失败:暂无权限");
                 throw new BusinessException("暂无权限");
             }
-        }else{
-            throw new BusinessException("设备未注册,请先注册");
         }
 
-
+        // 3. 构建下发命令参数
+        Map<String,Object> params = new HashMap<>();
+        params.put("commandCode", commandCode);
+        params.put("commandValue", commandValue);
         Map<String,Object> map = new HashMap<>();
-        map.put("method","control");
+        map.put("method", "control");
         map.put("deviceUuid", deviceUuid);
-        Map<String,Object> map1 = new HashMap<>();
-        map1.put("commandCode",commandCode);
-        map1.put("commandValue",commandValue);
-        map.put("params",map1);
+        map.put("params", params);
+
+        // 4. 下发命令并记录结果
+        String targetUuid = categoryType == 3 ? gatewayUuid : deviceUuid;
+        Map<String,Object> result = null;
+        String passResult = "下发命令失败";
+        try {
+            result = remoteTransferService.deviceControl(productCode, targetUuid, JSON.toJSONString(map), tenantId, commandUserId, commandUserName);
+            if (result == null || !Integer.valueOf(200).equals(result.get("code"))) {
+                passResult = result != null && result.get("message") != null ? result.get("message").toString() : "下发命令失败";
+                throw new BusinessException(passResult);
+            }
+            passResult = result.get("message") != null ? result.get("message").toString() : "下发命令成功";
+            return result;
+        } finally {
+            saveRecord(device.getId(), tenantId, commandUserName, passType, passResult);
+        }
+    }
 
-        if(categoryType == 3){
-            return remoteTransferService.deviceControl(productCode, gatewayUuid, JSON.toJSONString(map), tenantId, commandUserId, commandUserName);
-        }else{
-            return remoteTransferService.deviceControl(productCode, deviceUuid, JSON.toJSONString(map), tenantId, commandUserId, commandUserName);
+    /**
+     * 插入通行记录,失败不影响主流程
+     */
+    private void saveRecord(Integer deviceId, Integer tenantId, String userName, Integer passType, String passResult) {
+        try {
+            EgRecord record = new EgRecord();
+            record.setEgDeviceId(deviceId);
+            record.setTenantId(tenantId);
+            record.setPassTime(LocalDateTime.now());
+            record.setCreateTime(LocalDateTime.now());
+            record.setPassResult(passResult);
+            record.setUserName(userName);
+            record.setPassType(passType);
+            egRecordMapper.insert(record);
+        } catch (Exception ignored) {}
+    }
+
+    @Override
+    public void bindPerson(Integer deviceId, String personIds, Integer isLoginNotify) {
+        if (deviceId == null) {
+            throw new BusinessException("设备ID不能为空");
+        }
+
+        // 先校验设备是否存在
+        EgDevice device = this.getById(deviceId);
+        Optional.ofNullable(device).orElseThrow(() -> new BusinessException("门禁设备信息不存在"));
+
+        // 先清空原有绑定关系
+        egDevicePersonBindMapper.deleteByDeviceId(deviceId);
+
+        // 为空则视为解绑所有人员
+        if (!StringUtils.isNotBlank(personIds)) {
+            return;
+        }
+
+        String[] personIdArr = personIds.split(",");
+        int loginNotify = (isLoginNotify == null) ? 0 : isLoginNotify;
+        for (String personIdStr : personIdArr) {
+            if (!StringUtils.isNotBlank(personIdStr)) {
+                continue;
+            }
+            EgDevicePersonBind bind = new EgDevicePersonBind();
+            bind.setDeviceId(deviceId);
+            bind.setPersonId(Integer.parseInt(personIdStr.trim()));
+            bind.setIsLoginNotify(loginNotify);
+            egDevicePersonBindMapper.insert(bind);
         }
     }
 }

+ 17 - 10
service-eg/service-eg-biz/src/main/java/com/usky/eg/service/impl/EgRecordServiceImpl.java

@@ -47,23 +47,31 @@ public class EgRecordServiceImpl extends AbstractCrudService<EgRecordMapper, EgR
     @Override
     public void add(EgRecord egRecord){
         Integer tenantId;
-        if(StringUtils.isNotBlank(egRecord.getDomain())){
-            tenantId = egDeviceMapper.sysTenantId(egRecord.getDomain());
-        }else{
-            tenantId = SecurityUtils.getTenantId();
-        }
-
+        
+        // 通过deviceUuid查询设备获取tenantId
         LambdaQueryWrapper<EgDevice> queryWrapper = Wrappers.lambdaQuery();
         if(StringUtils.isBlank(egRecord.getDeviceUuid())){
             throw new BusinessException("设备Uuid不能为空");
         }
-        queryWrapper.eq(EgDevice::getDeviceUuid,egRecord.getDeviceUuid());
+        queryWrapper.select(EgDevice::getId, EgDevice::getTenantId)
+                .eq(EgDevice::getDeviceUuid,egRecord.getDeviceUuid());
         EgDevice one = egDeviceService.getOne(queryWrapper);
+        if(one == null){
+            throw new BusinessException("设备未注册,请先注册");
+        }
+        tenantId = one.getTenantId();
         egRecord.setEgDeviceId(one.getId());
-
         egRecord.setCreateTime(LocalDateTime.now());
         egRecord.setTenantId(tenantId);
-        egRecord.setDeptId(SecurityUtils.getLoginUser().getSysUser().getDeptId().intValue());
+        
+        // 安全获取部门ID
+        Integer deptId = null;
+        if(SecurityUtils.getLoginUser() != null 
+                && SecurityUtils.getLoginUser().getSysUser() != null 
+                && SecurityUtils.getLoginUser().getSysUser().getDeptId() != null){
+            deptId = SecurityUtils.getLoginUser().getSysUser().getDeptId().intValue();
+        }
+        egRecord.setDeptId(deptId);
 
         this.save(egRecord);
     }
@@ -114,7 +122,6 @@ public class EgRecordServiceImpl extends AbstractCrudService<EgRecordMapper, EgR
             }
         }
 
-
         return new CommonPage<>(page.getRecords(),page.getTotal(),requestVO.getSize(),requestVO.getCurrent());
     }
 }

+ 9 - 0
service-eg/service-eg-biz/src/main/java/com/usky/eg/service/vo/EgDeviceRequestVO.java

@@ -45,4 +45,13 @@ public class EgDeviceRequestVO implements Serializable {
      * 设备uuid
      */
     private String deviceUuid;
+
+    /**
+     * 设备编码
+     */
+    private String deviceCode;
+    /**
+     * 设备状态
+     */
+    private Integer deviceStatus;
 }

+ 20 - 0
service-eg/service-eg-biz/src/main/resources/mapper/eg/EgDeviceHeartbeatMapper.xml

@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
+<mapper namespace="com.usky.eg.mapper.EgDeviceHeartbeatMapper">
+
+    <!-- 通用查询映射结果 -->
+    <resultMap id="BaseResultMap" type="com.usky.eg.domain.EgDeviceHeartbeat">
+        <id column="id" property="id"/>
+        <result column="device_code" property="deviceCode"/>
+        <result column="ip_addr" property="ipAddr"/>
+        <result column="mac_addr" property="macAddr"/>
+        <result column="device_type" property="deviceType"/>
+        <result column="create_time" property="createTime"/>
+        <result column="model" property="model"/>
+        <result column="manu_facturer"  property="manuFacturer"/>
+        <result column="version" property="version"/>
+        <result column="sdk" property="sdk"/>
+        <result column="device_status" property="deviceStatus"/>
+    </resultMap>
+
+</mapper>

+ 1 - 2
service-eg/service-eg-biz/src/main/resources/mapper/eg/EgDeviceMapper.xml

@@ -11,9 +11,8 @@
         <result column="install_address" property="installAddress" />
         <result column="service_status" property="serviceStatus" />
         <result column="device_ip" property="deviceIp" />
-        <result column="device_port" property="devicePort" />
-        <result column="eg_number" property="egNumber" />
         <result column="bind_face" property="bindFace" />
+        <result column="bind_person" property="bindPerson" />
         <result column="create_by" property="createBy" />
         <result column="update_by" property="updateBy" />
         <result column="create_time" property="createTime" />

+ 62 - 0
service-eg/service-eg-biz/src/main/resources/mapper/eg/EgDevicePersonBindMapper.xml

@@ -0,0 +1,62 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
+<mapper namespace="com.usky.eg.mapper.EgDevicePersonBindMapper">
+
+    <resultMap id="BaseResultMap" type="com.usky.eg.domain.EgDevicePersonBind">
+        <result column="device_id" property="deviceId" />
+        <result column="person_id" property="personId" />
+        <result column="is_login_notify" property="isLoginNotify" />
+    </resultMap>
+
+    <select id="selectByDeviceIds" resultMap="BaseResultMap">
+        select device_id, person_id, is_login_notify
+        from eg_device_person_bind
+        <where>
+            <if test="deviceIds != null and deviceIds.size() > 0">
+                and device_id in
+                <foreach collection="deviceIds" item="id" open="(" separator="," close=")">
+                    #{id}
+                </foreach>
+            </if>
+        </where>
+    </select>
+
+    <select id="countByDeviceId" resultType="java.lang.Integer">
+        select count(1)
+        from eg_device_person_bind
+        where device_id = #{deviceId}
+    </select>
+
+    <!--
+        通过 sys_user_person 关联 sys_person,最终关联到 eg_device_person_bind,判断某个用户是否对某设备有绑定关系
+        假定字段:sys_user_person(user_id, person_id),sys_person(id),eg_device_person_bind(person_id, device_id)
+    -->
+    <select id="countByUserIdAndDeviceId" resultType="java.lang.Integer">
+        select count(1)
+        from eg_device_person_bind b
+                 join sys_person p on b.person_id = p.id
+                 join sys_user_person up on up.person_id = p.id
+        where up.user_id = #{userId}
+          and b.device_id = #{deviceId}
+    </select>
+
+    <!-- 根据用户ID查询其绑定的设备ID列表 -->
+    <select id="selectDeviceIdsByUserId" resultType="java.lang.Integer">
+        select distinct b.device_id
+        from eg_device_person_bind b
+                 join sys_person p on b.person_id = p.id
+                 join sys_user_person up on up.person_id = p.id
+        where up.user_id = #{userId}
+    </select>
+
+    <delete id="deleteByDeviceId">
+        delete from eg_device_person_bind
+        where device_id = #{deviceId}
+    </delete>
+
+    <insert id="insert" parameterType="com.usky.eg.domain.EgDevicePersonBind">
+        insert into eg_device_person_bind (device_id, person_id, is_login_notify)
+        values (#{deviceId}, #{personId}, #{isLoginNotify})
+    </insert>
+
+</mapper>

+ 0 - 11
service-eg/service-eg-biz/src/main/resources/mapper/eg/MeetingFaceDeviceMapper.xml

@@ -1,11 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
-<mapper namespace="com.usky.eg.mapper.MeetingFaceDeviceMapper">
-
-    <!-- 通用查询映射结果 -->
-    <resultMap id="BaseResultMap" type="com.usky.eg.domain.MeetingFaceDevice">
-        <id column="face_id" property="faceId" />
-        <result column="device_id" property="deviceId" />
-    </resultMap>
-
-</mapper>

+ 0 - 21
service-eg/service-eg-biz/src/main/resources/mapper/eg/MeetingFaceMapper.xml

@@ -1,21 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
-<mapper namespace="com.usky.eg.mapper.MeetingFaceMapper">
-
-    <!-- 通用查询映射结果 -->
-    <resultMap id="BaseResultMap" type="com.usky.eg.domain.MeetingFace">
-        <id column="fid" property="fid" />
-        <result column="face_base" property="faceBase" />
-        <result column="create_time" property="createTime" />
-        <result column="vef_num" property="vefNum" />
-        <result column="face_name" property="faceName" />
-        <result column="remark" property="remark" />
-        <result column="face_status" property="faceStatus" />
-        <result column="card_num" property="cardNum" />
-        <result column="bind_device" property="bindDevice" />
-        <result column="dept_id" property="deptId" />
-        <result column="tenant_id" property="tenantId" />
-        <result column="user_id" property="userId" />
-    </resultMap>
-
-</mapper>

+ 6 - 0
service-job/pom.xml

@@ -88,6 +88,12 @@
             <version>0.0.1</version>
             <scope>compile</scope>
         </dependency>
+        <dependency>
+            <groupId>com.usky</groupId>
+            <artifactId>service-eg-api</artifactId>
+            <version>0.0.1</version>
+            <scope>compile</scope>
+        </dependency>
     </dependencies>
 
     <build>

+ 9 - 0
service-job/src/main/java/com/ruoyi/job/task/RyTask.java

@@ -3,6 +3,7 @@ package com.ruoyi.job.task;
 import com.usky.cdi.AlarmDataSyncTaskService;
 import com.usky.cdi.RemotecdiTaskService;
 import com.usky.common.core.utils.StringUtils;
+import com.usky.eg.RemoteEgService;
 import com.usky.meeting.RemoteMeetingService;
 import com.usky.ems.RemoteEmsTaskService;
 import com.usky.fire.RemoteFireService;
@@ -39,6 +40,8 @@ public class RyTask {
     @Autowired
     private RemoteEmsTaskService remoteEmsTaskService;
 
+    @Autowired
+    private RemoteEgService remoteEgService;
 
     public void ryMultipleParams(String s, Boolean b, Long l, Double d, Integer i) {
         System.out.println(StringUtils.format("执行多参方法: 字符串类型{},布尔类型{},长整型{},浮点型{},整形{}", s, b, l, d, i));
@@ -121,4 +124,10 @@ public class RyTask {
         remoteEmsTaskService.sendEnergyHeartbeat();
     }
 
+    // 门禁设备心跳状态
+    public void egDeviceStatus() {
+        System.out.println("egDeviceStatus start......");
+        remoteEgService.egDeviceStatus();
+    }
+
 }

+ 0 - 10
service-meeting/service-meeting-biz/src/main/java/com/usky/meeting/domain/EgDevice.java

@@ -57,16 +57,6 @@ public class EgDevice implements Serializable {
      */
     private String deviceIp;
 
-    /**
-     * 端口
-     */
-    private Integer devicePort;
-
-    /**
-     * 门禁号
-     */
-    private String egNumber;
-
     /**
      * 创建者
      */

+ 0 - 2
service-meeting/service-meeting-biz/src/main/resources/mapper/meeting/EgDeviceMapper.xml

@@ -11,8 +11,6 @@
         <result column="install_address" property="installAddress" />
         <result column="service_status" property="serviceStatus" />
         <result column="device_ip" property="deviceIp" />
-        <result column="device_port" property="devicePort" />
-        <result column="eg_number" property="egNumber" />
         <result column="create_by" property="createBy" />
         <result column="update_by" property="updateBy" />
         <result column="create_time" property="createTime" />