package com.junmp.jyzb.websocket;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.junmp.jyzb.api.bean.dto.*;
import com.junmp.jyzb.api.bean.query.*;
import com.junmp.jyzb.api.bean.query.inAndOutRecordReq.SummaryLogReq;
import com.junmp.jyzb.api.bean.req.*;
import com.junmp.jyzb.api.bean.vo.CabinetEventVo;
import com.junmp.jyzb.api.bean.vo.CabinetWsVo;
import com.junmp.jyzb.api.bean.ws.RegCabinetReq;
import com.junmp.jyzb.api.cmd.CabinetCmd;
import com.junmp.jyzb.api.constant.JYZBConstant;
import com.junmp.jyzb.api.enums.CabinetStateEnum;
import com.junmp.jyzb.api.exception.enums.WsCabinetExceptionEnum;
import com.junmp.jyzb.api.exception.enums.CabinetExceptionEnum;
import com.junmp.jyzb.cache.MsgRedisCache;
import com.junmp.jyzb.entity.Application;
import com.junmp.jyzb.entity.Policeman;
import com.junmp.jyzb.event.EventPublisher;
import com.junmp.jyzb.service.CabinetAppBizService;
import com.junmp.jyzb.websocket.configurator.JyzbCabinetConfigurator;
import com.junmp.v2.common.bean.response.ApiRes;
import com.junmp.v2.common.bean.response.WsCmdRes;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * <pre>
 *
 * 描述：单警柜应用的APP服务
 * 版本：1.0.0
 * 日期：2024/4/9 14:07
 * 作者：ningzp@junmp.com.cn
 * <br>修改记录
 * <br>修改日期        修改人          修改内容
 *
 * </pre>
 */
@Component
@ServerEndpoint(value = "/ws/cabinet", configurator = JyzbCabinetConfigurator.class)
@Slf4j
public class WsCabinetAppServer {

    private final String CB_WS_PREFIX = "ws";

    private static CabinetAppBizService cabinetAppBizService;


    private static EventPublisher eventPublisher;


    private static MsgRedisCache redisCache;

    /**
     * 当前连接总数
     */
    private static AtomicInteger currentConnectTotal = new AtomicInteger(0);

    /**
     * 每个客户端对应的Session
     */
    public static Map<String, WsCabinetAppServer> sessionMap = new ConcurrentHashMap<>();


    /**
     * cabinet 会话对象
     */
    public Session cabinetSession;

    /**
     * 机构代码
     */
    private String orgCode;

    /**
     * 设备序号
     */
    private String devSn;

    @Autowired
    public void setCabinetAppBizService(CabinetAppBizService cabinetAppBizService) {
        WsCabinetAppServer.cabinetAppBizService = cabinetAppBizService;
    }

    @Autowired
    public void setEventPublisher(EventPublisher eventPublisher) {
        WsCabinetAppServer.eventPublisher = eventPublisher;
    }

    @Autowired
    public void setRedisCache(MsgRedisCache redisCache) {
        WsCabinetAppServer.redisCache = redisCache;
    }
    /**
     * 建立连接
     *
     * @param session
     */
    @OnOpen
    public void connect(Session session) {
        try {
            boolean isOk = (boolean) session.getUserProperties().get(JYZBConstant.CONNECTION_STATUS);
            if (isOk) {
                CabinetWsVo wsVo = (CabinetWsVo) session.getUserProperties().get(JYZBConstant.CABINET_WS_VALUE);
                this.cabinetSession = session;
                this.orgCode = wsVo.getOrgCode();
                this.devSn = wsVo.getDevSn();
                String keyVal = getCabinetWsKey(orgCode, devSn);
                WsCabinetAppServer oldSession = sessionMap.get(keyVal);
                eventPublisher.cabinetOnlineEventPublish(new CabinetEventVo(orgCode, devSn));
                if (null == oldSession) {
                    sessionMap.put(keyVal, this);
                    currentConnectTotal.incrementAndGet();
                    cabinetAppBizService.updateCabinetState(orgCode, devSn, CabinetStateEnum.ONLINE);
                    log.info("[Ws接入成功]|[组织机构={},设备编号={}],当前连接数：{}", orgCode, devSn, currentConnectTotal.get());
                }
            }
        } catch (Exception ex) {
            sendMessage(session, ApiRes.failure(ex.getMessage()));
            log.info("[Ws接入异常]|[组织机构={},设备编号={}],当前连接数：{}", orgCode, devSn, currentConnectTotal.get());
        }
    }

    @OnMessage
    public void onMessage(Session session, String message) {
        try {
            log.info("[接收客户端请求]|[组织机构={},设备序号={}]请求参数：{}", orgCode, devSn, message);
            if (StrUtil.isNotBlank(message)) {
                JSONObject jsonObject = JSON.parseObject(message);
                Optional<String> cmdInfo = Optional.ofNullable(jsonObject.getString(JYZBConstant.CABINET_CMD_KEY));
                Optional<String> dataInfo = Optional.ofNullable(jsonObject.getString(JYZBConstant.CABINET_DATA_KEY));

                if (!cmdInfo.isPresent() || StrUtil.isBlank(cmdInfo.get())) {
                    sendMessage(session, WsCmdRes.failure(JYZBConstant.CABINET_CMD_ERROR_KEY, WsCabinetExceptionEnum.WS_CABINET_REQ_CMD_FORMAT_ERROR.getMessage()));
                    return;
                }
                WsCmdRes<?> apiRes = null;

                switch (cmdInfo.get()) {
                    case CabinetCmd.CMD_REG_CABINET://注册智能柜
                    case CabinetCmd.CMD_UPDATE_CABINET://更新智能柜
                        apiRes = handleRegCabinetCmd(cmdInfo.get(), dataInfo);
                        break;
                    case CabinetCmd.CMD_PING://ping
                        apiRes = handlePingCmd(cmdInfo.get());
                        break;
                    case CabinetCmd.CMD_GET_CABINET_INFO://获取警柜信息指令
                        apiRes = handleGetCabinetInfoCmd(cmdInfo.get(), dataInfo);
                        break;
                    case CabinetCmd.CMD_ADD_BOX_INFO://添加箱门信息
                    case CabinetCmd.CMD_UPDATE_BOX_INFO://添加箱门信息
                        apiRes=handleRegOrUpCabinetBoxCmd(cmdInfo.get(),dataInfo);
                        break;
                    case CabinetCmd.CMD_DEL_BOX_INFO://删除箱门信息
                        apiRes=handleDelCabinetBoxCmd(cmdInfo.get(),dataInfo);
                        break;
                    case CabinetCmd.CMD_EXPORT_SIZE_TYPE_ORG_INFO://同步装备号型类型信息、组织机构信息
                        apiRes=handleExportSizeAndTypeCmd(cmdInfo.get(),dataInfo);
                        break;
                    case CabinetCmd.ADD_USER://添加人员信息
                        apiRes=handleAddUserCmd(cmdInfo.get(),dataInfo);
                        break;
                    case CabinetCmd.DELETE_USER://删除人员信息
                        apiRes=handleDelUserCmd(cmdInfo.get(),dataInfo);
                        break;
                    case CabinetCmd.UPDATE_USER://编辑人员信息
                        apiRes=handleUpdateUserCmd(cmdInfo.get(),dataInfo);
                        break;
                    case CabinetCmd.GET_LIST_BY_ORG://获取组织机构下人员信息
                        apiRes=handleGetListByOrgCmd(cmdInfo.get(),dataInfo);
                        break;
                    case CabinetCmd.ADD_USER_FACEINFO://添加人员面部信息
                        apiRes=handleAddUserFaceInfoCmd(cmdInfo.get(),dataInfo);
                        break;
                    case CabinetCmd.UPDATE_USER_FACEINFO://修改人员面部信息
                    case CabinetCmd.DEL_USER_FACEINFO://删除人员面部信息
                        apiRes=handleDelOrUpdateUserFaceInfoCmd(cmdInfo.get(),dataInfo);
                        break;
                    case CabinetCmd.SEARCH_USER_FACE_INFO://查询人脸信息
                        apiRes=handleSearchFaceInfoCmd(cmdInfo.get(),dataInfo);
                        break;
                    case CabinetCmd.ADD_FINGER_INFO://添加人员指纹信息
                    case CabinetCmd.UPDATE_FINGER_INFO://修改人员指纹信息
                        apiRes=handleAddOrUpdateFingerInfoCmd(cmdInfo.get(),dataInfo);
                        break;
                    case CabinetCmd.SEARCH_FINGER_INFO://查询人员指纹信息
                        apiRes=handleSearchFingerInfoCmd(cmdInfo.get(),dataInfo);
                        break;
                    case CabinetCmd.DELETE_FINGER_INFO://删除人员指纹信息
                        apiRes=handleDeleteFingerInfoCmd(cmdInfo.get(),dataInfo);
                        break;
                    case CabinetCmd.UPLOAD_USER_PHOTO://上传人员照片
                        apiRes=handleUploadUserPhotoCmd(cmdInfo.get(),dataInfo);
                        break;
                    case CabinetCmd.POLICE_BIND_BOX://人员绑定箱门、解绑箱门
                        apiRes=handlePoliceBindBoxFormCabCmd(cmdInfo.get(),dataInfo);
                        break;
                    case CabinetCmd.BOX_BIND_EQUIPMENT://箱门绑定装备、解绑装备
                        apiRes=handleBoxBindEquipmentCmd(cmdInfo.get(),dataInfo);
                        break;
                    case CabinetCmd.CABINET_LOGS_RECORD://出入库日志上报
                        apiRes=handleCabinetLogsRecordCmd(cmdInfo.get(),dataInfo);
                        break;
                    case CabinetCmd.UPLOAD_LOGS://上传日志内容
                        apiRes=handleUploadLogsCmd(cmdInfo.get(),dataInfo);
                        break;
                    case CabinetCmd.GET_VERSION://获取版本号
                        apiRes=handleGetVersionCmd(cmdInfo.get(),dataInfo);
                        break;
                    case CabinetCmd.GET_LOGLIST_RSP://日志内容返回
                        apiRes=handleGetLogListCmd(cmdInfo.get(),dataInfo);
                        break;
                    case CabinetCmd.GET_LOGFILE_RSP://日志文件内容返回
                        apiRes=handleGetLogFileCmd(cmdInfo.get(),dataInfo);
                        break;
                    case CabinetCmd.GET_CURRENT_TIME://获取当前时间
                        apiRes=handleGetCurrentTimeCmd(cmdInfo.get(),dataInfo);
                        break;
                    case CabinetCmd.GET_EQS_STATE://获取epc状态
                        apiRes=handleGetEqsStateCmd(cmdInfo.get(),dataInfo);
                        break;
                    default:
                        apiRes = WsCmdRes.failure(JYZBConstant.CABINET_CMD_ERROR_KEY,
                                StrUtil.format("{},当前请求指令：{}", WsCabinetExceptionEnum.WS_CABINET_CMD_NOT_EXISTS_ERROR.getMessage(), cmdInfo.get()));
                        break;
                }
                log.info("[智能柜业务处理]|[组织机构={},智能柜={}],正在执行[{}]业务。", orgCode, devSn, cmdInfo.get());
                sendMessage(session, apiRes);
            } else {
                sendMessage(session, WsCmdRes.failure(JYZBConstant.CABINET_CMD_ERROR_KEY, WsCabinetExceptionEnum.WS_CABINET_REQ_CMD_FORMAT_ERROR.getMessage()));
            }
        } catch (Exception ex) {
            log.error("[智能柜业务处理异常]|异常信息：{}", ex.getMessage());
            sendMessage(session, WsCmdRes.failure(JYZBConstant.CABINET_CMD_ERROR_KEY, WsCabinetExceptionEnum.WS_CABINET_REQ_CMD_FORMAT_ERROR.getMessage()));
        }

    }



    /**
     * 获取日志文件
     * @param cmd
     * @param dataInfo
     * @return
     */
    private WsCmdRes<?> handleGetLogFileCmd(String cmd, Optional<String> dataInfo) {
        if (dataInfo.isPresent()) {
            try {
                CabinetLogFileReq req = JSON.parseObject(dataInfo.get(), CabinetLogFileReq.class);

                if(StrUtil.isEmpty((req.getOrgCode())) || StrUtil.isEmpty((req.getDevSn())) || StrUtil.isEmpty((req.getFileName())))
                {
                    return WsCmdRes.failure(cmd, CabinetExceptionEnum.PARAMETER_ERROR.getMessage());
                }
                String key = req.getOrgCode() + "_" + req.getDevSn() + "_" + req.getFileName();
                redisCache.put(key,
                        req.getFile(), (long)(60 * 1));

                return WsCmdRes.success(cmd,null);

            } catch (RuntimeException ex) {
                return WsCmdRes.failure(cmd, ex.getMessage());
            }
        } else {
            return WsCmdRes.failure(cmd, WsCabinetExceptionEnum.WS_CABINET_BIZ_PARAM_ERROR.getMessage());
        }
    }

    /**
     * 获取日志列表
     * @param cmd
     * @param dataInfo
     * @return
     */
    private WsCmdRes<?> handleGetLogListCmd(String cmd, Optional<String> dataInfo) {
        if (dataInfo.isPresent()) {
            try {
                CabinetLogReq req = JSON.parseObject(dataInfo.get(), CabinetLogReq.class);

                redisCache.put(req.getOrgCode() + "_" + req.getDevSn(), JSON.toJSONString(req.getLogList()), (long)(1 * 60));
                return WsCmdRes.success(cmd,null);

            } catch (RuntimeException ex) {
                return WsCmdRes.failure(cmd, ex.getMessage());
            }
        } else {
            return WsCmdRes.failure(cmd, WsCabinetExceptionEnum.WS_CABINET_BIZ_PARAM_ERROR.getMessage());
        }
    }


    /**
     * 关闭连接
     */
    @OnClose
    public void disconnect(Session session) {
        try {
            log.info("[Ws正在断开连接]|[组织机构={},设备编号={}]", orgCode, devSn);
            String keyVal = getCabinetWsKey(orgCode, devSn);
            WsCabinetAppServer oldSession = sessionMap.get(keyVal);
            eventPublisher.cabinetOfflineEventPublish(new CabinetEventVo(orgCode, devSn));
            if (null != oldSession) {
                //设置离线
                cabinetAppBizService.updateCabinetState(orgCode, devSn, CabinetStateEnum.OFFLINE);
                oldSession.cabinetSession.close();
                sessionMap.remove(keyVal);
                currentConnectTotal.decrementAndGet();
                log.info("[Ws断开成功]|[组织机构={},设备编号={}],当前连接数：{}", orgCode, devSn, currentConnectTotal.get());
            }
        } catch (Exception ex) {
            log.error("[Ws断开异常]|[组织机构={},设备编号={}],异常信息：{}", orgCode, devSn, ex.getMessage());
        }
    }

    /**
     * 发送消息方法
     *
     * @param session 客户端与socket建立的会话
     * @param data    消息
     * @throws IOException
     */
    public void sendMessage(Session session, Object data) {
        try {
            if (session != null) {
                if (data instanceof String) {
                    session.getBasicRemote().sendText((String) data);
                } else {
                    session.getBasicRemote().sendText(JSON.toJSONString(data));
                }
            }
        } catch (Exception ex) {
            log.error("[Ws消息发送异常]|异常信息：{}", ex.getMessage());
        }
    }
    public String sendMessage1(Session session, Object data, String infoKey) {
        try {
            if (session != null) {
                if (data instanceof String) {
                    session.getBasicRemote().sendText((String) data);
                } else {
                    session.getBasicRemote().sendText(JSON.toJSONString(data));
                }
                while (true) {
                    if (ObjectUtil.isNotNull(redisCache) && redisCache.contains(infoKey)){
                        return redisCache.get(infoKey);
                    }
                }

            } else {
                return "session为空了";
            }
        } catch (Exception ex) {
            log.error("[Ws消息发送异常]|异常信息：{}", ex.getMessage());
            return "[Ws消息发送异常]|异常信息：{}" + ex.getMessage();
        }
    }

    private String getCabinetWsKey(String orgCode, String devSn) {
        return StrUtil.format("{}_{}_{}", CB_WS_PREFIX, orgCode, devSn);
    }

    /**
     * 处理单警柜注册和更新指令
     *
     * @param cmd     指令
     * @param dataVal 注册数据
     */
    private WsCmdRes<String> handleRegCabinetCmd(String cmd, Optional<String> dataVal) {
        if (dataVal.isPresent()) {
            try {

                RegCabinetReq req = JSON.parseObject(dataVal.get(), RegCabinetReq.class);
//                req.setDevSn(devSn);
//                req.setOrgCode(orgCode);
                String cbId;
                //单纯业务操作的区分，最终实现是一致的
                if (StrUtil.isNotBlank(req.getCabinetId())) {
                    cbId = cabinetAppBizService.updateCabinet(req);
                } else {
                    cbId = cabinetAppBizService.regCabinet(req);
                }
                return WsCmdRes.success(cmd, cbId);
            } catch (RuntimeException ex) {
                return WsCmdRes.failure(cmd, ex.getMessage());
            }
        } else {
            return WsCmdRes.failure(cmd, WsCabinetExceptionEnum.WS_CABINET_BIZ_PARAM_ERROR.getMessage());
        }

    }


    /**
     * 获取警柜信息
     *
     * @param cmd     指令信息
     * @param dataVal
     */
    private WsCmdRes<CabinetDto> handleGetCabinetInfoCmd(String cmd, Optional<String> dataVal) {
        if (dataVal.isPresent()) {
            try {
                CabinetReq req = JSON.parseObject(dataVal.get(), CabinetReq.class);
                CabinetDto cabinetDto = cabinetAppBizService.showOneCabinet(req);
                return WsCmdRes.success(cmd,cabinetDto);

            } catch (RuntimeException ex) {
                return WsCmdRes.failure(cmd, ex.getMessage());
            }
        } else {
            return WsCmdRes.failure(cmd, WsCabinetExceptionEnum.WS_CABINET_BIZ_PARAM_ERROR.getMessage());
        }
    }

    /**
     * 添加箱门信息指令
     * @param
     * @param dataInfo
     * @return
     */
    private WsCmdRes<CabinetDto> handleRegOrUpCabinetBoxCmd(String cmd, Optional<String> dataInfo) {
        if (dataInfo.isPresent()) {
            try {
                UpdateCabinetReq req = JSON.parseObject(dataInfo.get(), UpdateCabinetReq.class);
                List<String> collect = req.getCabinetBoxList().stream().map(UpdateCabinetBoxReq::getId).collect(Collectors.toList());
                CabinetDto cabinetDto;
                if (collect.size()>0 || CollectionUtil.isNotEmpty(collect)){
                    cabinetDto=cabinetAppBizService.regCabinetBox(req);
                }else {

                    cabinetDto = cabinetAppBizService.upCabinetBox(req);
                }
                return WsCmdRes.success(cmd,cabinetDto);

            } catch (RuntimeException ex) {
                return WsCmdRes.failure(cmd, ex.getMessage());
            }
        } else {
            return WsCmdRes.failure(cmd, WsCabinetExceptionEnum.WS_CABINET_BIZ_PARAM_ERROR.getMessage());
        }
    }

    /**
     * 删除箱门信息
     * @param cmd
     * @param dataInfo
     * @return
     */
    private WsCmdRes<CabinetDto> handleDelCabinetBoxCmd(String cmd, Optional<String> dataInfo) {
        if (dataInfo.isPresent()) {
            try {
                UpdateCabinetReq req = JSON.parseObject(dataInfo.get(), UpdateCabinetReq.class);

                CabinetDto cabinetDto = cabinetAppBizService.delCabinetBox(req);

                return WsCmdRes.success(cmd,cabinetDto);

            } catch (RuntimeException ex) {
                return WsCmdRes.failure(cmd, ex.getMessage());
            }
        } else {
            return WsCmdRes.failure(cmd, WsCabinetExceptionEnum.WS_CABINET_BIZ_PARAM_ERROR.getMessage());
        }
    }

    /**
     * 同步号型类型和组织机构
     * @param cmd
     * @param dataInfo
     * @return
     */
    private WsCmdRes<String> handleExportSizeAndTypeCmd(String cmd, Optional<String> dataInfo) {
        if (dataInfo.isPresent()) {
            try {
                QueryEquipmentTypeReq req = JSON.parseObject(dataInfo.get(), QueryEquipmentTypeReq.class);

                String data = cabinetAppBizService.exprotSizeAndType(req);

                return WsCmdRes.success(cmd,data);

            } catch (RuntimeException ex) {
                return WsCmdRes.failure(cmd, ex.getMessage());
            }
        } else {
            return WsCmdRes.failure(cmd, WsCabinetExceptionEnum.WS_CABINET_BIZ_PARAM_ERROR.getMessage());
        }
    }

    /**
     * 新增警员信息
     * @param cmd
     * @param dataInfo
     * @return
     */
    private WsCmdRes<PolicemanDto> handleAddUserCmd(String cmd, Optional<String> dataInfo) {
        if (dataInfo.isPresent()) {
            try {
                CabinetPolicemanReq req = JSON.parseObject(dataInfo.get(), CabinetPolicemanReq.class);

                PolicemanDto data = cabinetAppBizService.addPolicemanFromCab(req);

                return WsCmdRes.success(cmd,data);

            } catch (RuntimeException ex) {
                return WsCmdRes.failure(cmd, ex.getMessage());
            }
        } else {
            return WsCmdRes.failure(cmd, WsCabinetExceptionEnum.WS_CABINET_USER_PARAM_ERROR.getMessage());
        }
    }

    /**
     * 删除警员信息
     * @param cmd
     * @param dataInfo
     * @return
     */
    private WsCmdRes<PolicemanDto> handleDelUserCmd(String cmd, Optional<String> dataInfo) {
        if (dataInfo.isPresent()) {
            try {
                CabinetPolicemanReq req = JSON.parseObject(dataInfo.get(), CabinetPolicemanReq.class);

                PolicemanDto data = cabinetAppBizService.delPolicemanFromCab(req);

                return WsCmdRes.success(cmd,data);

            } catch (RuntimeException ex) {
                return WsCmdRes.failure(cmd, ex.getMessage());
            }
        } else {
            return WsCmdRes.failure(cmd, WsCabinetExceptionEnum.WS_CABINET_USER_PARAM_ERROR.getMessage());
        }
    }

    /**
     * 更新警员信息
     * @param cmd
     * @param dataInfo
     * @return
     */
    private WsCmdRes<PolicemanDto> handleUpdateUserCmd(String cmd, Optional<String> dataInfo) {
        if (dataInfo.isPresent()) {
            try {
                CabinetPolicemanReq req = JSON.parseObject(dataInfo.get(), CabinetPolicemanReq.class);

                PolicemanDto data = cabinetAppBizService.UpdatePoliceFromCab(req);

                return WsCmdRes.success(cmd,data);

            } catch (RuntimeException ex) {
                return WsCmdRes.failure(cmd, ex.getMessage());
            }
        } else {
            return WsCmdRes.failure(cmd, WsCabinetExceptionEnum.WS_CABINET_USER_PARAM_ERROR.getMessage());
        }
    }

    /**
     * 根据组织机构查询对应警员信息
     * @param cmd
     * @param dataInfo
     * @return
     */
    private WsCmdRes<List<CabinetPoliceDto>> handleGetListByOrgCmd(String cmd, Optional<String> dataInfo) {
        if (dataInfo.isPresent()) {
            try {
                PolicemanReq req = JSON.parseObject(dataInfo.get(), PolicemanReq.class);

                List<CabinetPoliceDto> data = cabinetAppBizService.GetListByOrg(req);

                return WsCmdRes.success(cmd,data);

            } catch (RuntimeException ex) {
                return WsCmdRes.failure(cmd, ex.getMessage());
            }
        } else {
            return WsCmdRes.failure(cmd, WsCabinetExceptionEnum.WS_CABINET_USER_PARAM_ERROR.getMessage());
        }
    }




    /**
     * 删除、修改警员人脸信息
     * @param cmd
     * @param dataInfo
     * @return
     */
    private WsCmdRes<CabinetPoliceDto> handleDelOrUpdateUserFaceInfoCmd(String cmd, Optional<String> dataInfo) {
        if (dataInfo.isPresent()) {
            try {
                CabinetPolicemanReq req = JSON.parseObject(dataInfo.get(), CabinetPolicemanReq.class);

                CabinetPoliceDto data = cabinetAppBizService.UpdateFaceInfo(req);

                return WsCmdRes.success(cmd,data);

            } catch (RuntimeException ex) {
                return WsCmdRes.failure(cmd, ex.getMessage());
            }
        } else {
            return WsCmdRes.failure(cmd, WsCabinetExceptionEnum.WS_CABINET_USER_PARAM_ERROR.getMessage());
        }
    }

    /**
     * 新增警员人脸信息
     * @param cmd
     * @param dataInfo
     * @return
     */
    private WsCmdRes<CabinetPoliceDto> handleAddUserFaceInfoCmd(String cmd, Optional<String> dataInfo) {
        if (dataInfo.isPresent()) {
            try {
                CabinetPolicemanReq req = JSON.parseObject(dataInfo.get(), CabinetPolicemanReq.class);

                CabinetPoliceDto data = cabinetAppBizService.AddFaceInfo(req);

                return WsCmdRes.success(cmd,data);

            } catch (RuntimeException ex) {
                return WsCmdRes.failure(cmd, ex.getMessage());
            }
        } else {
            return WsCmdRes.failure(cmd, WsCabinetExceptionEnum.WS_CABINET_USER_PARAM_ERROR.getMessage());
        }
    }

    /**
     * 查询人脸信息
     * @param
     * @param dataInfo
     * @return
     */
    private WsCmdRes<Policeman> handleSearchFaceInfoCmd(String cmd, Optional<String> dataInfo) {
        if (dataInfo.isPresent()) {
            try {
                CabinetPolicemanReq req = JSON.parseObject(dataInfo.get(), CabinetPolicemanReq.class);

                Policeman data = cabinetAppBizService.SearchFaceInfo(req);

                return WsCmdRes.success(cmd,data);

            } catch (RuntimeException ex) {
                return WsCmdRes.failure(cmd, ex.getMessage());
            }
        } else {
            return WsCmdRes.failure(cmd, WsCabinetExceptionEnum.WS_CABINET_USER_PARAM_ERROR.getMessage());
        }
    }

    /**
     * 删除指纹信息
     * @param cmd
     * @param dataInfo
     * @return
     */
    private WsCmdRes<CabinetPoliceDto> handleDeleteFingerInfoCmd(String cmd, Optional<String> dataInfo) {
        if (dataInfo.isPresent()) {
            try {
                CabinetPolicemanReq req = JSON.parseObject(dataInfo.get(), CabinetPolicemanReq.class);

                CabinetPoliceDto data = cabinetAppBizService.deleteFinger(req);

                return WsCmdRes.success(cmd,data);

            } catch (RuntimeException ex) {
                return WsCmdRes.failure(cmd, ex.getMessage());
            }
        } else {
            return WsCmdRes.failure(cmd, WsCabinetExceptionEnum.WS_CABINET_USER_PARAM_ERROR.getMessage());
        }
    }

    /**
     * 查询指纹信息
     * @param cmd
     * @param dataInfo
     * @return
     */
    private WsCmdRes<CabinetPoliceDto> handleSearchFingerInfoCmd(String cmd, Optional<String> dataInfo) {
        if (dataInfo.isPresent()) {
            try {
                PolicemanFingerReq req = JSON.parseObject(dataInfo.get(), PolicemanFingerReq.class);

                CabinetPoliceDto data = cabinetAppBizService.searchFingerInfo(req);

                return WsCmdRes.success(cmd,data);

            } catch (RuntimeException ex) {
                return WsCmdRes.failure(cmd, ex.getMessage());
            }
        } else {
            return WsCmdRes.failure(cmd, WsCabinetExceptionEnum.WS_CABINET_USER_PARAM_ERROR.getMessage());
        }
    }


    /**
     * 新增、修改指纹信息
     * @param cmd
     * @param dataInfo
     * @return
     */
    private WsCmdRes<CabinetPoliceDto> handleAddOrUpdateFingerInfoCmd(String cmd, Optional<String> dataInfo) {
        if (dataInfo.isPresent()) {
            try {
                CabinetPolicemanReq req = JSON.parseObject(dataInfo.get(), CabinetPolicemanReq.class);
                List<Integer> collect = req.getFingerList().stream().map(UpdatePoliceFingerReq::getId).collect(Collectors.toList());
                CabinetPoliceDto data;
                if (collect.size()>0 || CollectionUtil.isNotEmpty(collect)){

                    data = cabinetAppBizService.updateFingerInfo(req);
                }else {
                    data = cabinetAppBizService.addFingerInfo(req);

                }

                return WsCmdRes.success(cmd,data);

            } catch (RuntimeException ex) {
                return WsCmdRes.failure(cmd, ex.getMessage());
            }
        } else {
            return WsCmdRes.failure(cmd, WsCabinetExceptionEnum.WS_CABINET_USER_PARAM_ERROR.getMessage());
        }
    }

    /**
     * 上传人员照片
     * @param cmd
     * @param dataInfo
     * @return
     */
    private WsCmdRes<UploadPolicePhotoDto> handleUploadUserPhotoCmd(String cmd, Optional<String> dataInfo) {
        if (dataInfo.isPresent()) {
            try {
                UploadPolicePhotoReq req = JSON.parseObject(dataInfo.get(), UploadPolicePhotoReq.class);

                UploadPolicePhotoDto data = cabinetAppBizService.uploadPolicePhoto(req);


                return WsCmdRes.success(cmd,data);

            } catch (RuntimeException ex) {
                return WsCmdRes.failure(cmd, ex.getMessage());
            }
        } else {
            return WsCmdRes.failure(cmd, WsCabinetExceptionEnum.WS_CABINET_USER_PARAM_ERROR.getMessage());
        }
    }

    /**
     * 人员绑定箱门、解绑箱门
     * @param
     * @param dataInfo
     * @return
     */
    private WsCmdRes<CabinetPoliceDto> handlePoliceBindBoxFormCabCmd(String cmd, Optional<String> dataInfo) {
        if (dataInfo.isPresent()) {
            try {
                CabinetPolicemanReq req = JSON.parseObject(dataInfo.get(), CabinetPolicemanReq.class);

                CabinetPoliceDto data = cabinetAppBizService.policeBindBoxFormCab(req);

                return WsCmdRes.success(cmd,data);

            } catch (RuntimeException ex) {
                return WsCmdRes.failure(cmd, ex.getMessage());
            }
        } else {
            return WsCmdRes.failure(cmd, WsCabinetExceptionEnum.WS_CABINET_USER_PARAM_ERROR.getMessage());
        }
    }

    /**
     * 获取版本
     * @param cmd
     * @param dataInfo
     * @return
     */
    private WsCmdRes<Application> handleGetVersionCmd(String cmd, Optional<String> dataInfo) {
        if (dataInfo.isPresent()) {
            try {
                ApplicationReq req = JSON.parseObject(dataInfo.get(), ApplicationReq.class);

                Application data = cabinetAppBizService.getVersion(req);

                return WsCmdRes.success(cmd,data);

            } catch (RuntimeException ex) {
                return WsCmdRes.failure(cmd, ex.getMessage());
            }
        } else {
            return WsCmdRes.failure(cmd, WsCabinetExceptionEnum.WS_CABINET_USER_PARAM_ERROR.getMessage());
        }
    }

    /**
     * 上传日志
     * @param cmd
     * @param dataInfo
     * @return
     */
    private WsCmdRes<CabinetPoliceDto> handleUploadLogsCmd(String cmd, Optional<String> dataInfo) {
        if (dataInfo.isPresent()) {
            try {
                CabinetPolicemanReq req = JSON.parseObject(dataInfo.get(), CabinetPolicemanReq.class);

                CabinetPoliceDto data = cabinetAppBizService.uploadLogs(req);

                return WsCmdRes.success(cmd,data);

            } catch (RuntimeException ex) {
                return WsCmdRes.failure(cmd, ex.getMessage());
            }
        } else {
            return WsCmdRes.failure(cmd, WsCabinetExceptionEnum.WS_CABINET_USER_PARAM_ERROR.getMessage());
        }
    }

    /**
     * 出入日志上传
     * @param cmd
     * @param dataInfo
     * @return
     */
    private WsCmdRes<Boolean> handleCabinetLogsRecordCmd(String cmd, Optional<String> dataInfo) {
        if (dataInfo.isPresent()) {
            try {
                List<SummaryLogReq> req = JSON.parseArray(dataInfo.get(), SummaryLogReq.class);

                Boolean isSuccess = cabinetAppBizService.cabinetLogsRecord(req);

                return isSuccess ? WsCmdRes.success(cmd) : WsCmdRes.failure(cmd, "失败");

            } catch (RuntimeException ex) {
                return WsCmdRes.failure(cmd, ex.getMessage());
            }
        } else {
            return WsCmdRes.failure(cmd, WsCabinetExceptionEnum.WS_CABINET_USER_PARAM_ERROR.getMessage());
        }
    }

    /**
     * 装备绑定箱门、解绑箱门
     * @param cmd
     * @param dataInfo
     * @return
     */
    private WsCmdRes<String> handleBoxBindEquipmentCmd(String cmd, Optional<String> dataInfo) {
        if (dataInfo.isPresent()) {
            try {
                PoliceEquipmentDetailReq req = JSON.parseObject(dataInfo.get(), PoliceEquipmentDetailReq.class);

                String data = cabinetAppBizService.boxBindEquipment(req);

                return WsCmdRes.success(cmd,data);

            } catch (RuntimeException ex) {
                return WsCmdRes.failure(cmd, ex.getMessage());
            }
        } else {
            return WsCmdRes.failure(cmd, WsCabinetExceptionEnum.WS_CABINET_USER_PARAM_ERROR.getMessage());
        }
    }

    //获取当前时间
    private WsCmdRes<Date> handleGetCurrentTimeCmd(String cmd, Optional<String> dataInfo) {
        if (dataInfo.isPresent()) {
            try {
                Date data = cabinetAppBizService.getCurrentTime();

                return WsCmdRes.success(cmd,data);

            } catch (RuntimeException ex) {
                return WsCmdRes.failure(cmd, ex.getMessage());
            }
        } else {
            return WsCmdRes.failure(cmd, WsCabinetExceptionEnum.WS_CABINET_USER_PARAM_ERROR.getMessage());
        }
    }

    //获取当前的绑定箱门的出入库状态（修改最新的出入库状态以及修改库存最新出入库汇总）
    private WsCmdRes<Boolean> handleGetEqsStateCmd(String cmd, Optional<String> dataInfo) {
        if (dataInfo.isPresent()) {
            try {
                PoliceEquipmentDetailReq req = JSON.parseObject(dataInfo.get(), PoliceEquipmentDetailReq.class);
                 Boolean isSuccess  = cabinetAppBizService.getEqsState(req);

                return isSuccess ? WsCmdRes.success(cmd) : WsCmdRes.failure(cmd, "失败");

            } catch (RuntimeException ex) {
                return WsCmdRes.failure(cmd, ex.getMessage());
            }
        } else {
            return WsCmdRes.failure(cmd, WsCabinetExceptionEnum.WS_CABINET_USER_PARAM_ERROR.getMessage());
        }
    }



    /**
     * 响应心跳包
     *
     * @param cmd 指令
     */
    private WsCmdRes<String> handlePingCmd(String cmd) {
        log.info("{}_{}", this.orgCode, this.devSn);
        return WsCmdRes.success(cmd, JYZBConstant.CABINET_PONG_KEY);
    }
}
