package cn.component.message.mq;

import cn.component.message.mq.base.HandleRabbitBase;
import cn.facade.constant.AtvConst;
import cn.facade.constant.WebsocketConst;
import cn.pojo.atv.*;
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 com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * ATV消息得处理者
 * 需要创建队列atv.websocket.handle
 **/
@Component
@RabbitListener(queues = "atv.websocket.handel.cmd1", ackMode = "AUTO")
public class HandleRabbitMsgCmd1 extends HandleRabbitBase {
    protected void _distribute(Integer rawCode, JSONObject jsonObject, String userIdLine, String userIdTrain) {
        _handleCmd1Msg(jsonObject, userIdTrain);
    }

    private void _handleCmd1Msg(JSONObject jsonObject, String userIdTrain) {
        //BJTU 写入Influxdb 开始
        long time = System.currentTimeMillis();
        influxDbUtil.insertJSON(AtvConst.INFLUXDB_TABLE_BOARDCARD, jsonObject, TimeUnit.SECONDS);
        LogKit.info("CMD1写入Influxdb耗时:" + (System.currentTimeMillis() - time));
        // BJTU 写入Influxdb 结束
        /*发送板卡状态websocket开始*/
        JSONObject webBoardCardLogJson = new JSONObject();
        webBoardCardLogJson.put(WebsocketConst.MSG_CMD, "boardCardLog");
        webBoardCardLogJson.put(WebsocketConst.MSG_TXT, jsonObject);
        atvWebSocket.sendOneMessage("web", userIdTrain, webBoardCardLogJson.toString());

        /*发送板卡状态websocket结束*/
        String msg = jsonObject.getString("data");
        if (IsKit.isNull(msg)) {
            LogKit.info("接收到的消息报文(BoardCard)的数据为空!");
            return;
        }

        JSONObject data = JSONObject.parseObject(msg);
        String carriageSn = data.getString("carNo");
        String equipmentSn = data.getString("deviceNo");
        JSONArray boardCards = JSONArray.parseArray(data.getString("boardCards"));

        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;
        }
        for (Object boardCard : boardCards) {
            JSONObject boardCardInfo = JSONObject.parseObject(boardCard.toString());
            String sn = boardCardInfo.getString("cardslotID");
            if (IsKit.isNull(sn)) {
                continue;
            }
            AtvBoardCard atvBoardCard = (AtvBoardCard) redisCache.hget("boardCard", sn);
            if (IsKit.isNotNull(atvBoardCard)) {
                Integer RS485 = boardCardInfo.getInteger("RS485");//0,//0-100表示通信正确率
                //???Integer cardtype = boardCardInfo.getInteger("cardtype");//1电源版,2音频板,3控制板,4重连板,5功放板,6报警器,7广播控制盒,8MVB板卡
                Integer boardCardsNO = boardCardInfo.getInteger("boardCardsNO");//板卡序号
                Integer worktime = boardCardInfo.getInteger("worktime");//以秒为单位累加
                Double voltage12 = boardCardInfo.getDouble("voltage12");//0,电源电压12.0V单位为V
                Double voltage5 = boardCardInfo.getDouble("voltage5");//0,电源电压5.0V单位为V
                Double voltage3v3 = boardCardInfo.getDouble("voltage3v3");//0,//电源电压3.3V单位为V
                Double current12 = boardCardInfo.getDouble("current12");//0,//12V电流单位为A
                Double current5 = boardCardInfo.getDouble("current5");//0,5V电流单位为A
                Double current3v3 = boardCardInfo.getDouble("current3v3");//0,//3.3V电流 单位为A
                Double temperature = boardCardInfo.getDouble("temperature");//0,//1=0.1摄氏度
                Integer CAN1 = boardCardInfo.getInteger("CAN1");//0,//0-100表示通信正确率0%-100%
                Integer CAN2 = boardCardInfo.getInteger("CAN2");//0,//0-100表示通信正确率0%-100%
                Integer RS232No1 = boardCardInfo.getInteger("RS232No1");//0,//0-100表示通信正确率0%-100%
                Integer RS232No2 = boardCardInfo.getInteger("RS232No2");//0,//0-100表示通信正确率0%-100%
                Integer net1 = boardCardInfo.getInteger("net1");//0,//0-100表示通信正确率0%-100%
                Integer net2 = boardCardInfo.getInteger("net2");//0,//0-100表示通信正确率0%-100%
                Integer audiochannel1 = boardCardInfo.getInteger("audiochannel1");//0,//DB值
                Integer audiochannel2 = boardCardInfo.getInteger("audiochannel2");
                Integer audiochannel3 = boardCardInfo.getInteger("audiochannel3");
                Integer audiochannel4 = boardCardInfo.getInteger("audiochannel4");
                Integer audiochannel5 = boardCardInfo.getInteger("audiochannel5");
                Integer audiochannel6 = boardCardInfo.getInteger("audiochannel6");
                Integer audiochannel7 = boardCardInfo.getInteger("audiochannel7");
                Integer audiochannel8 = boardCardInfo.getInteger("audiochannel8");
                String softVer = boardCardInfo.getString("softVer");//板卡固件版本
                atvBoardCard.setCountryId(atvCountry.getId());
                atvBoardCard.setAreaId(atvArea.getId());
                atvBoardCard.setLineId(atvLine.getId());
                atvBoardCard.setTrainId(atvTrain.getId());
                atvBoardCard.setCarriageId(atvCarriage.getId());
                atvBoardCard.setEquipmentId(atvEquipment.getId());
                atvBoardCard.setWorkingHours(worktime);
                atvBoardCard.setEdition(softVer);
                atvBoardCards.add(atvBoardCard);
                //atvBoardCardService.updateById(atvBoardCard);
                redisCache.hset("boardCard", sn, atvBoardCard);

                AtvThreshold atvThreshold = (AtvThreshold) redisCache.hget("threshold", atvBoardCard.getBoardCardType().toString());
                if (IsKit.isNotNull(atvThreshold)) {
                    //??????
                    if ((atvThreshold.getVoltageMin12() != null && atvThreshold.getVoltageMax12() != null && voltage12 != null && (voltage12 <= atvThreshold.getVoltageMin12() || voltage12 >= atvThreshold.getVoltageMax12()))
                            || (atvThreshold.getVoltageMin5() != null && atvThreshold.getVoltageMax5() != null && voltage5 != null && (voltage5 <= atvThreshold.getVoltageMin5() || voltage5 >= atvThreshold.getVoltageMax5()))
                            || (atvThreshold.getVoltageMin3v3() != null && atvThreshold.getVoltageMax3v3() != null && voltage3v3 != null && (voltage3v3 <= atvThreshold.getVoltageMin3v3() || voltage3v3 >= atvThreshold.getVoltageMax3v3()))
                            || (atvThreshold.getCurrentMin12() != null && atvThreshold.getCurrentMax12() != null && current12 != null && ((current12 <= atvThreshold.getCurrentMin12() && atvThreshold.getCurrentMaxWait() != null && current12 > atvThreshold.getCurrentMaxWait()) || current12 >= atvThreshold.getCurrentMax12()))
                            || (atvThreshold.getCurrentMin5() != null && atvThreshold.getCurrentMax5() != null && current5 != null && (current5 <= atvThreshold.getCurrentMin5() || current5 >= atvThreshold.getCurrentMax5()))
                            || (atvThreshold.getCurrentMin3v3() != null && atvThreshold.getCurrentMax3v3() != null && current3v3 != null && (current3v3 <= atvThreshold.getCurrentMin3v3() || current3v3 >= atvThreshold.getCurrentMax3v3()))
                            || (atvThreshold.getTemperatureMax() != null && temperature != null && temperature > atvThreshold.getTemperatureMax())) {
                        /*板卡日志*/
                        AtvTrainWorkingLog atvTrainWorkingLog = new AtvTrainWorkingLog();
                        atvTrainWorkingLog.setTrainWorkingLogType(3);
                        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.setBoardCardId(atvBoardCard.getId());
                        atvTrainWorkingLog.setBoardCardType(atvBoardCard.getBoardCardType());
                        atvTrainWorkingLog.setBoardCardNo(boardCardsNO);
                        atvTrainWorkingLog.setRs485(RS485);
                        atvTrainWorkingLog.setWorktime(worktime);
                        atvTrainWorkingLog.setVoltage12(voltage12);
                        atvTrainWorkingLog.setVoltage5(voltage5);
                        atvTrainWorkingLog.setVoltage3v3(voltage3v3);
                        atvTrainWorkingLog.setCurrent12(current12);
                        atvTrainWorkingLog.setCurrent5(current5);
                        atvTrainWorkingLog.setCurrent3v3(current3v3);
                        atvTrainWorkingLog.setTemperature(temperature);
                        atvTrainWorkingLog.setCan1(CAN1);
                        atvTrainWorkingLog.setCan2(CAN2);
                        atvTrainWorkingLog.setRs232no1(RS232No1);
                        atvTrainWorkingLog.setRs232no2(RS232No2);
                        atvTrainWorkingLog.setNet1(net1);
                        atvTrainWorkingLog.setNet2(net2);
                        atvTrainWorkingLog.setAudiochannel1(audiochannel1);
                        atvTrainWorkingLog.setAudiochannel2(audiochannel2);
                        atvTrainWorkingLog.setAudiochannel3(audiochannel3);
                        atvTrainWorkingLog.setAudiochannel4(audiochannel4);
                        atvTrainWorkingLog.setAudiochannel5(audiochannel5);
                        atvTrainWorkingLog.setAudiochannel6(audiochannel6);
                        atvTrainWorkingLog.setAudiochannel7(audiochannel7);
                        atvTrainWorkingLog.setAudiochannel8(audiochannel8);
                        atvTrainWorkingLog.setVersion(softVer);//板卡固件版本
                        atvTrainWorkingLog.setId(UUIDKit.fastSimpleUUID());
                        atvTrainWorkingLogs.add(atvTrainWorkingLog);
                        //atvTrainWorkingLogService.save(atvTrainWorkingLog);
                        /*判断是否产生新的故障单*/
                        boolean isAdd;
                        String address = carriageSn + "车厢，" + equipmentSn + _equipmentType(atvEquipment.getEquipmentType()) + "，" + _boardCardType(atvBoardCard.getBoardCardType());
                        String phenomenon = "";
                        if (atvThreshold.getTemperatureMax() != null && temperature != null && temperature > atvThreshold.getTemperatureMax()) {
                            isAdd = _findByNowBoardCardFault(atvTrain.getId(), 2, address, "温度异常").size() == 0;
                            phenomenon += "温度异常（温度：" + temperature + "）";
                        } else {
                            isAdd = _findByNowBoardCardFault(atvTrain.getId(), 2, address, "电压电流故障").size() == 0;
                            phenomenon += "电压电流故障"
                                    + (voltage12 != null ? "（12V电压：" + voltage12 + "）" : "")
                                    + (voltage5 != null ? "（5V电压：" + voltage5 + "）" : "")
                                    + (voltage3v3 != null ? "（3.3V电压：" + voltage3v3 + "）" : "")
                                    + (current12 != null ? "（12V电流：" + current12 + "）" : "")
                                    + (current5 != null ? "（5V电流：" + current5 + "）" : "")
                                    + (current3v3 != null ? "（3.3V电流：" + current3v3 + "）" : "");
                        }
                        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);
                            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.setBoardCardId(atvBoardCard.getId());
                            atvWarnLog.setBoardCardType(atvBoardCard.getBoardCardType());
                            //广播异常1;乘客报警2;板卡日志3;设备异常4;设备离线5
                            atvWarnLog.setWarnType(3);
                            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(), atvBoardCard.getId(), 3, 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;
                            }
                        }
                    }
                }
            }
        }
    }

}
