package cn.component.message.mq;

import cn.component.message.mq.base.HandleRabbitBase;
import cn.orm.sqltoy.plus.query.QueryWrapper;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import cn.api.atv.AtvTtsCtrl;
import cn.facade.constant.AtvConst;
import cn.facade.constant.WebsocketConst;
import cn.orm.sqltoy.plus.Wrappers;
import cn.orm.sqltoy.plus.query.LambdaQueryWrapper;
import cn.pojo.atv.AtvBoardCardFault;
import cn.pojo.atv.AtvCarriage;
import cn.pojo.atv.AtvEquipment;
import cn.pojo.atv.AtvEquipmentLog;
import cn.pojo.atv.AtvLineSite;
import cn.pojo.atv.AtvTrainWorkingLog;
import cn.pojo.atv.AtvTts;
import cn.pojo.atv.AtvWarnLog;
import cn.pojo.atv.vo.PopupResult;
import cn.util.core.IsKit;
import cn.util.core.LogKit;
import cn.util.time.TimeKit;
import cn.util.uuid.UUIDKit;
import java.util.*;
import java.util.concurrent.TimeUnit;


/**
 * ATV消息得处理者
 * 需要创建队列atv.websocket.handle
 **/
@Component
@RabbitListener(queues = "atv.websocket.handle", ackMode = "AUTO")
public class HandleRabbitMsg extends HandleRabbitBase
{
    protected void _distribute(Integer rawCode, JSONObject jsonObject, String userIdLine, String userIdTrain) {
        switch (rawCode.intValue()) {
            //广播状态信息上传(数字)",广播系统运营状态上传接口
            case AtvConst.CMD_CODE_NUM2:
                _handleCmd2Msg(jsonObject, userIdLine, userIdTrain);
                break;
            //PIS系统设备状态上传接口 数据上传websocket板卡状态数据
            case AtvConst.CMD_CODE_NUM3:
                _handleCmd3Msg(jsonObject, userIdLine, userIdTrain);
                break;
            //设备故障信息上传接口
            case AtvConst.CMD_CODE_NUM4:
                _handleCmd4Msg(jsonObject);
                break;
            //TTS上传音频文件完成  列车TTS设备 ->运维平台
            case AtvConst.CMD_CODE_NUM6:
                _handleCmd6Msg(jsonObject, userIdTrain);
                break;
            //设备上传日志/音频完成 列车->列车运维平台
            case AtvConst.CMD_CODE_NUM15:
                _handleCmd15Msg(jsonObject);
                break;
            case AtvConst.CMD_CODE_NUM16:
                _handeCmd16Msg(jsonObject);
                break;
            case AtvConst.CMD_CODE_NUM17:
                _handleCmd17Msg(jsonObject);
                break;
            case AtvConst.CMD_CODE_NUM18:
                _handleCmd18Msg(jsonObject);
                break;
            case AtvConst.CMD_CODE_NUM20:
                _handleCmd20Msg(jsonObject);
                break;
            default:
                break;
        }
    }
    private void _handleCmd20Msg(JSONObject jsonObj){
        influxDbUtil.insertJSON(AtvConst.INFLUXDB_TABLE_LISTENER, jsonObj, TimeUnit.SECONDS);
    }
    private void _handleCmd18Msg(JSONObject jsonObj){
        influxDbUtil.insertJSON(AtvConst.INFLUXDB_TABLE_COMMAND, jsonObj, TimeUnit.SECONDS);
    }


    private void _handleCmd17Msg(JSONObject jsonObj){
        influxDbUtil.insertJSON(AtvConst.INFLUXDB_TABLE_CROWEDS, jsonObj, TimeUnit.SECONDS);
    }

    private void _handeCmd16Msg(JSONObject jsonObj) {
        //BJTU 写入Influxdb 开始
        influxDbUtil.insertJSON(AtvConst.INFLUXDB_TABLE_PORT, jsonObj, TimeUnit.SECONDS);
        influxDbUtil.insertJSON(AtvConst.INFLUXDB_TABLE_RINGNETWORK, jsonObj, TimeUnit.SECONDS);
        // BJTU 写入Influxdb 结束
    }

    private void _handleCmd2Msg(JSONObject jsonObject, String userIdLine, String userIdTrain) {
        // BJTU 写入Influxdb 开始
        influxDbUtil.insertJSON(AtvConst.INFLUXDB_TABLE_CARRIAGE, jsonObject, TimeUnit.SECONDS);
        influxDbUtil.insertJSON(AtvConst.INFLUXDB_TABLE_ALARMSTATE, jsonObject, TimeUnit.SECONDS);
        // BJTU 写入Influxdb 结束
        /*发送广播状态websocket开始*/
        JSONObject webTrainLogJson = new JSONObject();
        webTrainLogJson.put(WebsocketConst.MSG_CMD, "trainLog");
        webTrainLogJson.put(WebsocketConst.MSG_TXT, jsonObject);
        atvWebSocket.sendOneMessage("web", userIdLine, webTrainLogJson.toString());
        atvWebSocket.sendOneMessage("web", userIdTrain, webTrainLogJson.toString());

        /*发送广播状态websocket结束*/
        String msg = jsonObject.getString("data");
        if (IsKit.isNull(msg)) {
            LogKit.info("接收到的消息报文(Broadcast)的数据为空!");
            return;
        }
        JSONObject data = JSONObject.parseObject(msg);
        JSONArray carriages = JSONArray.parseArray(data.getString("carriages"));
        for (Object carriage : carriages) {
            JSONObject carriageInfo = JSONObject.parseObject(carriage.toString());
            String carriageSn = carriageInfo.getString("carNo");//车厢编号
            String equipmentSn = carriageInfo.getString("deviceNo");//设备编号

            AtvCarriage atvCarriage = (AtvCarriage) redisCache.hget("carriage", atvTrain.getId() + carriageSn);
            if (IsKit.isNull(atvCarriage)) {
                LogKit.info("未找到车厢:" + jsonObject);
                return;
            }

            AtvEquipment atvEquipment = (AtvEquipment) redisCache.hget("equipment", atvCarriage.getId() + equipmentSn);
            if (IsKit.isNull(atvEquipment)) {
                LogKit.info("未找到设备:" + jsonObject);
                return;
            }

            String LineID = carriageInfo.getString("LineID");//区间编号
            String startID = carriageInfo.getString("startID");//起始站点编号
            String terminalID = carriageInfo.getString("terminalID");//终点站点编号
            String nowID = carriageInfo.getString("nowID");//当前站点编号
            Integer PAstate = carriageInfo.getInteger("PAstate");//1全自动/2半自动/3手动
            Integer PAmodel = carriageInfo.getInteger("PAmodel");//0无广播/1自动/2OCC/3紧急/4媒体/5人工/6车内人工/7车外人工/8背景音乐/9预留/10外部音频输入/11开门提示音
            Integer MICmodel = carriageInfo.getInteger("MICmodel");//0司机对讲/1报警对讲/
            String PAcarMS = carriageInfo.getString("PAcarMS");//工作的广播主机设备编号
            String carDirection = carriageInfo.getString("carDirection");//列车运行方向车厢编号
            Integer PAupdown = carriageInfo.getInteger("PAupdown");//0上行,1下行
            String emergentPAID = carriageInfo.getString("emergentPAID");//紧急广播ID
            Integer emergentPANO = carriageInfo.getInteger("emergentPANO");//紧急广播次数
            Integer PAstartflag = carriageInfo.getInteger("PAstartflag");//语音报站开始标志位：0无广播，1到站广播//进站广播，2预报站广播//离站广播，3停止广播，4紧急广播
            String playfilename = carriageInfo.getString("playfilename");///home/001.mp3//报站文件名
            Integer opendoorDir = carriageInfo.getInteger("opendoorDir");//开门侧信息：0不开，1左侧，2右侧，3左右同时开

            AtvTrainWorkingLog atvTrainWorkingLog = new AtvTrainWorkingLog();
            atvTrainWorkingLog.setTrainWorkingLogType(1);
            atvTrainWorkingLog.setCountryId(atvCountry.getId());
            atvTrainWorkingLog.setAreaId(atvArea.getId());
            atvTrainWorkingLog.setLineId(atvLine.getId());
            atvTrainWorkingLog.setTrainId(atvTrain.getId());
            atvTrainWorkingLog.setCarriageId(atvCarriage.getId());
            atvTrainWorkingLog.setEquipmentId(atvEquipment.getId());
            atvTrainWorkingLog.setEquipmentType(atvEquipment.getEquipmentType());
            atvTrainWorkingLog.setSectionSn(LineID);
            atvTrainWorkingLog.setStartSiteSn(startID);
            atvTrainWorkingLog.setEndSiteSn(terminalID);
            atvTrainWorkingLog.setNowSiteSn(nowID);
            atvTrainWorkingLog.setPaState(PAstate);
            atvTrainWorkingLog.setPaModel(PAmodel);
            atvTrainWorkingLog.setMicModel(MICmodel);
            atvTrainWorkingLog.setPaCarms(PAcarMS);
            atvTrainWorkingLog.setCarDirection(carDirection);
            atvTrainWorkingLog.setDirection(PAupdown);
            atvTrainWorkingLog.setEmergentPaid(emergentPAID);
            atvTrainWorkingLog.setEmergentPano(emergentPANO);
            atvTrainWorkingLog.setPaStartFlag(PAstartflag);
            atvTrainWorkingLog.setPlayFileName(playfilename);
            atvTrainWorkingLog.setOpenDoorDirection(opendoorDir);
            atvTrainWorkingLog.setId(UUIDKit.fastSimpleUUID());
            atvTrainWorkingLogs.add(atvTrainWorkingLog);
            //atvTrainWorkingLogService.save(atvTrainWorkingLog);

            AtvLineSite atvLineSite = (AtvLineSite) redisCache.hget("lineSite", atvLine.getId() + nowID);
            //??????
            if (atvLineSite == null
                    || (PAstartflag == 1 && !playfilename.equals(atvLineSite.getInMusicSn()))
                    || (PAstartflag == 2 && !playfilename.equals(atvLineSite.getOutMusicSn()))
                    || (PAstartflag == 1 && !opendoorDir.equals(atvLineSite.getOpenDoorDirection()))) {
                /*判断是否产生新的故障单*/
                String address = carriageSn + "车厢，" + equipmentSn + _equipmentType(atvEquipment.getEquipmentType());
                String phenomenon = "";
                phenomenon += "广播故障"
                        + (PAstartflag == 1 ? "（到站广播语音文件：" + playfilename + "）" : "（离站广播语音文件：" + playfilename + "）")
                        + (opendoorDir == 0 ? "（不开门）" : (opendoorDir == 1 ? "（左侧开门）" : (opendoorDir == 2 ? "（右侧开门）" : "（左右同时开门）")));
                boolean isAdd = _findByNowBoardCardFault(atvTrain.getId(), 2, address, phenomenon).size() == 0;
                if (isAdd) {
                    /*上报故障*/
                    AtvBoardCardFault atvBoardCardFault = new AtvBoardCardFault();
                    //String faultSn = FillRuleUtil.executeRule("fault_sn_rule", new JSONObject()).toString();
                    String faultSn = ruleService.executeRule("fault_sn_rule", null).toString();
                    atvBoardCardFault.setSn(faultSn);
                    atvBoardCardFault.setCountryId(atvCountry.getId());
                    atvBoardCardFault.setAreaId(atvArea.getId());
                    atvBoardCardFault.setLineId(atvLine.getId());
                    atvBoardCardFault.setTrainId(atvTrain.getId());

                    //新报单1;处理中2;已上报3;已派单4;已完成5
                    atvBoardCardFault.setFaultStatus(1);
                    //原来是false；是否主管派单：0否？
                    atvBoardCardFault.setIsSend(0);
                    atvBoardCardFault.setIsRead(0);
                    atvBoardCardFault.setFaultSource(2);
                    atvBoardCardFault.setAddress(address);
                    atvBoardCardFault.setPhenomenon(phenomenon);
                    atvBoardCardFault.setIsFinish(0);
                    atvBoardCardFaults.add(atvBoardCardFault);
                    //atvBoardCardFaultService.save(atvBoardCardFault);
                    String text = atvCountry.getName() + "-" + atvArea.getName() + "-" + atvLine.getName() + "-" + atvTrain.getSn() + "车";
                    _pushFaultMsg(text, atvLine);

                    /*预警日志*/
                    AtvWarnLog atvWarnLog = new AtvWarnLog();
                    atvWarnLog.setLineId(atvLine.getId());
                    atvWarnLog.setTrainId(atvTrain.getId());
                    atvWarnLog.setCarriageId(atvCarriage.getId());
                    atvWarnLog.setEquipmentId(atvEquipment.getId());
                    atvWarnLog.setEquipmentType(atvEquipment.getEquipmentType());
                    atvWarnLog.setWarnType(1);
                    atvWarnLog.setTrainWorkingLogId(atvTrainWorkingLog.getId());
                    atvWarnLogs.add(atvWarnLog);
                    //atvWarnLogService.save(atvWarnLog);
                    /*添加预警弹窗*/
                    PopupResult popupResult = new PopupResult();
                    popupResult.setTrainSn(atvTrain.getSn());
                    popupResult.setWarnType(atvWarnLog.getWarnType());
                    popupResult.setTrainWorkingLogId(atvTrainWorkingLog.getId());
                    popupResultList.add(popupResult);
                } else {
                    /*更新实时预警时间*/
                    List<AtvWarnLog> atvWarnLogList = _findByNowWarnLog(atvLine.getId(), atvTrain.getId(), atvCarriage.getId(), atvEquipment.getId(), null, 1, null, null);
                    atvWarnLogs.addAll(atvWarnLogList);

                    for (AtvWarnLog atvWarnLog : atvWarnLogList) {
                        atvWarnLog.setCreateTime(TimeKit.getNowLocalDateTime());
                        atvWarnLog.setTrainWorkingLogId(atvTrainWorkingLog.getId());
                        //atvWarnLogService.updateById(atvWarnLog);
                        /*添加预警弹窗*/
                        PopupResult popupResult = new PopupResult();
                        popupResult.setTrainSn(atvTrain.getSn());
                        popupResult.setWarnType(atvWarnLog.getWarnType());
                        popupResult.setTrainWorkingLogId(atvWarnLog.getTrainWorkingLogId());
                        popupResultList.add(popupResult);
                        break;
                    }
                }
            }
        }

        JSONArray alarmstate = JSONArray.parseArray(data.getString("alarmstate"));
        for (Object alarm : alarmstate) {
            JSONObject alar = JSONObject.parseObject(alarm.toString());
            String carriageSn = alar.getString("carNo");//车厢编号
            String equipmentSn = alar.getString("deviceNo");//设备编号
            Integer state = alar.getInteger("state");//设备编号

            AtvCarriage atvCarriage = (AtvCarriage) redisCache.hget("carriage", atvTrain.getId() + carriageSn);
            if (IsKit.isNotNull(atvCarriage)) {
                AtvEquipment atvEquipment = (AtvEquipment) redisCache.hget("equipment", atvCarriage.getId() + equipmentSn);
                if (IsKit.isNotNull(atvEquipment)) {
                    /*乘客报警日志*/
                    AtvTrainWorkingLog atvTrainWorkingLog = new AtvTrainWorkingLog();
                    //广播日志1;乘客报警2;板卡日志3;故障日志4;设备日志5
                    atvTrainWorkingLog.setTrainWorkingLogType(2);
                    atvTrainWorkingLog.setCountryId(atvCountry.getId());
                    atvTrainWorkingLog.setAreaId(atvArea.getId());
                    atvTrainWorkingLog.setLineId(atvLine.getId());
                    atvTrainWorkingLog.setTrainId(atvTrain.getId());
                    atvTrainWorkingLog.setCarriageId(atvCarriage.getId());
                    atvTrainWorkingLog.setEquipmentId(atvEquipment.getId());
                    atvTrainWorkingLog.setEquipmentType(atvEquipment.getEquipmentType());
                    atvTrainWorkingLog.setAlarmStatus(state);
                    atvTrainWorkingLog.setId(UUIDKit.fastSimpleUUID());
                    atvTrainWorkingLogs.add(atvTrainWorkingLog);
                    //atvTrainWorkingLogService.save(atvTrainWorkingLog);
                    List<AtvWarnLog> atvWarnLogList = _findByNowWarnLog(atvLine.getId(), atvTrain.getId(), atvCarriage.getId(), atvEquipment.getId(), null, 2, null, null);
                    atvWarnLogs.addAll(atvWarnLogList);

                    if (IsKit.isNullOrEmpty(atvWarnLogList)) {
                        /*预警日志*/
                        AtvWarnLog atvWarnLog = new AtvWarnLog();
                        atvWarnLog.setLineId(atvLine.getId());
                        atvWarnLog.setTrainId(atvTrain.getId());
                        atvWarnLog.setCarriageId(atvCarriage.getId());
                        atvWarnLog.setEquipmentId(atvEquipment.getId());
                        atvWarnLog.setEquipmentType(atvEquipment.getEquipmentType());
                        atvWarnLog.setWarnType(2);
                        atvWarnLog.setTrainWorkingLogId(atvTrainWorkingLog.getId());
                        atvWarnLogs.add(atvWarnLog);
                        //atvWarnLogService.save(atvWarnLog);
                        /*添加预警弹窗*/
                        PopupResult popupResult = new PopupResult();
                        popupResult.setTrainSn(atvTrain.getSn());
                        popupResult.setWarnType(atvWarnLog.getWarnType());
                        popupResult.setTrainWorkingLogId(atvTrainWorkingLog.getId());
                        popupResultList.add(popupResult);
                    }

                    /*更新实时预警时间*/
                    for (AtvWarnLog atvWarnLog : atvWarnLogList) {
                        atvWarnLog.setCreateTime(TimeKit.getNowLocalDateTime());
                        atvWarnLog.setTrainWorkingLogId(atvTrainWorkingLog.getId());
                        //atvWarnLogService.updateById(atvWarnLog);
                        /*添加预警弹窗*/
                        PopupResult popupResult = new PopupResult();
                        popupResult.setTrainSn(atvTrain.getSn());
                        popupResult.setWarnType(atvWarnLog.getWarnType());
                        popupResult.setTrainWorkingLogId(atvWarnLog.getTrainWorkingLogId());
                        popupResultList.add(popupResult);
                        break;
                    }
                }
            }
        }
    }

    private void _handleCmd3Msg(JSONObject jsonObject, String userIdLine, String userIdTrain) {
        //BJTU 写入Influxdb 开始
        long time = System.currentTimeMillis();
        influxDbUtil.insertJSON(AtvConst.INFLUXDB_TABLE_PUTCARD, jsonObject, TimeUnit.SECONDS);
        LogKit.info("CMD3写入Influxdb耗时：" + (System.currentTimeMillis() - time));
        // BJTU 写入Influxdb 结束
        /*发送设备状态websocket开始*/
        JSONObject webEquipmentLogJson = new JSONObject();
        webEquipmentLogJson.put(WebsocketConst.MSG_CMD, "equipmentLog");
        webEquipmentLogJson.put(WebsocketConst.MSG_TXT, jsonObject);
        atvWebSocket.sendOneMessage("web", userIdLine, webEquipmentLogJson.toString());

        atvWebSocket.sendOneMessage("web", userIdTrain, webEquipmentLogJson.toString());


        /*发送设备状态websocket结束*/
        String msg = jsonObject.getString("data");
        if (IsKit.isNull(msg)) {
            LogKit.info("接收到的消息报文(EquipStatus)的数据为空!");
            return;
        }
        JSONArray dataArray = JSONArray.parseArray(msg);
        for (Object data : dataArray) {
            long time4 = System.currentTimeMillis();
            JSONObject dataObj = JSONObject.parseObject(data.toString());
            String carriageSn = dataObj.getString("carNo");
            String equipmentSn = dataObj.getString("deviceNo");
            Integer state = dataObj.getInteger("state");
            String version = dataObj.getString("version");
            Integer playstate = dataObj.getInteger("playstate");

            AtvCarriage atvCarriage = (AtvCarriage) redisCache.hget("carriage", atvTrain.getId() + carriageSn);
            if (IsKit.isNull(atvCarriage)) {
                LogKit.info("车厢缓存信息为空!");
                return;
            }

            AtvEquipment atvEquipment = (AtvEquipment) redisCache.hget("equipment", atvCarriage.getId() + equipmentSn);
            // BJTU 2022.11.9 无法从Redis获取设备则将其放入Redis中
            if (IsKit.isNull(atvEquipment)) {
                atvEquipment = new AtvEquipment();
                atvEquipment.setAreaId(atvArea.getId());
                atvEquipment.setCountryId(atvCountry.getId());
                atvEquipment.setTrainId(atvTrain.getId());
                atvEquipment.setLineId(atvLine.getId());
                atvEquipment.setCarriageId(atvCarriage.getId());
                atvEquipment.setSn(equipmentSn);
                atvEquipment.setOnlineStatus(state);
                atvEquipment.setEdition(version);
                atvEquipment.setEquipmentType(_stringEquipmentType(equipmentSn));
                atvEquipments.add(atvEquipment);
                redisCache.hset("equipment", atvCarriage.getId() + equipmentSn, atvEquipment);

                //atvEquipment = (AtvEquipment) redisCache.hget("equipment", atvCarriage.getId() + equipmentSn);
            }

            // BJTU 2022.11.9 根据Redis数据判断是否发生变化，只有变化了才会更新
            if (!state.equals(atvEquipment.getOnlineStatus()) || !version.equals(atvEquipment.getEdition())) {
                atvEquipment.setOnlineStatus(state);
                atvEquipment.setEdition(version);
                atvEquipments.add(atvEquipment);
                redisCache.hset("equipment", atvCarriage.getId() + equipmentSn, atvEquipment);

            }
            //atvEquipmentService.updateById(atvEquipment);
            AtvTrainWorkingLog atvTrainWorkingLog = new AtvTrainWorkingLog();
            atvTrainWorkingLog.setTrainWorkingLogType(5);
            atvTrainWorkingLog.setCountryId(atvCountry.getId());
            atvTrainWorkingLog.setAreaId(atvArea.getId());
            atvTrainWorkingLog.setLineId(atvLine.getId());
            atvTrainWorkingLog.setTrainId(atvTrain.getId());
            atvTrainWorkingLog.setCarriageId(atvCarriage.getId());
            atvTrainWorkingLog.setEquipmentId(atvEquipment.getId());
            atvTrainWorkingLog.setEquipmentType(atvEquipment.getEquipmentType());
            atvTrainWorkingLog.setOnlineStatus(state);
            atvTrainWorkingLog.setVersion(version);
            atvTrainWorkingLog.setPlayState(playstate);
            atvTrainWorkingLog.setId(UUIDKit.fastSimpleUUID());
            atvTrainWorkingLogs.add(atvTrainWorkingLog);

            //atvTrainWorkingLogService.save(atvTrainWorkingLog);
            //判断是否产生新的故障单
            String address = carriageSn + "车厢，" + equipmentSn;
            String phenomenon = "";
            boolean isAdd = _findByNowBoardCardFault(atvTrain.getId(), 2, address, "设备离线：" + equipmentSn).size() == 0;
            phenomenon += "设备离线：" + equipmentSn;
            //state: 0未知，1在线，2掉线(数字)
            if (1 == state.intValue()) {
                LogKit.info("在线状态不能产生故障单!");
                if(!isAdd){
                    _updateByNowBoardCardFault(atvTrain.getId(), 2, address, "设备离线：" + equipmentSn);
                }
                continue;
            }


            //xbm String type = _equipmentType(atvEquipment.getEquipmentType());

            if (isAdd) {
                /*上报故障*/
                AtvBoardCardFault atvBoardCardFault = new AtvBoardCardFault();
                //String faultSn = FillRuleUtil.executeRule("fault_sn_rule", new JSONObject()).toString();
                String faultSn = ruleService.executeRule("fault_sn_rule", null).toString();
                atvBoardCardFault.setSn(faultSn);
                atvBoardCardFault.setCountryId(atvCountry.getId());
                atvBoardCardFault.setAreaId(atvArea.getId());
                atvBoardCardFault.setLineId(atvLine.getId());
                atvBoardCardFault.setTrainId(atvTrain.getId());
                //新报单1;处理中2;已上报3;已派单4;已完成5
                atvBoardCardFault.setFaultStatus(1);
                //原来是false；是否主管派单：0否？
                atvBoardCardFault.setIsSend(0);
                atvBoardCardFault.setIsRead(0);
                //人工上报1;平台智能检测2;设备自检3
                atvBoardCardFault.setFaultSource(2);
                atvBoardCardFault.setAddress(address);
                atvBoardCardFault.setPhenomenon(phenomenon);
                atvBoardCardFault.setIsFinish(0);
                atvBoardCardFaults.add(atvBoardCardFault);
                //atvBoardCardFaultService.save(atvBoardCardFault);
                String text = atvCountry.getName() + "-" + atvArea.getName() + "-" + atvLine.getName() + "-" + atvTrain.getSn() + "车";
                _pushFaultMsg(text, atvLine);

                /*预警日志*/
                AtvWarnLog atvWarnLog = new AtvWarnLog();
                atvWarnLog.setLineId(atvLine.getId());
                atvWarnLog.setTrainId(atvTrain.getId());
                atvWarnLog.setCarriageId(atvCarriage.getId());
                atvWarnLog.setEquipmentId(atvEquipment.getId());
                atvWarnLog.setEquipmentType(atvEquipment.getEquipmentType());
                //广播异常1;乘客报警2;板卡日志3;设备异常4;设备离线5
                atvWarnLog.setWarnType(5);
                atvWarnLog.setTrainWorkingLogId(atvTrainWorkingLog.getId());
                atvWarnLogs.add(atvWarnLog);

                // atvWarnLogService.save(atvWarnLog);
                /*添加预警弹窗*/
                PopupResult popupResult = new PopupResult();
                popupResult.setTrainSn(atvTrain.getSn());
                popupResult.setWarnType(atvWarnLog.getWarnType());
                popupResult.setTrainWorkingLogId(atvTrainWorkingLog.getId());
                popupResultList.add(popupResult);
            } else {
                /*更新实时预警时间*/
                List<AtvWarnLog> atvWarnLogList = _findByNowWarnLog(atvLine.getId(), atvTrain.getId(), atvCarriage.getId(), atvEquipment.getId(), null, 5, null, null);
                atvWarnLogs.addAll(atvWarnLogList);
                for (AtvWarnLog atvWarnLog : atvWarnLogList) {
                    atvWarnLog.setCreateTime(TimeKit.getNowLocalDateTime());
                    atvWarnLog.setTrainWorkingLogId(atvTrainWorkingLog.getId());
                    //atvWarnLogService.updateById(atvWarnLog);
                    /*添加预警弹窗*/
                    PopupResult popupResult = new PopupResult();
                    popupResult.setTrainSn(atvTrain.getSn());
                    popupResult.setWarnType(atvWarnLog.getWarnType());
                    popupResult.setTrainWorkingLogId(atvWarnLog.getTrainWorkingLogId());
                    popupResultList.add(popupResult);
                    break;
                }
            }
        }
    }

    private void _updateByNowBoardCardFault(String trainId, int faultSource, String address, String phenomenon) {

        QueryWrapper<AtvBoardCardFault> wrapper = Wrappers.wrapper(AtvBoardCardFault.class)
                .eq("trainId", trainId)
                .eq("address", address)
                .eq("phenomenon", phenomenon)
                .eq("faultSource", faultSource)
                .eq("isFinish", 0);
        AtvBoardCardFault atvBoardCardFault = daoService.findOne(wrapper);
        if(IsKit.isNotNull(atvBoardCardFault)){
            atvBoardCardFault.setFinishTime(TimeKit.getNowLocalDateTime());
            atvBoardCardFault.setIsFinish(1);
			 atvBoardCardFault.setFaultStatus(5);
            daoService.update(atvBoardCardFault);
        }

    }

    private void _handleCmd4Msg(JSONObject jsonObject) {
        String msg = jsonObject.getString("data");
        if (IsKit.isNull(msg)) {
            LogKit.info("接收到的消息报文(EquipFault)的数据为空!");
            return;
        }
        JSONArray faults = JSONArray.parseArray(msg);
        for (Object fault : faults) {
            JSONObject faultInfo = JSONObject.parseObject(fault.toString());
            String carriageSn = faultInfo.getString("carNo");//车厢号
            String equipmentSn = faultInfo.getString("deviceNo");//设备编号
            Integer FaultType = faultInfo.getInteger("FaultType");//故障类型
            String FaultNo = faultInfo.getString("FaultNo");//故障编码
            String FaultDescription = faultInfo.getString("FaultDescription");//故障描述

            AtvCarriage atvCarriage = (AtvCarriage) redisCache.hget("carriage", atvTrain.getId() + carriageSn);
            if (IsKit.isNull(atvCarriage)) {
                LogKit.info("未找到车厢：" + jsonObject);
                return;
            }
            AtvEquipment atvEquipment = (AtvEquipment) redisCache.hget("equipment", atvCarriage.getId() + equipmentSn);
            if (IsKit.isNull(atvEquipment)) {
                LogKit.info("未找到设备：" + jsonObject);
                return;
            }

            AtvTrainWorkingLog atvTrainWorkingLog = new AtvTrainWorkingLog();
            //故障日志4;(1广播日志;2乘客报警;3板卡日志;5设备日志);
            atvTrainWorkingLog.setTrainWorkingLogType(4);
            atvTrainWorkingLog.setCountryId(atvCountry.getId());
            atvTrainWorkingLog.setAreaId(atvArea.getId());
            atvTrainWorkingLog.setLineId(atvLine.getId());
            atvTrainWorkingLog.setTrainId(atvTrain.getId());
            atvTrainWorkingLog.setCarriageId(atvCarriage.getId());
            atvTrainWorkingLog.setEquipmentId(atvEquipment.getId());
            atvTrainWorkingLog.setEquipmentType(atvEquipment.getEquipmentType());
            atvTrainWorkingLog.setFaultType(FaultType);
            atvTrainWorkingLog.setFaultNo(FaultNo);
            atvTrainWorkingLog.setFaultDescription(FaultDescription);
            atvTrainWorkingLog.setId(UUIDKit.fastSimpleUUID());
            atvTrainWorkingLogs.add(atvTrainWorkingLog);
            //atvTrainWorkingLogService.save(atvTrainWorkingLog);

            /*判断是否产生新的故障单*/
            String address = carriageSn + "车厢，" + equipmentSn + _equipmentType(atvEquipment.getEquipmentType());
            String phenomenon = "";
            boolean isAdd = _findByNowBoardCardFault(atvTrain.getId(), 3, address, "设备自检故障编码：" + FaultNo).size() == 0;
            phenomenon += "设备自检故障编码：" + FaultNo + "，故障描述：" + FaultDescription;
            if (isAdd) {
                /*上报故障*/
                AtvBoardCardFault atvBoardCardFault = new AtvBoardCardFault();
                String faultSn = ruleService.executeRule("fault_sn_rule", null).toString();
                atvBoardCardFault.setSn(faultSn);
                atvBoardCardFault.setCountryId(atvCountry.getId());
                atvBoardCardFault.setAreaId(atvArea.getId());
                atvBoardCardFault.setLineId(atvLine.getId());
                atvBoardCardFault.setTrainId(atvTrain.getId());
                //新报单1;处理中2;已上报3;已派单4;已完成5
                atvBoardCardFault.setFaultStatus(1);
                //原来是false；是否主管派单：0否？
                atvBoardCardFault.setIsSend(0);
                atvBoardCardFault.setIsRead(0);
                //1人工上报; 2平台智能检测；设备自检3
                atvBoardCardFault.setFaultSource(3);
                atvBoardCardFault.setAddress(address);
                atvBoardCardFault.setPhenomenon(phenomenon);
                atvBoardCardFaults.add(atvBoardCardFault);

                //atvBoardCardFaultService.save(atvBoardCardFault);
                String text = atvCountry.getName() + "-" + atvArea.getName() + "-" + atvLine.getName() + "-" + atvTrain.getSn() + "车";
                _pushFaultMsg(text, atvLine);

                /*预警日志*/
                AtvWarnLog atvWarnLog = new AtvWarnLog();
                atvWarnLog.setLineId(atvLine.getId());
                atvWarnLog.setTrainId(atvTrain.getId());
                atvWarnLog.setCarriageId(atvCarriage.getId());
                atvWarnLog.setEquipmentId(atvEquipment.getId());
                atvWarnLog.setEquipmentType(atvEquipment.getEquipmentType());
                //广播异常1;乘客报警2;板卡日志3;设备异常4;设备离线5
                atvWarnLog.setWarnType(4);
                atvWarnLog.setTrainWorkingLogId(atvTrainWorkingLog.getId());
                atvWarnLog.setFaultType(FaultType);
                atvWarnLog.setFaultNo(FaultNo);
                atvWarnLogs.add(atvWarnLog);
                //atvWarnLogService.save(atvWarnLog);
                /*添加预警弹窗*/
                PopupResult popupResult = new PopupResult();
                popupResult.setTrainSn(atvTrain.getSn());
                popupResult.setWarnType(atvWarnLog.getWarnType());
                popupResult.setTrainWorkingLogId(atvTrainWorkingLog.getId());
                popupResultList.add(popupResult);
            } else {
                /*更新实时预警时间faultType和faultNo为空 warn_type=3板卡异常*/
                List<AtvWarnLog> atvWarnLogList = _findByNowWarnLog(atvLine.getId(), atvTrain.getId(), atvCarriage.getId(), atvEquipment.getId(), null, 4, FaultType, FaultNo);
                atvWarnLogs.addAll(atvWarnLogList);
                for (AtvWarnLog atvWarnLog : atvWarnLogList) {
                    atvWarnLog.setCreateTime(TimeKit.getNowLocalDateTime());
                    atvWarnLog.setTrainWorkingLogId(atvTrainWorkingLog.getId());
                    //atvWarnLogService.updateById(atvWarnLog);
                    /*添加预警弹窗*/
                    PopupResult popupResult = new PopupResult();
                    popupResult.setTrainSn(atvTrain.getSn());
                    popupResult.setWarnType(atvWarnLog.getWarnType());
                    popupResult.setTrainWorkingLogId(atvWarnLog.getTrainWorkingLogId());
                    popupResultList.add(popupResult);
                    break;
                }
            }
        }
        // /**发送到websocket*/
        // JSONObject webJson = new JSONObject();
        //webJson.put(WebsocketConst.MSG_CMD, "atvWarnLog");
        // webJson.put(WebsocketConst.MSG_TXT, jsonObject);
        //atvWebSocket.sendOneMessage("web", userIdLine, webJson.toString());
    }

    private void _handleCmd6Msg(JSONObject jsonObject, String userIdTrain) {
        LogKit.info("handleRabbitMsg-1【cmd_code6】");
        String msg = jsonObject.getString("data");
        LogKit.info("handleRabbitMsg-msg【cmd_code6】:"+msg);
        if (IsKit.isNull(msg)) {
            LogKit.info("接收到的消息报文(TTS)的数据为空!");
            return;
        }

        JSONObject data = JSONObject.parseObject(msg);
        String messageId = data.getString("messageId");//消息ID
        LambdaQueryWrapper<AtvTts> wrapper = Wrappers.lambdaWrapper(AtvTts.class)
                .eq(AtvTts::getId, messageId);//??
        AtvTts entity = daoService.findOne(wrapper);
        LogKit.info("handleRabbitMsg-entity【cmd_code6】:"+entity);
        if (IsKit.isNotNull(entity)) {
            String audioSn = data.getString("audioSn");//音频编号
            String audioLink = data.getString("audioLink");//音频连接
            entity.setTurnStatus(1);//成功
            entity.setAudioSn(audioSn);
            entity.setAudioLink(audioLink);
            LogKit.info("handleRabbitMsg-update【cmd_code6】:"+entity);
            daoService.update(entity);
            AtvTtsCtrl.turnTts.remove(userIdTrain + messageId);
        }
    }

    private void _handleCmd15Msg(JSONObject jsonObject) {
        String msg = jsonObject.getString("data");
        if (IsKit.isNull(msg)) {
            LogKit.info("接收到的消息报文(EquipLog)的数据为空!");
            return;
        }

        JSONObject data = JSONObject.parseObject(msg);
        String carriageSn = data.getString("carNo");//车厢号
        String equipmentSn = data.getString("deviceNo");//设备编号
        //1上传日志，2上传背景音频，3上传报警音频
        Integer method = data.getInteger("method");
        String fileUrl = data.getString("fileUrl");//文件URL
        String StartDate = data.getString("StartDate");//日志开始时间yyyy-MM-dd HH:mm
        String EndDate = data.getString("EndDate");//日志截止时间yyyy-MM-dd HH:mm

        AtvCarriage atvCarriage = (AtvCarriage) redisCache.hget("carriage", atvTrain.getId() + carriageSn);
        if (IsKit.isNull(atvCarriage)) {
            LogKit.info("未找到车厢：" + jsonObject);
            return;
        }
        AtvEquipment atvEquipment = (AtvEquipment) redisCache.hget("equipment", atvCarriage.getId() + equipmentSn);
        if (IsKit.isNull(atvEquipment)) {
            LogKit.info("未找到设备：" + jsonObject);
            return;
        }
        //检查文件是否有重复
        LambdaQueryWrapper<AtvEquipmentLog> wrapper = Wrappers.lambdaWrapper(AtvEquipmentLog.class)
                .eq(AtvEquipmentLog::getEquipmentId, atvEquipment.getId())
                .eq(AtvEquipmentLog::getEquipmentLogType, method)
                .eq(AtvEquipmentLog::getStartTime, StartDate + ":00")
                .eq(AtvEquipmentLog::getEndTime, EndDate + ":00");
        List<AtvEquipmentLog> atvEquipmentLogOld = daoService.findList(wrapper);
        if (IsKit.isNullOrEmpty(atvEquipmentLogOld)) {
            AtvEquipmentLog atvEquipmentLog = new AtvEquipmentLog();
            atvEquipmentLog.setCountryId(atvCountry.getId());
            atvEquipmentLog.setAreaId(atvArea.getId());
            atvEquipmentLog.setLineId(atvLine.getId());
            atvEquipmentLog.setTrainId(atvTrain.getId());
            atvEquipmentLog.setCarriageId(atvCarriage.getId());
            atvEquipmentLog.setEquipmentId(atvEquipment.getId());
            atvEquipmentLog.setEquipmentType(atvEquipment.getEquipmentType());
            atvEquipmentLog.setEquipmentLogType(method);
            atvEquipmentLog.setStartTime(TimeKit.dateToLocalDateTime(StartDate));
            atvEquipmentLog.setEndTime(TimeKit.dateToLocalDateTime(EndDate));
            atvEquipmentLog.setLink(fileUrl);
            daoService.save(atvEquipmentLog);
        }
    }

}