package com.ozs.controller.upload;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ozs.common.core.domain.entity.SysDictData;
import com.ozs.common.core.redis.RedisCache;
import com.ozs.common.utils.ApiTokenUtils;
import com.ozs.common.utils.AppendUtils;
import com.ozs.common.utils.ChineseToPingyin;
import com.ozs.common.utils.HeartbeatUtils;
import com.ozs.common.utils.HttpClientUtil;
import com.ozs.common.utils.IgnoreUtils;
import com.ozs.common.utils.StringUtils;
import com.ozs.common.utils.http.HttpUtils;
import com.ozs.common.utils.stateSecrets.SM4Utils;
import com.ozs.config.AjaxResults;
import com.ozs.config.Constant;
import com.ozs.entity.BaseCameraManagement;
import com.ozs.entity.BaseRailwayManagement;
import com.ozs.entity.BaseRouteMassage;
import com.ozs.entity.BaseTerminal;
import com.ozs.entity.BaseTerminalLog;
import com.ozs.entity.BaseUser;
import com.ozs.entity.BaseVehicleTerminal;
import com.ozs.entity.MsgAlarm;
import com.ozs.entity.MsgAlarmExt;
import com.ozs.entity.MsgAlarmFrequency;
import com.ozs.entity.MsgHeartbeatAlarmMessage;
import com.ozs.entity.PreAlarm;
import com.ozs.entity.SkynetHeartbeatLog;
import com.ozs.entity.SvcAddress;
import com.ozs.entity.TerminalIgnoreAlarm;
import com.ozs.entity.VehiclePosition;
import com.ozs.entity.BaseVideoTrains;
import com.ozs.entity.response.BaseCameraManagementReq;
import com.ozs.entity.response.PreAlarmListResponse;
import com.ozs.entity.response.PreAlarmResponse;
import com.ozs.entity.response.VehicleVedioResponse;
import com.ozs.entity.vo.AlarmFilesVo;
import com.ozs.entity.vo.AlarmHeartbeatLog;
import com.ozs.entity.vo.AlarmInfoVo;
import com.ozs.entity.vo.AlarmListVo;
import com.ozs.entity.vo.CameraPlayVo;
import com.ozs.entity.vo.CameraVo;
import com.ozs.entity.vo.CameraVos;
import com.ozs.entity.vo.CamerasVo;
import com.ozs.entity.vo.Files;
import com.ozs.entity.vo.HeartbeatVo;
import com.ozs.entity.vo.ParameterVo;
import com.ozs.entity.vo.QueryAlarmVo;
import com.ozs.entity.vo.ReleaseAlarmVo;
import com.ozs.entity.vo.ReqMsgAlarmVo;
import com.ozs.entity.vo.RespAlarmList;
import com.ozs.entity.vo.RespCameraVo;
import com.ozs.entity.vo.RespGeoHazardMonitorVo;
import com.ozs.entity.vo.RespHeartbeatVo;
import com.ozs.entity.vo.SkynetHeartbeatVo;
import com.ozs.entity.vo.TerminalIgnoreVo;
import com.ozs.mapper.AlarmHeartbeatLogMapper;
import com.ozs.mapper.MsgHeartbeatAlarmMessageMapper;
import com.ozs.mapper.SkynetHeartbeatLogMapper;
import com.ozs.service.BaseCameraManagementService;
import com.ozs.service.BaseRailwayManagementService;
import com.ozs.service.BaseRouteMassageService;
import com.ozs.service.BaseTerminalLogService;
import com.ozs.service.BaseTerminalService;
import com.ozs.service.BaseUserService;
import com.ozs.service.BaseVehicleTerminalService;
import com.ozs.service.BaseVideoTrainsService;
import com.ozs.service.MsgAlarmExtService;
import com.ozs.service.MsgAlarmFrequencyService;
import com.ozs.service.MsgAlarmService;
import com.ozs.service.PreAlarmService;
import com.ozs.service.SvcAddressService;
import com.ozs.service.TerminalIgnoreAlarmService;
import com.ozs.service.VehiclePositionService;
import com.ozs.system.service.ISysDictTypeService;
import com.ozs.utils.CameraUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * 1. 获取身份认证控制层
 *
 * @author Administrator
 */
@RestController
@Slf4j
@CrossOrigin(origins = "*")
public class GeoHazardMonitorTokenController {
    public static final String PATTERN = "^([0-9]+),([0-9]+),([0-9]+),([0-9]+),([0-9]+),([0-9]+)$";
    public static final String PATTERNS = "^[0-9]*$";
    public static final String REGEX = "^\\d{13}$";

    public static final String KEY = "58792429c08c43e9";
    @Resource
    private ApiTokenUtils apiTokenUtils;
    @Autowired
    MsgAlarmService msgAlarmService;
    @Autowired
    MsgAlarmFrequencyService msgAlarmFrequencyService;
    @Autowired
    SvcAddressService svcAddressService;
    @Autowired
    BaseCameraManagementService baseCameraManagementService;
    @Autowired
    private BaseUserService baseUserService;
    @Autowired
    private MsgAlarmExtService msgAlarmExtService;
    @Autowired
    private BaseVehicleTerminalService baseVehicleTerminalService;
    @Autowired
    private VehiclePositionService vehiclePositionService;
    @Autowired
    private HeartbeatUtils heartbeatUtils;
    @Autowired
    private TerminalIgnoreAlarmService terminalIgnoreAlarmService;
    @Autowired
    private IgnoreUtils ignoreUtils;
    @Autowired
    private BaseRailwayManagementService baseRailwayManagementService;
    @Autowired
    private BaseTerminalService baseTerminalService;
    @Autowired
    private CameraUtil cameraUtil;
    @Resource
    private SkynetHeartbeatLogMapper synetHeartbeatLogMapper;
    @Resource
    private AlarmHeartbeatLogMapper alarmHeartbeatLogMapper;
    @Resource
    private MsgHeartbeatAlarmMessageMapper msgHearbeatAlarmMessageMapper;
    @Resource
    private BaseRouteMassageService baseRouteMassageService;

    @Value("${base.env}")
    private String env;
    @Value("${sdk.publish}")
    private String sdkUrl;
    @Autowired
    private ISysDictTypeService dictTypeService;
    @Resource
    private BaseTerminalLogService baseTerminalLogService;
    @Resource
    private PreAlarmService preAlarmService;
    @Resource
    private RedisCache redisCache;
    @Resource
    private BaseVideoTrainsService baseVideoTrainsService;

    /**
     * 获取web访问令牌
     *
     * @return
     */
    @PostMapping("/api/token")
    public String getWebToken(@RequestBody SvcAddress svcAddress) {
        // 生成令牌
        AjaxResults AjaxResults1 = null;
        if (ObjectUtils.isEmpty(svcAddress)) {
            AjaxResults1 = new AjaxResults(0, "svcAddress参数不能为空");
            return JSONObject.toJSONString(AjaxResults1);
        }
        LambdaQueryWrapper<SvcAddress> lw = new LambdaQueryWrapper<SvcAddress>();
        if (!ObjectUtils.isEmpty(svcAddress.getClientId())) {
            lw.eq(SvcAddress::getClientId, svcAddress.getClientId());
            lw.eq(SvcAddress::getEnv, env);
        } else {
            AjaxResults1 = new AjaxResults(0, "客户端编号不能为空");
            return JSONObject.toJSONString(AjaxResults1);
        }
        SvcAddress serviceOne = svcAddressService.getOne(lw);
        if (!ObjectUtils.isEmpty(serviceOne)) {
            String clientSecret = SM4Utils.decryptData_ECB(serviceOne.getClientSecret(), KEY);
            String sm4 = SM4Utils.decryptData_ECB(svcAddress.getClientSecret(), clientSecret);
            if (clientSecret.equals(sm4)) {
                if (!ObjectUtils.isEmpty(svcAddress.getGrantType())) {
                    if (!svcAddress.getGrantType().toString().matches(PATTERNS)) {
                        AjaxResults1 = new AjaxResults(0, "授权类型填写错误");
                        return JSONObject.toJSONString(AjaxResults1);
                    }
                } else {
                    AjaxResults1 = new AjaxResults(0, "授权类型不能为空");
                    return JSONObject.toJSONString(AjaxResults1);
                }
                ArrayList<String> objects = apiTokenUtils.createGeoHazardMonitorToken(svcAddress.getGrantType().toString(), svcAddress.getClientId(), sm4);
                if (objects.size() > 0) {
                    RespGeoHazardMonitorVo respGeoHazardMonitorVo = new RespGeoHazardMonitorVo();
                    respGeoHazardMonitorVo.setAccessToken(objects.get(1));
                    Long l = Long.valueOf(objects.get(0));
                    respGeoHazardMonitorVo.setExpiresIn(l / 1000);
                    respGeoHazardMonitorVo.setTokenType("令牌类型");
                    AjaxResults1 = new AjaxResults(1, "ok", respGeoHazardMonitorVo);
                    return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), sm4);
                } else {
                    AjaxResults1 = new AjaxResults(0, "生成token失败");
                    return JSONObject.toJSONString(AjaxResults1);
                }
            } else {
                AjaxResults1 = new AjaxResults(2, "客户端密钥错误");
                return JSONObject.toJSONString(AjaxResults1);
            }
        } else {
            AjaxResults1 = new AjaxResults(0, "参数验证失败");
            return JSONObject.toJSONString(AjaxResults1);
        }
    }

    /**
     * 报警信息数据传输
     */
    @PostMapping("/api/alarm")
    @Transactional(rollbackFor = Exception.class)
    public synchronized String alarm(@RequestBody ParameterVo parameterVo, HttpServletRequest request) throws Exception {
        String token = apiTokenUtils.getGeoHazardMonitorToken(request);
        log.info("token:{}", token);
        log.info("parameter:{}", parameterVo);
        AjaxResults AjaxResults1 = null;
        if (StringUtils.isNotEmpty(token)) {
            String[] split = token.split("-");
            String key = split[split.length - 1];
            if (ObjectUtils.isEmpty(parameterVo)) {
                AjaxResults1 = new AjaxResults(0, "parameterVo参数不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            String s = SM4Utils.decryptData_ECB(parameterVo.getParameter(), key);
            ReqMsgAlarmVo reqMsgAlarmVo = JSON.parseObject(s, ReqMsgAlarmVo.class);
            if (!reqMsgAlarmVo.getAlarmMile().toString().matches(PATTERNS)) {
                AjaxResults1 = new AjaxResults(0, "报警里程位置填写错误");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            if (reqMsgAlarmVo.getLineDir() != 1 && reqMsgAlarmVo.getLineDir() != 2) {
                AjaxResults1 = new AjaxResults(0, "行别填写错误");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            LambdaQueryWrapper<BaseRailwayManagement> queryWrapper = new LambdaQueryWrapper<BaseRailwayManagement>();
            if (!ObjectUtils.isEmpty(reqMsgAlarmVo.getAlarmRailway())) {
                queryWrapper.eq(BaseRailwayManagement::getRailwayCode, reqMsgAlarmVo.getAlarmRailway());
            }
            BaseRailwayManagement baseRailwayManagement = baseRailwayManagementService.getOne(queryWrapper);
            if (ObjectUtils.isEmpty(baseRailwayManagement)) {
                AjaxResults1 = new AjaxResults(0, "填写的报警线路编码不存在");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            if (ObjectUtils.isEmpty(reqMsgAlarmVo.getAlarmId())) {
                AjaxResults1 = new AjaxResults(0, "报警的唯一标识不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            if (ObjectUtils.isEmpty(reqMsgAlarmVo.getAlarmTime())) {
                AjaxResults1 = new AjaxResults(0, "报警时间不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            if (reqMsgAlarmVo.getAlarmType() < 1 || reqMsgAlarmVo.getAlarmType() > 4) {
                AjaxResults1 = new AjaxResults(0, "报警病害类型填写错误");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            if (!reqMsgAlarmVo.getAlarmLevel().toString().matches(PATTERNS)) {
                AjaxResults1 = new AjaxResults(0, "报警级别填写错误");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            if (reqMsgAlarmVo.getAlarmTime().toString().length() == 10) {
                reqMsgAlarmVo.setAlarmTime(reqMsgAlarmVo.getAlarmTime() * 1000);
            }
            log.info("reqMsgAlarmVo:{}", reqMsgAlarmVo);

            LambdaQueryWrapper<BaseCameraManagement> wrapper = new LambdaQueryWrapper<BaseCameraManagement>();
            if (!ObjectUtils.isEmpty(reqMsgAlarmVo.getAlarmMile())) {
                if (reqMsgAlarmVo.getLineDir() == 1) {
                    wrapper.ge(BaseCameraManagement::getEndMile, reqMsgAlarmVo.getAlarmMile());
                    wrapper.le(BaseCameraManagement::getBeginMile, reqMsgAlarmVo.getAlarmMile());
                    wrapper.in(BaseCameraManagement::getMonitoringDirection, 1, 3);
                    wrapper.orderByAsc(BaseCameraManagement::getInstallMile);
                }
                if (reqMsgAlarmVo.getLineDir() == 2) {
                    wrapper.ge(BaseCameraManagement::getEndMile, reqMsgAlarmVo.getAlarmMile());
                    wrapper.le(BaseCameraManagement::getBeginMile, reqMsgAlarmVo.getAlarmMile());
                    wrapper.in(BaseCameraManagement::getMonitoringDirection, 2, 3);
                    wrapper.orderByDesc(BaseCameraManagement::getInstallMile);
                }
                wrapper.eq(BaseCameraManagement::getRailwayCode, reqMsgAlarmVo.getAlarmRailway());
                wrapper.eq(BaseCameraManagement::getOnline, 2);
                wrapper.eq(BaseCameraManagement::getEnableOrNot, 1);
            }
            List<BaseCameraManagement> baseCameraManagementList = baseCameraManagementService.list(wrapper);
            LambdaQueryWrapper<MsgAlarm> lw = new LambdaQueryWrapper<MsgAlarm>();
            if (!ObjectUtils.isEmpty(reqMsgAlarmVo.getAlarmId())) {
                lw.eq(MsgAlarm::getAlarmId, reqMsgAlarmVo.getAlarmId());
            }
            MsgAlarm alarm = msgAlarmService.getOne(lw);
            BaseUser admin = baseUserService.getUserName("admin");
            MsgAlarmFrequency msgAlarmVice = new MsgAlarmFrequency();
            if (ObjectUtils.isEmpty(alarm)) {
                MsgAlarm msgAlarm = new MsgAlarm();
                BeanUtils.copyProperties(reqMsgAlarmVo, msgAlarm);
                BeanUtils.copyProperties(reqMsgAlarmVo, msgAlarmVice);
                msgAlarm.setCreateBy(admin.getUserId());
                msgAlarm.setUpdateBy(admin.getUserId());
                //log.info("时间++++ long ---- " + reqMsgAlarmVo.getAlarmTime());
                //log.info("时间++++" + new Date(reqMsgAlarmVo.getAlarmTime()));
                msgAlarm.setAlarmTime(new Date(reqMsgAlarmVo.getAlarmTime()));
                //log.info("时间++++get" + msgAlarm.getAlarmTime());
                msgAlarm.setRailwayCode(reqMsgAlarmVo.getAlarmRailway());
                String source = split[split.length - 2];
                msgAlarm.setSource(source);
                msgAlarmService.save(msgAlarm);
                if (!ObjectUtils.isEmpty(reqMsgAlarmVo.getFiles())) {
                    Files[] files1 = reqMsgAlarmVo.getFiles();
                    if (files1.length > 0) {
                        for (int i = 0; i < files1.length; i++) {
                            if (ObjectUtils.isEmpty(files1[i].fileUrl)) {
                                AjaxResults1 = new AjaxResults(0, "上传文件地址不能为空!!!");
                                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
                            }
                            if (files1[i].fileType < 1 || files1[i].fileType > 3) {
                                AjaxResults1 = new AjaxResults(0, "文件类型填写错误!!!");
                                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
                            }
                            MsgAlarmExt msgAlarmExt = new MsgAlarmExt();
                            msgAlarmExt.setAlarmId(msgAlarm.getAlarmId());
                            msgAlarmExt.setAlarmAttPath(files1[i].fileUrl);
                            msgAlarmExt.setAlarmAttType(files1[i].fileType);
                            msgAlarmExtService.save(msgAlarmExt);
                        }
                    }
                }
                msgAlarmVice.setCreateBy(admin.getUserId());
                msgAlarmVice.setUpdateBy(admin.getUserId());
                msgAlarmVice.setRailwayCode(reqMsgAlarmVo.getAlarmRailway());
                msgAlarmVice.setAlarmTime(new Date(reqMsgAlarmVo.getAlarmTime()));
                msgAlarmFrequencyService.save(msgAlarmVice);

                log.info("alarmJSON ：{}", JSON.toJSONString(msgAlarm));
                log.info("->>>>>>>>>>>>>>>>>>>>>>>>>>" + msgAlarm);
//                String result = HttpClientUtil.postJson(sdkUrl, JSON.toJSONString(msgAlarm));
//                log.info("->>>>>>>>>>>>>>>>>>>>>>>>>>>>" + result);
//                log.info("result：{}", result);
//                if (!ObjectUtils.isEmpty(baseCameraManagementList)) {
//
//                    // 获取当前时间的前5分钟
//                    List<SysDictData> frontValue = dictTypeService.selectDictDataByType("alarm_time");
//                    Date fiveMinutesAgo = Date.from(Instant.now().minus(Long.valueOf(frontValue.get(0).getDictValue()), ChronoUnit.MINUTES));
//                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                    String formattedDate = sdf.format(fiveMinutesAgo);
//                    LambdaQueryWrapper<MsgAlarm> wrapper1 = new LambdaQueryWrapper<MsgAlarm>();
//                    wrapper1.eq(MsgAlarm::getAlarmMile, alarm.getAlarmMile());
//                    wrapper1.ge(MsgAlarm::getAlarmTime,formattedDate);
//                    List<MsgAlarm> list = msgAlarmService.list(lw);
//                    if (list.size() < 0) {
//                        CompletableFuture.runAsync(() -> {
//                            String records = CameraUtil.getPlayFlvRtsp(baseCameraManagementList.get(0).getCameraCode(), baseCameraManagementList.get(0).getChannel(), true);
//                            log.info("-----records-----------" + records);
//                            MsgAlarm alarm1 = msgAlarmService.getById(msgAlarm.getId());
//                            alarm1.setReleasedUrl(records);
//                            msgAlarmService.updateById(alarm1);
//                        });
//                    }
////                    String url = future.get();
////                    if (url.contains("无视频")) {
////                        jsonObject.put("resultCode", 0);
////                        jsonObject.put("message", url);
////                        return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), key);
////                    }else {
////                    }
//                }
            } else {
                BeanUtils.copyProperties(reqMsgAlarmVo, msgAlarmVice);
                msgAlarmVice.setCreateBy(admin.getUserId());
                msgAlarmVice.setUpdateBy(admin.getUserId());
                msgAlarmVice.setAlarmTime(new Date(reqMsgAlarmVo.getAlarmTime()));
                msgAlarmVice.setRailwayCode(reqMsgAlarmVo.getAlarmRailway());
                msgAlarmFrequencyService.save(msgAlarmVice);
            }
            AjaxResults1 = new AjaxResults(1, "ok");
            return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
        } else {
            AjaxResults1 = new AjaxResults(2, "token验证失败");
            return JSONObject.toJSONString(AjaxResults1);
        }
    }

    /**
     * 报警解除接口
     *
     * @param parameterVo
     * @param request
     * @return
     */
    @PostMapping("/api/releaseAlarm")
    public String releaseAlarm(@RequestBody ParameterVo parameterVo, HttpServletRequest request) {
        AjaxResults AjaxResults1 = null;
        String token = apiTokenUtils.getGeoHazardMonitorToken(request);
        log.info("token:{}", token);
        log.info("parameter:{}", parameterVo);
        if (StringUtils.isNotEmpty(token)) {
            String[] split = token.split("-");
            String key = split[split.length - 1];
            if (ObjectUtils.isEmpty(parameterVo)) {
                AjaxResults1 = new AjaxResults(0, "parameterVo参数不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            String s = SM4Utils.decryptData_ECB(parameterVo.getParameter(), key);
            ReleaseAlarmVo releaseAlarmVo = JSON.parseObject(s, ReleaseAlarmVo.class);
            if (ObjectUtils.isEmpty(releaseAlarmVo.getAlarmId())) {
                AjaxResults1 = new AjaxResults(0, "报警的唯一标识不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            if (ObjectUtils.isEmpty(releaseAlarmVo.getReleaseTime())) {
                AjaxResults1 = new AjaxResults(0, "解除报警时间不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            if (ObjectUtils.isEmpty(releaseAlarmVo.getReleaseContent())) {
                AjaxResults1 = new AjaxResults(0, "解除原因不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            if (ObjectUtils.isEmpty(releaseAlarmVo.getReleaseTime())) {
                AjaxResults1 = new AjaxResults(0, "解除人不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            LambdaQueryWrapper<MsgAlarm> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(MsgAlarm::getAlarmId, releaseAlarmVo.getAlarmId());
            MsgAlarm msgAlarm = msgAlarmService.getOne(wrapper);
            if (ObjectUtils.isEmpty(msgAlarm)) {
                AjaxResults1 = new AjaxResults(0, "不存在该报警的唯一标识的数据");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            if (releaseAlarmVo.getReleaseTime().toString().length() == 10) {
                releaseAlarmVo.setReleaseTime(releaseAlarmVo.getReleaseTime() * 1000);
            }
            Calendar cal = Calendar.getInstance();
            cal.setTime(new Date(releaseAlarmVo.getReleaseTime()));
            cal.set(Calendar.MILLISECOND, 0);
            cal.set(Calendar.MILLISECOND, 0);
            msgAlarm.setReleasedTime(cal.getTime());
            msgAlarm.setReleaseContent(releaseAlarmVo.getReleaseContent());
            msgAlarm.setReleasedBy(releaseAlarmVo.getOperator());
            msgAlarm.setUpdateBy(releaseAlarmVo.getOperator());
            msgAlarm.setUpdateTime(new Date());
            msgAlarm.setIsRelease(1);
            boolean count = msgAlarmService.updateById(msgAlarm);
            Map<String, Object> map = new HashMap<>();
            map.put("alarmId", msgAlarm.getAlarmId());
            if (count) {
                map.put("releaseState", 1);
                AjaxResults1 = new AjaxResults(1, "ok", map);
            } else {
                map.put("releaseState", 2);
                AjaxResults1 = new AjaxResults(0, "失败", map);
            }
            return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
        } else {
            AjaxResults1 = new AjaxResults(2, "token验证失败");
            return JSONObject.toJSONString(AjaxResults1);
        }
    }

    /**
     * 车载心跳机制交互
     *
     * @param parameterVo
     * @param request
     * @return
     */
    @PostMapping("/api/terminal/heartbeat")
    @Transactional
    public String heartbeat(@RequestBody ParameterVo parameterVo, HttpServletRequest request) throws Exception {
        long begin = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        log.info("接受心跳时间: " + sdf.format(new Date(begin)));
        Map<String, Object> twoMap = new HashMap<>();
        String playFlv1 = null;
        int distance = 0;
        boolean type = true;
        RespHeartbeatVo respHeartbeatVo = new RespHeartbeatVo();
        String token = apiTokenUtils.getGeoHazardMonitorToken(request);
        log.info("token:{}", token);
        log.info("parameter:{}", parameterVo);
        AjaxResults AjaxResults1 = null;
        if (StringUtils.isNotEmpty(token)) {
            String[] split = token.split("-");
            String key = split[split.length - 1];
            if (ObjectUtils.isEmpty(parameterVo)) {
                AjaxResults1 = new AjaxResults(0, "parameterVo参数不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            //  1.  解密参数
            String s = SM4Utils.decryptData_ECB(parameterVo.getParameter(), key);
            //  2、 心跳参数
            HeartbeatVo heartbeatVo = JSON.parseObject(s, HeartbeatVo.class);
            if (ObjectUtils.isEmpty(heartbeatVo.getTerminalCode())) {
                AjaxResults1 = new AjaxResults(0, "车载终端编码不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            if (!heartbeatVo.getCurrentMile().toString().matches(PATTERNS)) {
                AjaxResults1 = new AjaxResults(0, "当前里程位置填写错误");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            if (ObjectUtils.isEmpty(heartbeatVo.getLatitude())) {
                AjaxResults1 = new AjaxResults(0, "当前所在纬度不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            if (ObjectUtils.isEmpty(heartbeatVo.getLongitude())) {
                AjaxResults1 = new AjaxResults(0, "当前所在经度不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            LambdaQueryWrapper<BaseRailwayManagement> railway = new LambdaQueryWrapper<BaseRailwayManagement>();
            if (!ObjectUtils.isEmpty(heartbeatVo.getRailwayCode())) {
                railway.eq(BaseRailwayManagement::getRailwayCode, heartbeatVo.getRailwayCode());
            }
            BaseRailwayManagement baseRailwayManagement = baseRailwayManagementService.getOne(railway);
            if (ObjectUtils.isEmpty(baseRailwayManagement)) {
                AjaxResults1 = new AjaxResults(0, "填写的线路编码不存在");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            if (heartbeatVo.getLineDir() != 1 && heartbeatVo.getLineDir() != 2) {
                AjaxResults1 = new AjaxResults(0, "行别填写错误");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            if (!heartbeatVo.getVisualDistance().toString().matches(PATTERNS)) {
                AjaxResults1 = new AjaxResults(0, "司机目视距离填写错误");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            if (heartbeatVo.getSignalStrength() != 1 && heartbeatVo.getSignalStrength() != 2) {
                AjaxResults1 = new AjaxResults(0, "信号强度填写错误");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            VehiclePosition vehiclePosition = new VehiclePosition();
            BaseVideoTrains baseVideoTrains = new BaseVideoTrains();
            BeanUtils.copyProperties(heartbeatVo, vehiclePosition);
            LambdaQueryWrapper<BaseVehicleTerminal> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(BaseVehicleTerminal::getTerminalCode, vehiclePosition.getTerminalCode());
            BaseVehicleTerminal baseTerminal = baseVehicleTerminalService.getOne(wrapper);
            if (ObjectUtils.isEmpty(baseTerminal)) {
                AjaxResults1 = new AjaxResults(0, "关联表中没有改终端编码的信息");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            if (heartbeatVo.getSignalStrength() == 2) {
                type = false;
            }
            vehiclePosition.setTravelMile(heartbeatVo.getCurrentMile());
            vehiclePosition.setVehicleCode(baseTerminal.getVehicleCode());
            vehiclePosition.setTerminalLatitude(heartbeatVo.getLatitude());
            vehiclePosition.setTerminalLongitude(heartbeatVo.getLongitude());
            vehiclePosition.setCreateTime(new Date());
            vehiclePosition.setCurrenTime(vehiclePosition.getCreateTime());
            //机车行驶表添加数据
            boolean save = vehiclePositionService.save(vehiclePosition);
            baseVideoTrains.setTrainsMile(heartbeatVo.getCurrentMile());
            //目视距离和里程位置
            if (save) {
                LambdaQueryWrapper<MsgAlarm> queryWrapper = new LambdaQueryWrapper<>();
                if (heartbeatVo.getLineDir() == 1) {
                    queryWrapper.ge(MsgAlarm::getAlarmMile, heartbeatVo.getCurrentMile());
                    queryWrapper.le(MsgAlarm::getAlarmMile, (heartbeatVo.getCurrentMile() + 10000));
                    queryWrapper.orderByAsc(MsgAlarm::getAlarmMile);
                } else if (heartbeatVo.getLineDir() == 2) {
                    queryWrapper.le(MsgAlarm::getAlarmMile, heartbeatVo.getCurrentMile());
                    queryWrapper.ge(MsgAlarm::getAlarmMile, (heartbeatVo.getCurrentMile() - 10000));
                    queryWrapper.orderByDesc(MsgAlarm::getAlarmMile);
                }
                queryWrapper.eq(MsgAlarm::getRailwayCode, heartbeatVo.getRailwayCode());
                queryWrapper.eq(MsgAlarm::getIsRelease, 2);
                List<MsgAlarm> alarmsList = msgAlarmService.list(queryWrapper);
                //根据终端编码 判断终端忽略报警信息记录表中的是否有忽略的报警
                PreAlarm preAlarm = preAlarmService.getOne(new LambdaQueryWrapper<PreAlarm>()
                        .eq(PreAlarm::getTrainId, heartbeatVo.getTrainNum())
                        .orderByDesc(PreAlarm::getPreAlarmTime)
                        .last("limit 1"));
                if (!ObjectUtils.isEmpty(alarmsList)) {
                    // 获取当前时间
                    LocalDateTime currentDateTime = LocalDateTime.now();
                    // 获取前一天的时间
                    LocalDateTime previousDateTime = currentDateTime.minusDays(1);
                    // 格式化日期时间
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    String currentFormattedDateTime = currentDateTime.format(formatter);
                    String previousFormattedDateTime = previousDateTime.format(formatter);

                    LambdaQueryWrapper<TerminalIgnoreAlarm> queryWrapper1 = new LambdaQueryWrapper<>();
                    //报警信息表中报警标识的信息
                    List<String> collect = alarmsList.stream().map(MsgAlarm::getAlarmId).collect(Collectors.toList());
                    queryWrapper1.in(TerminalIgnoreAlarm::getAlarmId, collect);
                    queryWrapper1.eq(TerminalIgnoreAlarm::getTerminalCode, heartbeatVo.getTerminalCode());
                    queryWrapper1.ge(TerminalIgnoreAlarm::getIgnoreTime, previousFormattedDateTime);
                    queryWrapper1.le(TerminalIgnoreAlarm::getIgnoreTime, currentFormattedDateTime);
                    //终端忽略报警信息记录表
                    List<TerminalIgnoreAlarm> list2 = terminalIgnoreAlarmService.list(queryWrapper1);
                    //找出未忽略的报警信息
                    LambdaQueryWrapper<MsgAlarm> queryWrapper2 = new LambdaQueryWrapper<>();
                    if (!ObjectUtils.isEmpty(list2)) {
                        //忽略报警表中报警标识的信息
                        List<String> collect1 = list2.stream().map(TerminalIgnoreAlarm::getAlarmId).collect(Collectors.toList());
                        List<String> list = collect.stream()
                                .filter(item -> !collect1.contains(item))
                                .collect(Collectors.toList());
                        if (!ObjectUtils.isEmpty(list)) {
                            queryWrapper2.in(MsgAlarm::getAlarmId, list);
                        } else {
                            queryWrapper2.eq(MsgAlarm::getAlarmId, "1111111111111");
                        }
                    } else {
                        queryWrapper2.in(MsgAlarm::getAlarmId, collect);
                    }
                    if (heartbeatVo.getLineDir() == 1) {
                        queryWrapper2.orderByAsc(MsgAlarm::getAlarmMile);
                    } else if (heartbeatVo.getLineDir() == 2) {
                        queryWrapper2.orderByDesc(MsgAlarm::getAlarmMile);
                    }
                    List<MsgAlarm> list = msgAlarmService.list(queryWrapper2);
                    log.info("--------List<MsgAlarm>--------" + list);
                    //有报警信息的时候
                    LambdaQueryWrapper<BaseCameraManagement> camera = new LambdaQueryWrapper<BaseCameraManagement>();
                    if (!ObjectUtils.isEmpty(list)) {
                        //获取报警里程所监控的所有相机
                        if (heartbeatVo.getLineDir() == 1) {
                            log.info("-------getLineDir() == 1--------" + list.get(0).getAlarmMile());
                            camera.ge(BaseCameraManagement::getEndMile, list.get(0).getAlarmMile());
                            camera.le(BaseCameraManagement::getBeginMile, list.get(0).getAlarmMile());
                            camera.in(BaseCameraManagement::getMonitoringDirection, 1, 3);
                            camera.orderByAsc(BaseCameraManagement::getGrou).orderByAsc(BaseCameraManagement::getSort);
                        }
                        if (heartbeatVo.getLineDir() == 2) {
                            log.info("-------getLineDir() == 2--------" + list.get(0).getAlarmMile());
                            camera.ge(BaseCameraManagement::getEndMile, list.get(0).getAlarmMile());
                            camera.le(BaseCameraManagement::getBeginMile, list.get(0).getAlarmMile());
                            camera.in(BaseCameraManagement::getMonitoringDirection, 2, 3);
                            camera.orderByDesc(BaseCameraManagement::getGrou).orderByDesc(BaseCameraManagement::getSort);
                        }
                        camera.eq(BaseCameraManagement::getRailwayCode, heartbeatVo.getRailwayCode());
                        camera.eq(BaseCameraManagement::getOnline, 2);
                        camera.eq(BaseCameraManagement::getEnableOrNot, 1);
                        List<BaseCameraManagement> baseCameraManagementList = baseCameraManagementService.list(camera);
                        log.info("-------baseCameraManagementList123111--------" + baseCameraManagementList);
                        List<AlarmListVo> listVos = new ArrayList<>();
                        if (baseCameraManagementList.size() > 0) {
                            int minDifference = Integer.MAX_VALUE;
                            String code = null;
                            String channel = null;
                            for (BaseCameraManagement baseCameraManagement : baseCameraManagementList) {
                                log.info("------------baseCameraManagement.getInstallMile()-------" + baseCameraManagement.getInstallMile());
                                log.info("------------list.get(0).getAlarmMile()-------" + list.get(0).getAlarmMile());
                                int difference = Math.abs(baseCameraManagement.getInstallMile() - list.get(0).getAlarmMile());
                                log.info("------------difference-------" + difference);
                                log.info("------------minDifference-------" + minDifference);
                                if (difference < minDifference) {
                                    minDifference = difference;
                                    log.info("------------minDifference变更-------" + minDifference);
                                    code = baseCameraManagement.getCameraCode();
                                    log.info("------------code-------" + code);
                                    channel = baseCameraManagement.getChannel();
                                    log.info("------------channel-------" + channel);
                                }
                            }
                            playFlv1 = CameraUtil.getPlayFlvRtsp(code, channel, type);
                            if (StringUtils.isEmpty(playFlv1)) {
                                playFlv1 = CameraUtil.getPlayFlvRtsp(code, channel, type);
                                if (playFlv1.contains("无视频")) {
                                    AjaxResults1 = new AjaxResults(0, playFlv1);
                                    return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
                                }
                            }
                            log.info("-------playFlv--------" + playFlv1);
                            CameraVos cameraVos = new CameraVos();
                            cameraVos.setCameraCode(code);
                            cameraVos.setCurrentStream(playFlv1);
                            List<CameraVos> cameraVosList = new ArrayList<>();
                            cameraVosList.add(cameraVos);
                            respHeartbeatVo.setCameraList(cameraVosList);
                            respHeartbeatVo.setIsAlarm(1);
                            twoMap.put("currentStream", playFlv1);
                            twoMap.put("cameraCode", baseCameraManagementList.get(0).getCameraCode());
                        }
                        for (int i = 0; i < list.size(); i++) {
                            MsgHeartbeatAlarmMessage msgHearbeatAlarmMessage = new MsgHeartbeatAlarmMessage();
                            msgHearbeatAlarmMessage.setAlarmId(list.get(i).getAlarmId());
                            msgHearbeatAlarmMessage.setTerminalCode(heartbeatVo.getTerminalCode());
                            msgHearbeatAlarmMessage.setTrainNum(heartbeatVo.getTrainNum());
                            msgHearbeatAlarmMessageMapper.insert(msgHearbeatAlarmMessage);
                            //获取剩余的报警信息
                            LambdaQueryWrapper<BaseCameraManagement> ment = new LambdaQueryWrapper<BaseCameraManagement>();
                            ment.eq(BaseCameraManagement::getRailwayCode, heartbeatVo.getRailwayCode());
                            ment.eq(BaseCameraManagement::getOnline, 2);
                            ment.eq(BaseCameraManagement::getEnableOrNot, 1);
                            if (heartbeatVo.getLineDir() == 1) {
                                ment.ge(BaseCameraManagement::getEndMile, list.get(i).getAlarmMile());
                                ment.le(BaseCameraManagement::getBeginMile, list.get(i).getAlarmMile());
                                ment.in(BaseCameraManagement::getMonitoringDirection, 1, 3);
                                ment.orderByAsc(BaseCameraManagement::getGrou).orderByAsc(BaseCameraManagement::getSort);
                            } else if (heartbeatVo.getLineDir() == 2) {
                                ment.ge(BaseCameraManagement::getEndMile, list.get(i).getAlarmMile());
                                ment.le(BaseCameraManagement::getBeginMile, list.get(i).getAlarmMile());
                                ment.in(BaseCameraManagement::getMonitoringDirection, 2, 3);
                                ment.orderByDesc(BaseCameraManagement::getGrou).orderByDesc(BaseCameraManagement::getSort);
                            }
                            //获取所有报警安装里程位置的相机
                            List<BaseCameraManagement> baseList = baseCameraManagementService.list(ment);
                            if (baseList.size() > 0) {
                                if (i > 0) {
                                    int minDifference = Integer.MAX_VALUE;
                                    String code = null;
                                    String channel = null;
                                    for (BaseCameraManagement baseCameraManagement : baseList) {
                                        log.info("------------baseCameraManagement.getInstallMile()-------" + baseCameraManagement.getInstallMile());
                                        log.info("------------list.get(0).getAlarmMile()-------" + list.get(0).getAlarmMile());
                                        int difference = Math.abs(baseCameraManagement.getInstallMile() - list.get(0).getAlarmMile());
                                        log.info("------------difference-------" + difference);
                                        log.info("------------minDifference-------" + minDifference);
                                        if (difference < minDifference) {
                                            minDifference = difference;
                                            log.info("------------minDifference变更-------" + minDifference);
                                            code = baseCameraManagement.getCameraCode();
                                            log.info("------------code-------" + code);
                                            channel = baseCameraManagement.getChannel();
                                            log.info("------------channel-------" + channel);
                                        }
                                    }
                                    playFlv1 = CameraUtil.getPlayFlvRtsp(code, channel, type);
                                }
                                AlarmListVo alarmListVo = new AlarmListVo();
                                //alarmList对象
                                if (playFlv1 != null) {
                                    alarmListVo.setCameraStream(playFlv1);
                                } else {
                                    alarmListVo.setCameraStream("");
                                }
                                alarmListVo.setCameraCode(baseList.get(0).getCameraCode());
                                //alarmInfo对象
                                AlarmInfoVo alarmInfoVo1 = new AlarmInfoVo();
                                log.info("----------------list.get(i).getAlarmId()---后续-----------" + list.get(i).getAlarmId());
                                alarmInfoVo1.setAlarmId(list.get(i).getAlarmId());
                                alarmInfoVo1.setAlarmMile(list.get(i).getAlarmMile());
                                alarmInfoVo1.setAlarmTime(list.get(i).getAlarmTime().getTime());
                                alarmInfoVo1.setAlarmType(list.get(i).getAlarmType());
                                alarmInfoVo1.setAlarmContent(list.get(i).getContent());
                                alarmInfoVo1.setAlarmLevel(list.get(i).getAlarmLevel());
                                LambdaQueryWrapper<MsgAlarmExt> alarm = new LambdaQueryWrapper<>();
                                alarm.eq(MsgAlarmExt::getAlarmId, list.get(i).getAlarmId());
                                List<MsgAlarmExt> list1 = msgAlarmExtService.list(alarm);
                                if (list1.size() > 0) {
                                    AlarmFilesVo[] vo = new AlarmFilesVo[list1.size()];
                                    for (int i1 = 0; i1 < list1.size(); i1++) {
                                        vo[i1] = new AlarmFilesVo();
                                        vo[i1].setAlarmAttType(list1.get(i1).getAlarmAttType());
                                        vo[i1].setAlarmAttPath(list1.get(i1).getAlarmAttPath());
                                    }
                                    alarmInfoVo1.setAlarmFiles(vo);
                                }
                                alarmListVo.setAlarmInfo(alarmInfoVo1);
                                log.info("----------------alarmListVo-----------" + alarmListVo);
                                listVos.add(alarmListVo);
                            }
                        }
                        AlarmListVo[] array = listVos.toArray(new AlarmListVo[]{});
                        log.info("----------------array-----------" + Arrays.toString(array));
                        respHeartbeatVo.setAlarmList(array);
                        //获取机车前一路视频
                        int mile = heartbeatVo.getVisualDistance() + heartbeatVo.getCurrentMile();
                        LambdaQueryWrapper<BaseCameraManagement> base = new LambdaQueryWrapper<>();
                        if (heartbeatVo.getLineDir() == 1) {
                            base.orderByAsc(BaseCameraManagement::getGrou).orderByAsc(BaseCameraManagement::getSort);
                            base.gt(BaseCameraManagement::getInstallMile, mile);
                        }
                        if (heartbeatVo.getLineDir() == 2) {
                            base.orderByDesc(BaseCameraManagement::getGrou).orderByDesc(BaseCameraManagement::getSort);
                            base.lt(BaseCameraManagement::getInstallMile, mile);
                        }
                        base.eq(BaseCameraManagement::getRailwayCode, heartbeatVo.getRailwayCode());
                        base.eq(BaseCameraManagement::getOnline, 2);
                        base.eq(BaseCameraManagement::getEnableOrNot, 1);
                        base.last("limit 1");
                        BaseCameraManagement baseCameraManagement = baseCameraManagementService.getOne(base);
                        //根据相机ID找出分组并排序
                        List<BaseCameraManagement> baseCameraManagementList1 = cameraUtil.getBaseCameraManagementList(baseCameraManagement.getId(), heartbeatVo.getLineDir());
                        if (!ObjectUtils.isEmpty(baseCameraManagementList1)) {
                            for (BaseCameraManagement cameraManagement : baseCameraManagementList1) {
                                String playFlv = CameraUtil.getPlayFlvRtsp(cameraManagement.getCameraCode(), cameraManagement.getChannel(), type);
                                if (StringUtils.isEmpty(playFlv)) {
                                    String url = CameraUtil.getPlayFlvRtsp(cameraManagement.getCameraCode(), cameraManagement.getChannel(), type);
                                    if (url.contains("无视频")) {
                                        AjaxResults1 = new AjaxResults(0, url);
                                        return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
                                    }
                                }
                            }
                        }
                    } else if (!ObjectUtils.isEmpty(preAlarm)) {
                        List<PreAlarmListResponse> responseList = new ArrayList<>();
                        List<PreAlarmResponse.PreAlarmList> preAlarmList = JSON.parseArray(preAlarm.getPreAlarmList(), PreAlarmResponse.PreAlarmList.class);
                        Comparator<PreAlarmResponse.PreAlarmList> distanceComparator = new Comparator<PreAlarmResponse.PreAlarmList>() {
                            @Override
                            public int compare(PreAlarmResponse.PreAlarmList o1, PreAlarmResponse.PreAlarmList o2) {
                                return Integer.compare(o1.getDistance(), o2.getDistance());
                            }
                        };
                        //排序
                        preAlarmList.sort(distanceComparator);
                        for (int i = 0; i < preAlarmList.size(); i++) {
                            PreAlarmListResponse preAlarmListResponse = new PreAlarmListResponse();
                            int mile = 0;
                            LambdaQueryWrapper<BaseCameraManagement> wrapper1 = new LambdaQueryWrapper<BaseCameraManagement>();
                            if (heartbeatVo.getLineDir() == 1) {
                                mile = preAlarmList.get(i).getDistance() + heartbeatVo.getCurrentMile();
                                wrapper1.ge(BaseCameraManagement::getEndMile, mile);
                                wrapper1.le(BaseCameraManagement::getBeginMile, mile);
                                wrapper1.in(BaseCameraManagement::getMonitoringDirection, 1, 3);
                                wrapper1.orderByAsc(BaseCameraManagement::getGrou).orderByAsc(BaseCameraManagement::getSort);
                            }
                            if (heartbeatVo.getLineDir() == 2) {
                                mile = heartbeatVo.getCurrentMile() - preAlarmList.get(i).getDistance();
                                wrapper1.ge(BaseCameraManagement::getEndMile, mile);
                                wrapper1.le(BaseCameraManagement::getBeginMile, mile);
                                wrapper1.in(BaseCameraManagement::getMonitoringDirection, 2, 3);
                                wrapper1.orderByDesc(BaseCameraManagement::getGrou).orderByDesc(BaseCameraManagement::getSort);
                            }
                            List<BaseCameraManagement> baseCameraManagementList = baseCameraManagementService.list(wrapper1);
                            log.info("-------baseCameraManagementList123111--------" + baseCameraManagementList);
                            if (baseCameraManagementList.size() > 0) {
                                int minDifference = Integer.MAX_VALUE;
                                String code = null;
                                String channel = null;
                                for (BaseCameraManagement baseCameraManagement : baseCameraManagementList) {
                                    log.info("------------baseCameraManagement.getInstallMile()-------" + baseCameraManagement.getInstallMile());
                                    log.info("------------list.get(0).getAlarmMile()-------" + mile);
                                    int difference = Math.abs(baseCameraManagement.getInstallMile() - mile);
                                    log.info("------------difference-------" + difference);
                                    log.info("------------minDifference-------" + minDifference);
                                    if (difference < minDifference) {
                                        minDifference = difference;
                                        log.info("------------minDifference变更-------" + minDifference);
                                        code = baseCameraManagement.getCameraCode();
                                        log.info("------------code-------" + code);
                                        channel = baseCameraManagement.getChannel();
                                        log.info("------------channel-------" + channel);
                                    }
                                    //添加预警信息
                                    preAlarmListResponse.setCameraCode(baseCameraManagement.getCameraCode());
                                    preAlarmListResponse.setCameraStream(CameraUtil.getPlayFlvRtsp(baseCameraManagement.getCameraCode(), baseCameraManagement.getChannel(), type));
                                }
                                if (i == 0) {
                                    playFlv1 = CameraUtil.getPlayFlvRtsp(code, channel, type);
                                    if (StringUtils.isEmpty(playFlv1)) {
                                        playFlv1 = CameraUtil.getPlayFlvRtsp(code, channel, type);
                                        if (playFlv1.contains("无视频")) {
                                            AjaxResults1 = new AjaxResults(0, playFlv1);
                                            return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
                                        }
                                    }
                                    log.info("-------playFlv--------" + playFlv1);
                                    CameraVos cameraVos = new CameraVos();
                                    cameraVos.setCameraCode(code);
                                    cameraVos.setCurrentStream(playFlv1);
                                    List<CameraVos> cameraVosList = new ArrayList<>();
                                    cameraVosList.add(cameraVos);
                                    respHeartbeatVo.setCameraList(cameraVosList);
                                    respHeartbeatVo.setIsAlarm(1);
                                    twoMap.put("currentStream", playFlv1);
                                    twoMap.put("cameraCode", baseCameraManagementList.get(0).getCameraCode());
                                }
                            } else {
                                preAlarmListResponse.setCameraCode("");
                                preAlarmListResponse.setCameraStream("");
                            }
                            BeanUtils.copyProperties(preAlarmList.get(i), preAlarmListResponse);
                            responseList.add(preAlarmListResponse);
                        }
                        respHeartbeatVo.setPreAlarmList(responseList);
                    } else {
                        BaseCameraManagementReq baseCameraManagementReq = new BaseCameraManagementReq();
                        //没有报警信息的时候
                        if (heartbeatVo.getLineDir() == 1) {
                            distance = heartbeatVo.getVisualDistance() + heartbeatVo.getCurrentMile();
                            baseCameraManagementReq.setInstallMile(heartbeatVo.getCurrentMile() + 10000);
                        }
                        if (heartbeatVo.getLineDir() == 2) {
                            distance = heartbeatVo.getCurrentMile() - heartbeatVo.getVisualDistance();
                            baseCameraManagementReq.setInstallMile(heartbeatVo.getCurrentMile() - 10000);
                        }
                        baseCameraManagementReq.setDistance(distance);
                        baseCameraManagementReq.setLineDir(heartbeatVo.getLineDir());
                        baseCameraManagementReq.setRailwayCode(heartbeatVo.getRailwayCode());
                        List<BaseCameraManagement> list1 = baseCameraManagementService.cameraMangemnetList(baseCameraManagementReq);
                        if (list1.size() <= 0) {
                            AjaxResults1 = new AjaxResults(0, "前方没有摄像机", respHeartbeatVo);
                            return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
                        }
                        log.info("流程1----------------->");
                        //判断流媒体是否有流
                        String playFlv = CameraUtil.getPlayFlvRtsp(list1.get(0).getCameraCode(), list1.get(0).getChannel(), type);
                        log.info("playFlv------------>" + playFlv);
                        baseVideoTrains.setVideoMile(list1.get(0).getInstallMile());
                        long delay = System.currentTimeMillis();
                        log.info("关联距离时间: " + sdf.format(new Date(delay)));
                        long mile = delay - begin;
                        log.info("关联距离请求用时时间:" + mile + "毫秒");
                        baseVideoTrains.setDelay((int) mile);
                        if (heartbeatVo.getLineDir() == 1) {
                            baseVideoTrains.setDistance(list1.get(0).getInstallMile() - heartbeatVo.getCurrentMile());
                        } else {
                            baseVideoTrains.setDistance(heartbeatVo.getCurrentMile() - list1.get(0).getInstallMile());
                        }
                        if (baseVideoTrains.getDistance() >= 1000 && baseVideoTrains.getDistance() <= 10000) {
                            baseVideoTrains.setIsAccuracy(1);
                        } else {
                            baseVideoTrains.setIsAccuracy(2);
                        }
                        //拉两路视频
                        if (StringUtils.isEmpty(playFlv)) {
                            log.info("--------------->>已进入拉两路视频");
                            for (BaseCameraManagement baseCameraManagement : list1) {
                                List<BaseCameraManagement> baseCameraManagementList1 = cameraUtil.getBaseCameraManagementList(baseCameraManagement.getId(), heartbeatVo.getLineDir());
                                if (!ObjectUtils.isEmpty(baseCameraManagementList1)) {
                                    for (BaseCameraManagement cameraManagement : baseCameraManagementList1) {
                                        String flv = CameraUtil.getPlayFlvRtsp(cameraManagement.getCameraCode(), cameraManagement.getChannel(), type);
                                        if (StringUtils.isEmpty(flv)) {
                                            String url = CameraUtil.getPlayFlvRtsp(cameraManagement.getCameraCode(), cameraManagement.getChannel(), type);
                                            if (url.contains("无视频")) {
                                                AjaxResults1 = new AjaxResults(0, url);
                                                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
                                            }
                                        }
                                    }
                                }
                                BaseCameraManagement idOne = baseCameraManagementService.getById(list1.get(0).getId());
                                BaseCameraManagement idTwo = baseCameraManagementService.getById(list1.get(1).getId());
                                if (idOne.getGrou().equals(idTwo.getGrou())) {
                                    break;
                                }
                            }
//                            CompletableFuture.runAsync(() -> {
//                                cameraUtil.removePlayFlv(heartbeatVo.getLineDir(), heartbeatVo.getCurrentMile(), heartbeatVo.getVisualDistance());
//                            });
                        } else {
                            log.info("-------------->>已进入拉一路视频");
                            log.info("list1-------------->>" + list1.size());
                            for (int i = 1; i < list1.size(); i++) {
                                List<BaseCameraManagement> baseCameraManagementList1 = cameraUtil.getBaseCameraManagementList(list1.get(i).getId(), heartbeatVo.getLineDir());
                                if (!ObjectUtils.isEmpty(baseCameraManagementList1)) {
                                    for (BaseCameraManagement cameraManagement : baseCameraManagementList1) {
                                        String flv = CameraUtil.getPlayFlvRtsp(cameraManagement.getCameraCode(), cameraManagement.getChannel(), type);
                                        if (StringUtils.isEmpty(flv)) {
                                            String url = CameraUtil.getPlayFlvRtsp(cameraManagement.getCameraCode(), cameraManagement.getChannel(), type);
                                            if (url.contains("无视频")) {
                                                AjaxResults1 = new AjaxResults(0, url);
                                                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        List<BaseCameraManagement> baseCameraManagementList1 = cameraUtil.getBaseCameraManagementList(list1.get(0).getId(), heartbeatVo.getLineDir());
                        if (!ObjectUtils.isEmpty(baseCameraManagementList1)) {
                            List<CameraVos> cameraVosList = new ArrayList<>();
                            for (BaseCameraManagement baseCameraManagement : baseCameraManagementList1) {
                                CameraVos cameraVos = new CameraVos();
                                cameraVos.setCameraCode(baseCameraManagement.getCameraCode());
                                cameraVos.setCurrentStream(CameraUtil.getPlayFlvRtsp(baseCameraManagement.getCameraCode(), baseCameraManagement.getChannel(), type));
                                cameraVosList.add(cameraVos);
                            }
                            respHeartbeatVo.setCameraList(cameraVosList);
                        }
                        twoMap.put("currentStream", playFlv);
                        twoMap.put("cameraCode", list1.get(0).getCameraCode());
                        respHeartbeatVo.setIsAlarm(2);
                    }
                } else if (!ObjectUtils.isEmpty(preAlarm)) {
                    List<PreAlarmListResponse> responseList = new ArrayList<>();
                    List<PreAlarmResponse.PreAlarmList> preAlarmList = JSON.parseArray(preAlarm.getPreAlarmList(), PreAlarmResponse.PreAlarmList.class);
                    Comparator<PreAlarmResponse.PreAlarmList> distanceComparator = new Comparator<PreAlarmResponse.PreAlarmList>() {
                        @Override
                        public int compare(PreAlarmResponse.PreAlarmList o1, PreAlarmResponse.PreAlarmList o2) {
                            return Integer.compare(o1.getDistance(), o2.getDistance());
                        }
                    };
                    //排序
                    preAlarmList.sort(distanceComparator);
                    for (int i = 0; i < preAlarmList.size(); i++) {
                        PreAlarmListResponse preAlarmListResponse = new PreAlarmListResponse();
                        int mile = 0;
                        LambdaQueryWrapper<BaseCameraManagement> wrapper1 = new LambdaQueryWrapper<BaseCameraManagement>();
                        if (heartbeatVo.getLineDir() == 1) {
                            mile = preAlarmList.get(i).getDistance() + heartbeatVo.getCurrentMile();
                            wrapper1.ge(BaseCameraManagement::getEndMile, mile);
                            wrapper1.le(BaseCameraManagement::getBeginMile, mile);
                            wrapper1.in(BaseCameraManagement::getMonitoringDirection, 1, 3);
                            wrapper1.orderByAsc(BaseCameraManagement::getGrou).orderByAsc(BaseCameraManagement::getSort);
                        }
                        if (heartbeatVo.getLineDir() == 2) {
                            mile = heartbeatVo.getCurrentMile() - preAlarmList.get(i).getDistance();
                            wrapper1.ge(BaseCameraManagement::getEndMile, mile);
                            wrapper1.le(BaseCameraManagement::getBeginMile, mile);
                            wrapper1.in(BaseCameraManagement::getMonitoringDirection, 2, 3);
                            wrapper1.orderByDesc(BaseCameraManagement::getGrou).orderByDesc(BaseCameraManagement::getSort);
                        }
                        List<BaseCameraManagement> baseCameraManagementList = baseCameraManagementService.list(wrapper1);
                        log.info("-------baseCameraManagementList123111--------" + baseCameraManagementList);
                        if (baseCameraManagementList.size() > 0) {
                            int minDifference = Integer.MAX_VALUE;
                            String code = null;
                            String channel = null;
                            for (BaseCameraManagement baseCameraManagement : baseCameraManagementList) {
                                log.info("------------baseCameraManagement.getInstallMile()-------" + baseCameraManagement.getInstallMile());
                                log.info("------------list.get(0).getAlarmMile()-------" + mile);
                                int difference = Math.abs(baseCameraManagement.getInstallMile() - mile);
                                log.info("------------difference-------" + difference);
                                log.info("------------minDifference-------" + minDifference);
                                if (difference < minDifference) {
                                    minDifference = difference;
                                    log.info("------------minDifference变更-------" + minDifference);
                                    code = baseCameraManagement.getCameraCode();
                                    log.info("------------code-------" + code);
                                    channel = baseCameraManagement.getChannel();
                                    log.info("------------channel-------" + channel);
                                }
                                //添加预警信息
                                preAlarmListResponse.setCameraCode(baseCameraManagement.getCameraCode());
                                preAlarmListResponse.setCameraStream(CameraUtil.getPlayFlvRtsp(baseCameraManagement.getCameraCode(), baseCameraManagement.getChannel(), type));
                            }
                            if (i == 0) {
                                playFlv1 = CameraUtil.getPlayFlvRtsp(code, channel, type);
                                if (StringUtils.isEmpty(playFlv1)) {
                                    playFlv1 = CameraUtil.getPlayFlvRtsp(code, channel, type);
                                    if (playFlv1.contains("无视频")) {
                                        AjaxResults1 = new AjaxResults(0, playFlv1);
                                        return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
                                    }
                                }
                                log.info("-------playFlv--------" + playFlv1);
                                CameraVos cameraVos = new CameraVos();
                                cameraVos.setCameraCode(code);
                                cameraVos.setCurrentStream(playFlv1);
                                List<CameraVos> cameraVosList = new ArrayList<>();
                                cameraVosList.add(cameraVos);
                                respHeartbeatVo.setCameraList(cameraVosList);
                                respHeartbeatVo.setIsAlarm(1);
                                twoMap.put("currentStream", playFlv1);
                                twoMap.put("cameraCode", baseCameraManagementList.get(0).getCameraCode());
                            }
                        } else {
                            preAlarmListResponse.setCameraCode("");
                            preAlarmListResponse.setCameraStream("");
                        }
                        BeanUtils.copyProperties(preAlarmList.get(i), preAlarmListResponse);
                        responseList.add(preAlarmListResponse);
                    }
                    respHeartbeatVo.setPreAlarmList(responseList);
                } else {
                    //没有报警信息的时候
                    LambdaQueryWrapper<BaseCameraManagement> base = new LambdaQueryWrapper<>();
                    BaseCameraManagementReq baseCameraManagementReq = new BaseCameraManagementReq();
                    if (heartbeatVo.getLineDir() == 1) {
                        distance = heartbeatVo.getVisualDistance() + heartbeatVo.getCurrentMile();
                        baseCameraManagementReq.setInstallMile(heartbeatVo.getCurrentMile() + 10000);
                    }
                    if (heartbeatVo.getLineDir() == 2) {
                        distance = heartbeatVo.getCurrentMile() - heartbeatVo.getVisualDistance();
                        baseCameraManagementReq.setInstallMile(heartbeatVo.getCurrentMile() - 10000);
                    }
                    baseCameraManagementReq.setDistance(distance);
                    baseCameraManagementReq.setLineDir(heartbeatVo.getLineDir());
                    baseCameraManagementReq.setRailwayCode(heartbeatVo.getRailwayCode());
                    List<BaseCameraManagement> list1 = baseCameraManagementService.cameraMangemnetList(baseCameraManagementReq);
                    if (list1.size() <= 0) {
                        AjaxResults1 = new AjaxResults(0, "前方没有摄像机", respHeartbeatVo);
                        return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
                    }

                    log.info("流程2----------------->");
                    //判断流媒体是否有流
                    String playFlv = CameraUtil.getPlayFlvRtsp(list1.get(0).getCameraCode(), list1.get(0).getChannel(), type);
                    log.info("playFlv------------>" + playFlv);
                    baseVideoTrains.setVideoMile(list1.get(0).getInstallMile());
                    long delay = System.currentTimeMillis();
                    log.info("关联距离时间: " + sdf.format(new Date(delay)));
                    long mile = delay - begin;
                    log.info("关联距离请求用时时间:" + mile + "毫秒");
                    baseVideoTrains.setDelay((int) mile);
                    if (heartbeatVo.getLineDir() == 1) {
                        baseVideoTrains.setDistance(list1.get(0).getInstallMile() - heartbeatVo.getCurrentMile());
                    } else {
                        baseVideoTrains.setDistance(heartbeatVo.getCurrentMile() - list1.get(0).getInstallMile());
                    }
                    if (baseVideoTrains.getDistance() >= 1000 && baseVideoTrains.getDistance() <= 10000) {
                        baseVideoTrains.setIsAccuracy(1);
                    } else {
                        baseVideoTrains.setIsAccuracy(2);
                    }
                    //拉两路视频
                    if (StringUtils.isEmpty(playFlv)) {
                        log.info("--------------->>已进入拉两路视频");
                        for (BaseCameraManagement baseCameraManagement : list1) {
                            List<BaseCameraManagement> baseCameraManagementList1 = cameraUtil.getBaseCameraManagementList(baseCameraManagement.getId(), heartbeatVo.getLineDir());
                            if (!ObjectUtils.isEmpty(baseCameraManagementList1)) {
                                for (BaseCameraManagement cameraManagement : baseCameraManagementList1) {
                                    String flv = CameraUtil.getPlayFlvRtsp(cameraManagement.getCameraCode(), cameraManagement.getChannel(), type);
                                    if (StringUtils.isEmpty(flv)) {
                                        String url = CameraUtil.getPlayFlvRtsp(cameraManagement.getCameraCode(), cameraManagement.getChannel(), type);
                                        if (url.contains("无视频")) {
                                            AjaxResults1 = new AjaxResults(0, url);
                                            return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
                                        }
                                    }
                                }
                            }
                            BaseCameraManagement idOne = baseCameraManagementService.getById(list1.get(0).getId());
                            BaseCameraManagement idTwo = baseCameraManagementService.getById(list1.get(1).getId());
                            if (idOne.getGrou().equals(idTwo.getGrou())) {
                                break;
                            }
                        }
                    } else {
                        log.info("-------------->>已进入拉一路路视频");
                        log.info("list1-------------->>" + list1.size());
                        for (int i = 1; i < list1.size(); i++) {
                            List<BaseCameraManagement> baseCameraManagementList1 = cameraUtil.getBaseCameraManagementList(list1.get(i).getId(), heartbeatVo.getLineDir());
                            if (!ObjectUtils.isEmpty(baseCameraManagementList1)) {
                                for (BaseCameraManagement cameraManagement : baseCameraManagementList1) {
                                    String flv = CameraUtil.getPlayFlvRtsp(cameraManagement.getCameraCode(), cameraManagement.getChannel(), type);
                                    if (StringUtils.isEmpty(flv)) {
                                        String url = CameraUtil.getPlayFlvRtsp(cameraManagement.getCameraCode(), cameraManagement.getChannel(), type);
                                        if (url.contains("无视频")) {
                                            AjaxResults1 = new AjaxResults(0, url);
                                            return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    List<BaseCameraManagement> baseCameraManagementList1 = cameraUtil.getBaseCameraManagementList(list1.get(0).getId(), heartbeatVo.getLineDir());
                    if (!ObjectUtils.isEmpty(baseCameraManagementList1)) {
                        List<CameraVos> cameraVosList = new ArrayList<>();
                        for (BaseCameraManagement baseCameraManagement : baseCameraManagementList1) {
                            CameraVos cameraVos = new CameraVos();
                            cameraVos.setCameraCode(baseCameraManagement.getCameraCode());
                            String cacheObject = redisCache.getCacheObject(baseCameraManagement.getCameraCode());
                            cameraVos.setCurrentStream(CameraUtil.getPlayFlvRtsp(baseCameraManagement.getCameraCode(), baseCameraManagement.getChannel(), type));
                            cameraVosList.add(cameraVos);
                        }
                        respHeartbeatVo.setCameraList(cameraVosList);
                    }
                    twoMap.put("currentStream", playFlv);
                    twoMap.put("cameraCode", list1.get(0).getCameraCode());
                    respHeartbeatVo.setIsAlarm(2);
                }
                //赋值--股道
                List<BaseRouteMassage> baseRouteMassageList = baseRouteMassageService.list();
                if (!ObjectUtils.isEmpty(baseRouteMassageList)) {
                    for (BaseRouteMassage baseRouteMassage : baseRouteMassageList) {
                        if (heartbeatVo.getLineDir() == 1) {
                            if (baseRouteMassage.getMileagePosition() - heartbeatVo.getCurrentMile() <= 1500 && baseRouteMassage.getMileagePosition() - heartbeatVo.getCurrentMile() >= 0) {
                                respHeartbeatVo.setRouteTrack(baseRouteMassage.getRouteStationTrack().toString());
                                respHeartbeatVo.setStationCode(baseRouteMassage.getStationCode());
                                break;
                            } else {
                                respHeartbeatVo.setRouteTrack("");
                                respHeartbeatVo.setStationCode("");
                            }
                        } else if (heartbeatVo.getLineDir() == 2) {
                            if (heartbeatVo.getCurrentMile() - baseRouteMassage.getMileagePosition() <= 1500 && heartbeatVo.getCurrentMile() - baseRouteMassage.getMileagePosition() >= 0) {
                                respHeartbeatVo.setRouteTrack(baseRouteMassage.getRouteStationTrack().toString());
                                respHeartbeatVo.setStationCode(baseRouteMassage.getStationCode());
                                break;
                            } else {
                                respHeartbeatVo.setRouteTrack("");
                                respHeartbeatVo.setStationCode("");
                            }
                        }
                    }
                } else {
                    respHeartbeatVo.setRouteTrack("");
                    respHeartbeatVo.setStationCode("");
                }
                twoMap.put("visualDistance", heartbeatVo.getVisualDistance().toString());
                String string = JSON.toJSONString(twoMap);
                baseVideoTrainsService.save(baseVideoTrains);
                heartbeatUtils.createHeartbeat(Constant.HERTBEA_KEY + heartbeatVo.getTerminalCode(), string);
                log.info("---------data---结果-------" + respHeartbeatVo);
                if (StringUtils.isNotEmpty(respHeartbeatVo.getCameraList())) {
                    AjaxResults1 = new AjaxResults(1, "ok", respHeartbeatVo);
                }
                long end = System.currentTimeMillis();
                log.info("结束心跳时间: " + sdf.format(new Date(end)));
                log.info("心跳接口请求用时时间:" + (end - begin) + "毫秒");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            } else {
                AjaxResults1 = new AjaxResults(0, "心跳机制交互失败");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
        } else {
            AjaxResults1 = new AjaxResults(2, "token验证失败");
            return JSONObject.toJSONString(AjaxResults1);
        }

    }

    /**
     * 司机忽略报警接口
     *
     * @param parameterVo
     * @param request
     * @return
     */
    @PostMapping("/api/terminal/ignore")
    public String terminalIgnore(@RequestBody ParameterVo parameterVo, HttpServletRequest request) {
        String token = apiTokenUtils.getGeoHazardMonitorToken(request);
        Map<String, Object> map = new HashMap<>();
        log.info("token:{}", token);
        log.info("parameter:{}", parameterVo);
        AjaxResults AjaxResults1 = null;
        if (StringUtils.isNotEmpty(token)) {
            String[] split = token.split("-");
            String key = split[split.length - 1];
            if (ObjectUtils.isEmpty(parameterVo)) {
                AjaxResults1 = new AjaxResults(0, "parameterVo参数不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            String s = SM4Utils.decryptData_ECB(parameterVo.getParameter(), key);
            TerminalIgnoreVo terminalIgnoreVo = JSON.parseObject(s, TerminalIgnoreVo.class);
            if (ObjectUtils.isEmpty(terminalIgnoreVo.getTerminalCode())) {
                AjaxResults1 = new AjaxResults(0, "车载终端编码不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            if (ObjectUtils.isEmpty(terminalIgnoreVo.getAlarmId())) {
                AjaxResults1 = new AjaxResults(0, "报警唯一UUID不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            map.put("terminalCode", terminalIgnoreVo.getTerminalCode());
            map.put("alarmId", terminalIgnoreVo.getAlarmId());
            LambdaQueryWrapper<MsgAlarm> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(MsgAlarm::getAlarmId, terminalIgnoreVo.getAlarmId());
            MsgAlarm msgAlarm = msgAlarmService.getOne(wrapper);
            if (ObjectUtils.isEmpty(msgAlarm)) {
                map.put("isIgnore", 1);
                AjaxResults1 = new AjaxResults(0, "失败", map);
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            TerminalIgnoreAlarm terminalIgnoreAlarm = new TerminalIgnoreAlarm();
            terminalIgnoreAlarm.setAlarmId(terminalIgnoreVo.getAlarmId());
            terminalIgnoreAlarm.setTerminalCode(terminalIgnoreVo.getTerminalCode());
            terminalIgnoreAlarm.setIgnoreTime(new Date());
            terminalIgnoreAlarm.setCreateBy(terminalIgnoreVo.getTerminalCode());
            terminalIgnoreAlarm.setUpdateBy(terminalIgnoreVo.getTerminalCode());
            boolean save = terminalIgnoreAlarmService.save(terminalIgnoreAlarm);
            if (save) {
                ignoreUtils.createIgnore("HL" + terminalIgnoreAlarm.getTerminalCode(), terminalIgnoreAlarm.getAlarmId());
                map.put("isIgnore", 2);
                AjaxResults1 = new AjaxResults(1, "ok", map);
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            } else {
                map.put("isIgnore", 3);
                AjaxResults1 = new AjaxResults(0, "失败", map);
            }
            return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
        } else {
            AjaxResults1 = new AjaxResults(2, "token验证失败");
            return JSONObject.toJSONString(AjaxResults1);
        }
    }

    /**
     * 获取所有的相机列表接口定义
     *
     * @param parameterVo
     * @param request
     * @return
     */
    @PostMapping("/api/query/camera")
    public String camera(@RequestBody ParameterVo parameterVo, HttpServletRequest request) {
        String token = apiTokenUtils.getGeoHazardMonitorToken(request);
        log.info("token:{}", token);
        log.info("parameter:{}", parameterVo);
        AjaxResults AjaxResults1 = null;
        if (StringUtils.isNotEmpty(token)) {
            String[] split = token.split("-");
            String key = split[split.length - 1];
            if (ObjectUtils.isEmpty(parameterVo)) {
                AjaxResults1 = new AjaxResults(0, "parameterVo参数不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            String s = SM4Utils.decryptData_ECB(parameterVo.getParameter(), key);
            CameraVo cameraVo = JSON.parseObject(s, CameraVo.class);
            if (ObjectUtils.isEmpty(cameraVo.getTerminalCode())) {
                AjaxResults1 = new AjaxResults(0, "车载终端编码不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            LambdaQueryWrapper<BaseCameraManagement> wrapper = new LambdaQueryWrapper<>();
            if (!ObjectUtils.isEmpty(cameraVo.getLineDir())) {
                wrapper.eq(BaseCameraManagement::getRailwayCode, cameraVo.getRailwayCode())
                        .and(w1 -> w1.eq(BaseCameraManagement::getMonitoringDirection, cameraVo.getLineDir())
                                .or(w2 -> w2.eq(BaseCameraManagement::getMonitoringDirection, 3)));
                wrapper.eq(BaseCameraManagement::getEnableOrNot, 1);
                if (cameraVo.getLineDir() == 1) {
                    wrapper.orderByAsc(BaseCameraManagement::getGrou).orderByAsc(BaseCameraManagement::getSort);
                } else {
                    wrapper.orderByDesc(BaseCameraManagement::getGrou).orderByDesc(BaseCameraManagement::getSort);
                }
            } else {
                wrapper.orderByAsc(BaseCameraManagement::getGrou).orderByAsc(BaseCameraManagement::getSort);
            }
            List<BaseCameraManagement> list = baseCameraManagementService.list(wrapper);
            if (list.size() <= 0) {
                AjaxResults1 = new AjaxResults(0, "没有该线路编码或行别的相机信息");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            for (BaseCameraManagement baseCameraManagement : list) {
                LambdaQueryWrapper<BaseRailwayManagement> queryWrapper = new LambdaQueryWrapper<BaseRailwayManagement>();
                if (!ObjectUtils.isEmpty(baseCameraManagement.getRailwayCode())) {
                    queryWrapper.eq(BaseRailwayManagement::getRailwayCode, baseCameraManagement.getRailwayCode());
                }
                BaseRailwayManagement baseRailwayManagement = baseRailwayManagementService.getOne(queryWrapper);
                if (ObjectUtils.isEmpty(baseRailwayManagement)) {
                    AjaxResults1 = new AjaxResults(0, "没有该线路编码的线路信息");
                    return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
                }
                baseCameraManagement.setRailwayName(baseRailwayManagement.getRailwayName());
            }
//            list.sort(new Comparator<BaseCameraManagement>() {
//                @Override
//                public int compare(BaseCameraManagement o1, BaseCameraManagement o2) {
//                    String name1 = ChineseToPingyin.convertHanziToPinyin(o1.getRailwayName());
//                    String substring1 = name1.substring(0, 1);
//                    String name2 = ChineseToPingyin.convertHanziToPinyin(o2.getRailwayName());
//                    String substring2 = name2.substring(0, 1);
//                    int i = substring1.compareTo(substring2);
//                    if (i == 0) {
//                        return -o1.getInstallMile() - o2.getInstallMile();
//                    } else {
//                        return i;
//                    }
//                }
//            });
            List<RespCameraVo> cameraVos = new ArrayList<>();
            for (BaseCameraManagement baseCameraManagement : list) {
                RespCameraVo respCameraVo = new RespCameraVo();
                BeanUtils.copyProperties(baseCameraManagement, respCameraVo);
                cameraVos.add(respCameraVo);
            }
            AjaxResults1 = new AjaxResults(1, "ok", cameraVos);
            return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
        } else {
            AjaxResults1 = new AjaxResults(2, "token验证失败");
            return JSONObject.toJSONString(AjaxResults1);
        }
    }

    /**
     * 点播功能接口定义(直播流)
     *
     * @param parameterVo
     * @param request
     * @return
     */
    @PostMapping("/api/camera/play")
    public String cameraPlay(@RequestBody ParameterVo parameterVo, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        String token = apiTokenUtils.getGeoHazardMonitorToken(request);
        log.info("token:{}", token);
        log.info("parameter:{}", parameterVo);
        AjaxResults AjaxResults1 = null;
        if (StringUtils.isNotEmpty(token)) {
            String[] split = token.split("-");
            String key = split[split.length - 1];
            if (ObjectUtils.isEmpty(parameterVo)) {
                AjaxResults1 = new AjaxResults(0, "parameterVo参数不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            String s = SM4Utils.decryptData_ECB(parameterVo.getParameter(), key);
            CameraPlayVo cameraPlayVo = JSON.parseObject(s, CameraPlayVo.class);
            if (ObjectUtils.isEmpty(cameraPlayVo.getTerminalCode())) {
                AjaxResults1 = new AjaxResults(0, "车载终端编码不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            if (ObjectUtils.isEmpty(cameraPlayVo.getCameraCode())) {
                AjaxResults1 = new AjaxResults(0, "相机编码不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            LambdaQueryWrapper<BaseCameraManagement> lw = new LambdaQueryWrapper<BaseCameraManagement>();
            lw.eq(BaseCameraManagement::getCameraCode, cameraPlayVo.getCameraCode());
            lw.eq(BaseCameraManagement::getOnline, 2);
            lw.eq(BaseCameraManagement::getEnableOrNot, 1);
            BaseCameraManagement one = baseCameraManagementService.getOne(lw);
            if (ObjectUtils.isEmpty(one)) {
                AjaxResults1 = new AjaxResults(0, "没有该相机编码的相机或已离线");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            String playFlv = CameraUtil.getPlayFlvRtsp(one.getCameraCode(), one.getChannel(), false);
            if (playFlv.contains("无视频")) {
                AjaxResults1 = new AjaxResults(0, playFlv);
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            ArrayList<String> list3 = new ArrayList<>();
            String code = one.getCameraCode() + "/" + one.getChannel();
            list3.add(code);
            log.info("--------------cameraPlay--------------:" + list3);
            map.put("url", playFlv);
            AjaxResults1 = new AjaxResults(1, "ok", map);
            return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
        } else {
            AjaxResults1 = new AjaxResults(2, "token验证失败");
            return JSONObject.toJSONString(AjaxResults1);
        }
    }

    /**
     * 关闭点播功能接口
     *
     * @param parameterVo
     * @param request
     * @return
     */
    @PostMapping("/api/close/camera/play")
    public String closeCameraPlay(@RequestBody ParameterVo parameterVo, HttpServletRequest request) {
        String token = apiTokenUtils.getGeoHazardMonitorToken(request);
        log.info("token:{}", token);
        log.info("parameter:{}", parameterVo);
        AjaxResults AjaxResults1 = null;
        if (StringUtils.isNotEmpty(token)) {
            String[] split = token.split("-");
            String key = split[split.length - 1];
            if (ObjectUtils.isEmpty(parameterVo)) {
                AjaxResults1 = new AjaxResults(0, "parameterVo参数不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            String s = SM4Utils.decryptData_ECB(parameterVo.getParameter(), key);
            CameraPlayVo cameraPlayVo = JSON.parseObject(s, CameraPlayVo.class);
            if (ObjectUtils.isEmpty(cameraPlayVo.getCameraCode())) {
                AjaxResults1 = new AjaxResults(0, "相机编码不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            LambdaQueryWrapper<BaseCameraManagement> lw = new LambdaQueryWrapper<BaseCameraManagement>();
            lw.eq(BaseCameraManagement::getCameraCode, cameraPlayVo.getCameraCode());
            lw.eq(BaseCameraManagement::getOnline, 2);
            lw.eq(BaseCameraManagement::getEnableOrNot, 1);
            BaseCameraManagement one = baseCameraManagementService.getOne(lw);
            if (ObjectUtils.isEmpty(one)) {
                AjaxResults1 = new AjaxResults(0, "没有该相机编码的相机或已离线");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            AjaxResults1 = new AjaxResults(1, "ok");
            return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
        } else {
            AjaxResults1 = new AjaxResults(2, "token验证失败");
            return JSONObject.toJSONString(AjaxResults1);
        }
    }


    /**
     * 获取报警列表（已解除和未解除）
     *
     * @param parameterVo
     * @param request
     * @return
     */
    @PostMapping("/api/query/alarm")
    public String queryAlarm(@RequestBody ParameterVo parameterVo, HttpServletRequest request) {
        String token = apiTokenUtils.getGeoHazardMonitorToken(request);
        log.info("token:{}", token);
        log.info("parameter:{}", parameterVo);
        AjaxResults AjaxResults1 = null;
        if (StringUtils.isNotEmpty(token)) {
            String[] split = token.split("-");
            String key = split[split.length - 1];
            if (ObjectUtils.isEmpty(parameterVo)) {
                AjaxResults1 = new AjaxResults(0, "parameterVo参数不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            String s = SM4Utils.decryptData_ECB(parameterVo.getParameter(), key);
            CameraVo cameraVo = JSON.parseObject(s, CameraVo.class);
            if (ObjectUtils.isEmpty(cameraVo.getTerminalCode())) {
                AjaxResults1 = new AjaxResults(0, "车载终端编码不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            LambdaQueryWrapper<MsgAlarm> wrapper = new LambdaQueryWrapper<>();
            if (!ObjectUtils.isEmpty(cameraVo.getRailwayCode())) {
                wrapper.eq(MsgAlarm::getRailwayCode, cameraVo.getRailwayCode());
            }
            if (!ObjectUtils.isEmpty(cameraVo.getLineDir())) {
                wrapper.eq(MsgAlarm::getLineDir, cameraVo.getLineDir());
            }
            wrapper.orderByDesc(MsgAlarm::getAlarmTime);
            List<MsgAlarm> list = msgAlarmService.list(wrapper);
            if (list.size() <= 0) {
                AjaxResults1 = new AjaxResults(0, "没有该报警线路或行别的报警信息");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            QueryAlarmVo queryAlarmVo = new QueryAlarmVo();
            List<RespAlarmList> listVos = new ArrayList<>();
            for (MsgAlarm msgAlarm : list) {
                RespAlarmList alarmListVo = new RespAlarmList();
                AlarmInfoVo alarmInfoVo1 = new AlarmInfoVo();
                alarmInfoVo1.setAlarmId(msgAlarm.getAlarmId());
                alarmInfoVo1.setAlarmMile(msgAlarm.getAlarmMile());
                alarmInfoVo1.setAlarmTime(msgAlarm.getAlarmTime().getTime());
                alarmInfoVo1.setAlarmType(msgAlarm.getAlarmType());
                alarmInfoVo1.setAlarmLevel(msgAlarm.getAlarmLevel());
                alarmInfoVo1.setLineDirStr(msgAlarm.getLineDir() == 1 ? "上行" : "下行");
                alarmInfoVo1.setIsRelease(msgAlarm.getIsRelease());
                LambdaQueryWrapper<MsgAlarmExt> alarm = new LambdaQueryWrapper<>();
                alarm.eq(MsgAlarmExt::getAlarmId, msgAlarm.getAlarmId());
                List<MsgAlarmExt> list1 = msgAlarmExtService.list(alarm);
                if (list1.size() > 0) {
                    AlarmFilesVo[] vo = new AlarmFilesVo[list1.size()];
                    for (int i1 = 0; i1 < list1.size(); i1++) {
                        vo[i1] = new AlarmFilesVo();
                        vo[i1].setAlarmAttType(list1.get(i1).getAlarmAttType());
                        vo[i1].setAlarmAttPath(list1.get(i1).getAlarmAttPath());
                    }
                    //返回结果
                    alarmInfoVo1.setAlarmFiles(vo);
                }
                alarmListVo.setAlarmInfo(alarmInfoVo1);
                listVos.add(alarmListVo);
            }
            RespAlarmList[] array = listVos.toArray(new RespAlarmList[]{});
            queryAlarmVo.setAlarmList(array);
            AjaxResults1 = new AjaxResults(1, "ok", queryAlarmVo);
            return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
        } else {
            AjaxResults1 = new AjaxResults(2, "token验证失败");
            return JSONObject.toJSONString(AjaxResults1);
        }
    }

    /**
     * 获取报警回放
     *
     * @param parameterVo
     * @param request
     * @return
     */
    @PostMapping("/api/alarm/play")
    public String alarmPlay(@RequestBody ParameterVo parameterVo, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        String urls = null;
        String token = apiTokenUtils.getGeoHazardMonitorToken(request);
        log.info("token:{}", token);
        log.info("parameter:{}", parameterVo);
        AjaxResults AjaxResults1 = null;
        if (StringUtils.isNotEmpty(token)) {
            String[] split = token.split("-");
            String key = split[split.length - 1];
            if (ObjectUtils.isEmpty(parameterVo)) {
                AjaxResults1 = new AjaxResults(0, "parameterVo参数不能为空", AjaxResults1);
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            String s = SM4Utils.decryptData_ECB(parameterVo.getParameter(), key);
            TerminalIgnoreVo terminalIgnoreVo = JSON.parseObject(s, TerminalIgnoreVo.class);
            if (ObjectUtils.isEmpty(terminalIgnoreVo.getTerminalCode())) {
                AjaxResults1 = new AjaxResults(0, "车载终端编码不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            if (ObjectUtils.isEmpty(terminalIgnoreVo.getAlarmId())) {
                AjaxResults1 = new AjaxResults(0, "报警唯一UUID不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            LambdaQueryWrapper<MsgAlarm> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(MsgAlarm::getAlarmId, terminalIgnoreVo.getAlarmId());
            MsgAlarm one = msgAlarmService.getOne(wrapper);
            if (ObjectUtils.isEmpty(one)) {
                AjaxResults1 = new AjaxResults(0, "没有该报警唯一UUID的报警数据");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            } else {
                if (StringUtils.isEmpty(one.getReleasedUrl())) {
                    AjaxResults1 = new AjaxResults(0, "该报警还未生成报警回放视频");
                    return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
                }
            }
            map.put("url", one.getReleasedUrl());
            AjaxResults1 = new AjaxResults(1, "ok", map);
            return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
        } else {
            AjaxResults1 = new AjaxResults(2, "token验证失败");
            return JSONObject.toJSONString(AjaxResults1);
        }
    }


    /**
     * 天网相机心跳监测接口定义
     */
    @PostMapping("/api/skynet/heartbeat")
    public String skynetHeartbeat(@RequestBody ParameterVo parameterVo, HttpServletRequest request) {
        String token = apiTokenUtils.getGeoHazardMonitorToken(request);
        log.info("token:{}", token);
        log.info("parameter:{}", parameterVo);
        AjaxResults AjaxResults1 = null;
        if (StringUtils.isNotEmpty(token)) {
            String[] split = token.split("-");
            String key = split[split.length - 1];
            if (ObjectUtils.isEmpty(parameterVo)) {
                AjaxResults1 = new AjaxResults(0, "parameterVo参数不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            String s = SM4Utils.decryptData_ECB(parameterVo.getParameter(), key);
            SkynetHeartbeatVo skynetHeartbeatVo = JSON.parseObject(s, SkynetHeartbeatVo.class);
            if (ObjectUtils.isEmpty(skynetHeartbeatVo.getRailwayCode())) {
                AjaxResults1 = new AjaxResults(0, "线路编码不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            if (ObjectUtils.isEmpty(skynetHeartbeatVo.getLineDir())) {
                AjaxResults1 = new AjaxResults(0, "行别不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString("行别不能为空"), key);
            }
            if (skynetHeartbeatVo.getLineDir() != 1 && skynetHeartbeatVo.getLineDir() != 2) {
                AjaxResults1 = new AjaxResults(0, "行别填写错误");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            if (ObjectUtils.isEmpty(skynetHeartbeatVo.getInstallMile())) {
                AjaxResults1 = new AjaxResults(0, "安装里程位置不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            if (!skynetHeartbeatVo.getInstallMile().toString().matches(PATTERNS)) {
                AjaxResults1 = new AjaxResults(0, "里程位置填写错误,只能填写数字");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            if (ObjectUtils.isEmpty(skynetHeartbeatVo.getCameraCode())) {
                AjaxResults1 = new AjaxResults(0, "相机编码不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            SkynetHeartbeatLog skynetHeartbeatLog = new SkynetHeartbeatLog();
            skynetHeartbeatLog.setCameraCode(skynetHeartbeatVo.getCameraCode());
            skynetHeartbeatLog.setInstallMile(skynetHeartbeatVo.getInstallMile());
            skynetHeartbeatLog.setRailwayCode(skynetHeartbeatVo.getRailwayCode());
            skynetHeartbeatLog.setLineDir(skynetHeartbeatVo.getLineDir());
            if (synetHeartbeatLogMapper.insert(skynetHeartbeatLog) > 0) {
                Map<String, Object> map = new HashMap<>();
                map.put("cameraCode", skynetHeartbeatVo.getCameraCode());
                AjaxResults1 = new AjaxResults(1, "ok", map);
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            } else {
                AjaxResults1 = new AjaxResults(0, "新增失败");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
        } else {
            AjaxResults1 = new AjaxResults(2, "token验证失败");
            return JSONObject.toJSONString(AjaxResults1);
        }
    }

    /**
     * 第三方报警系统心跳监测接口定义
     */
    @PostMapping("/api/alarm/heartbeat")
    public String alarmHeartbeat(@RequestBody ParameterVo parameterVo, HttpServletRequest request) {
        String token = apiTokenUtils.getGeoHazardMonitorToken(request);
        log.info("token:{}", token);
        log.info("parameter:{}", parameterVo);
        AjaxResults AjaxResults1 = null;
        if (StringUtils.isNotEmpty(token)) {
            String[] split = token.split("-");
            String key = split[split.length - 1];
            if (ObjectUtils.isEmpty(parameterVo)) {
                AjaxResults1 = new AjaxResults(0, "parameterVo参数不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            String s = SM4Utils.decryptData_ECB(parameterVo.getParameter(), key);
            SvcAddress svcAddress = JSON.parseObject(s, SvcAddress.class);
            if (ObjectUtils.isEmpty(svcAddress.getGrantType())) {
                AjaxResults1 = new AjaxResults(0, "授权类型不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            if (ObjectUtils.isEmpty(svcAddress.getClientId())) {
                AjaxResults1 = new AjaxResults(0, "客户端编号不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            AlarmHeartbeatLog alarmHeartbeatLog = new AlarmHeartbeatLog();
            alarmHeartbeatLog.setClientId(svcAddress.getClientId());
            alarmHeartbeatLog.setGrantType(svcAddress.getGrantType());
            if (alarmHeartbeatLogMapper.insert(alarmHeartbeatLog) > 0) {
                Map<String, Object> map = new HashMap<>();
                map.put("clientId", svcAddress.getClientId());
                AjaxResults1 = new AjaxResults(1, "ok", map);
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            } else {
                AjaxResults1 = new AjaxResults(0, "新增失败");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
        } else {
            AjaxResults1 = new AjaxResults(2, "token验证失败");
            return JSONObject.toJSONString(AjaxResults1);
        }
    }


    /**
     * 车载心跳监测接口定义
     */
    @PostMapping("/api/terminal/heartbeatHeartbeat")
    public String heartbeatHeartbeat(@RequestBody ParameterVo parameterVo, HttpServletRequest request) {
        String token = apiTokenUtils.getGeoHazardMonitorToken(request);
        log.info("token:{}", token);
        log.info("parameterVo:{}", parameterVo);
        AjaxResults AjaxResults1 = null;
        if (StringUtils.isNotEmpty(token)) {
            String[] split = token.split("-");
            String key = split[split.length - 1];
            if (ObjectUtils.isEmpty(parameterVo)) {
                AjaxResults1 = new AjaxResults(0, "parameterVo参数不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            String s = SM4Utils.decryptData_ECB(parameterVo.getParameter(), key);
            BaseTerminalLog baseTerminalLog = JSON.parseObject(s, BaseTerminalLog.class);
            if (ObjectUtils.isEmpty(baseTerminalLog.getTerminalCode())) {
                AjaxResults1 = new AjaxResults(0, "终端编码不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            BaseTerminal baseTerminal1 = new BaseTerminal();
            baseTerminal1.setTerminalLatitude(baseTerminalLog.getTerminalLatitude());
            baseTerminal1.setTerminalLongitude(baseTerminalLog.getTerminalLongitude());
            baseTerminal1.setStatus(1);
            LambdaQueryWrapper<BaseTerminal> terminal = new LambdaQueryWrapper<>();
            terminal.eq(BaseTerminal::getTerminalCode, baseTerminalLog.getTerminalCode());
            boolean update = baseTerminalService.update(baseTerminal1, terminal);
            if (baseTerminalLogService.save(baseTerminalLog) && update) {
                VehiclePosition vehiclePosition = vehiclePositionService.getOne(new LambdaQueryWrapper<VehiclePosition>().eq(VehiclePosition::getVehicleCode, baseTerminalLog.getTrainNum()).orderByDesc(VehiclePosition::getCreateTime).last("limit 1"));
                // 获取当前时间的前5分钟
                List<SysDictData> frontValue = dictTypeService.selectDictDataByType("distance_time");
                Date fiveMinutesAgo = Date.from(Instant.now().minus(Long.valueOf(frontValue.get(0).getDictValue()), ChronoUnit.MINUTES));
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String formattedDate = sdf.format(fiveMinutesAgo);
                log.info("fiveMinutesAgo:{}", fiveMinutesAgo);
                VehiclePosition positionServiceOne = vehiclePositionService.getOne(new LambdaQueryWrapper<VehiclePosition>()
                        .eq(VehiclePosition::getVehicleCode, baseTerminalLog.getFrontTrainNum())
                        .eq(VehiclePosition::getLineDir, 1)
                        .ge(VehiclePosition::getCreateTime, formattedDate) // 添加条件：createTime大于当前时间前5分钟
                        .orderByDesc(VehiclePosition::getCreateTime).last("limit 1"));
                Map<String, Object> map = new HashMap<>();
                if (!ObjectUtils.isEmpty(positionServiceOne) && !ObjectUtils.isEmpty(vehiclePosition)) {
                    if ((vehiclePosition.getLineDir() == 1 && positionServiceOne.getTravelMile() >= vehiclePosition.getTravelMile()) ||
                            (vehiclePosition.getLineDir() == 2 && positionServiceOne.getTravelMile() <= vehiclePosition.getTravelMile())) {
                        int dif = vehiclePosition.getTravelMile() - positionServiceOne.getTravelMile();
                        map.put("frontVehicleDistance", Math.abs(dif));
                    } else {
                        map.put("frontVehicleDistance", "_");
                    }
                } else {
                    map.put("frontVehicleDistance", "_");
                }
                AjaxResults1 = new AjaxResults(1, "ok", map);
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            } else {
                AjaxResults1 = new AjaxResults(0, "新增失败");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
        } else {
            AjaxResults1 = new AjaxResults(2, "token验证失败");
            return JSONObject.toJSONString(AjaxResults1);
        }
    }

    /**
     * 获取机车前向摄像机视频
     */
    @PostMapping("/api/vehicle/vedio")
    public String vehicleVedio(@RequestBody ParameterVo parameterVo, HttpServletRequest request) {
        String token = apiTokenUtils.getGeoHazardMonitorToken(request);
        log.info("token:{}", token);
        log.info("parameterVo:{}", parameterVo);
        AjaxResults AjaxResults1 = null;
        if (StringUtils.isNotEmpty(token)) {
            String[] split = token.split("-");
            String key = split[split.length - 1];
            if (ObjectUtils.isEmpty(parameterVo)) {
                AjaxResults1 = new AjaxResults(0, "parameterVo参数不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            String s = SM4Utils.decryptData_ECB(parameterVo.getParameter(), key);
            VehicleVedioResponse vehicleVedioResponse = JSON.parseObject(s, VehicleVedioResponse.class);
            if (ObjectUtils.isEmpty(vehicleVedioResponse.getTerminalCode())) {
                AjaxResults1 = new AjaxResults(0, "终端编码不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            if (ObjectUtils.isEmpty(vehicleVedioResponse.getTrainNum())) {
                AjaxResults1 = new AjaxResults(0, "车号不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            BaseCameraManagement baseCameraManagement = baseCameraManagementService.getOne(new LambdaQueryWrapper<BaseCameraManagement>().eq(BaseCameraManagement::getTrainNum, vehicleVedioResponse.getTrainNum()));
            if (!ObjectUtils.isEmpty(baseCameraManagement)) {
//                CompletableFuture.runAsync(() -> {
//                    String playFlv = cameraUtil.heartbeatgetPlayFlv(baseCameraManagement.getCameraCode(), baseCameraManagement.getGraphicsCard(), true);
//                    log.info("-------playFlv--------" + playFlv);
//                    if (StringUtils.isEmpty(playFlv)) {
//                        try {
//                            cameraUtil.heartbeatgetUrl(baseCameraManagement.getCameraCode(), baseCameraManagement.getGraphicsCard(),true, httpUrl);
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                    }
//                });
                CameraVos cameraVos = new CameraVos();
                cameraVos.setCameraCode(baseCameraManagement.getCameraCode());
                cameraVos.setCurrentStream("1111");
                AjaxResults1 = new AjaxResults(1, "ok", cameraVos);
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            } else {
                AjaxResults1 = new AjaxResults(0, "未查询到改车号的相机信息");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
        } else {
            AjaxResults1 = new AjaxResults(2, "token验证失败");
            return JSONObject.toJSONString(AjaxResults1);
        }
    }


    /**
     * 预警信息接口定义
     */
    @PostMapping("/api/preAlarm")
    public String preAlarm(@RequestBody ParameterVo parameterVo, HttpServletRequest request) {
        String token = apiTokenUtils.getGeoHazardMonitorToken(request);
        log.info("token:{}", token);
        log.info("parameterVo:{}", parameterVo);
        AjaxResults AjaxResults1 = null;
        if (StringUtils.isNotEmpty(token)) {
            String[] split = token.split("-");
            String key = split[split.length - 1];
            if (ObjectUtils.isEmpty(parameterVo)) {
                AjaxResults1 = new AjaxResults(0, "parameterVo参数不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            String s = SM4Utils.decryptData_ECB(parameterVo.getParameter(), key);
            PreAlarmResponse preAlarmResponse = JSON.parseObject(s, PreAlarmResponse.class);
            if (ObjectUtils.isEmpty(preAlarmResponse.getTrainId())) {
                AjaxResults1 = new AjaxResults(0, "机车号不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            if (ObjectUtils.isEmpty(preAlarmResponse.getPreAlarmType())) {
                AjaxResults1 = new AjaxResults(0, "预警病害类型不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            if (ObjectUtils.isEmpty(preAlarmResponse.getPreAlarmNum())) {
                AjaxResults1 = new AjaxResults(0, "预警目标个数不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            if (ObjectUtils.isEmpty(preAlarmResponse.getPreAlarmTime())) {
                AjaxResults1 = new AjaxResults(0, "预警时间不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            if (!preAlarmResponse.getPreAlarmTime().toString().matches(REGEX)) {
                AjaxResults1 = new AjaxResults(0, "预警时间参数不对，正确格式为:单位毫秒（13位）");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
            if (!ObjectUtils.isEmpty(preAlarmResponse.getPreAlarmList())) {
                for (PreAlarmResponse.PreAlarmList preAlarmList : preAlarmResponse.getPreAlarmList()) {
                    if (ObjectUtils.isEmpty(preAlarmList.getContent())) {
                        AjaxResults1 = new AjaxResults(0, "预警内容不能为空");
                        return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
                    }
                    if (ObjectUtils.isEmpty(preAlarmList.getDistance())) {
                        AjaxResults1 = new AjaxResults(0, "目标点离机车的距离不能为空");
                        return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
                    }
                    if (ObjectUtils.isEmpty(preAlarmList.getLevel())) {
                        AjaxResults1 = new AjaxResults(0, "预警级别不能为空");
                        return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
                    }
                    if (ObjectUtils.isEmpty(preAlarmList.getTargetType())) {
                        AjaxResults1 = new AjaxResults(0, "预警目标点类型不能为空");
                        return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
                    }
                }
            }
            PreAlarm preAlarm = new PreAlarm();
            preAlarm.setTrainId(preAlarmResponse.getTrainId());
            preAlarm.setPreAlarmNum(preAlarmResponse.getPreAlarmNum());
            Calendar cal = Calendar.getInstance();
            cal.setTime(new Date(preAlarmResponse.getPreAlarmTime()));
            cal.set(Calendar.MILLISECOND, 0);
            cal.set(Calendar.MILLISECOND, 0);
            preAlarm.setPreAlarmTime(cal.getTime());
            preAlarm.setPreAlarmType(preAlarmResponse.getPreAlarmType());
            preAlarm.setPreAlarmList(JSON.toJSONString(preAlarmResponse.getPreAlarmList()));
            preAlarm.setCreatedTime(new Date());
            if (preAlarmService.save(preAlarm)) {
                AjaxResults1 = new AjaxResults(1, "ok");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            } else {
                AjaxResults1 = new AjaxResults(0, "新增失败");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(AjaxResults1), key);
            }
        } else {
            AjaxResults1 = new AjaxResults(2, "token验证失败");
            return JSONObject.toJSONString(AjaxResults1);
        }
    }

    @GetMapping("/test/{key}")
    public void test(@PathVariable String key) {
        String heartbeat = heartbeatUtils.getHeartbeat(key);
        Map maps2 = JSON.parseObject(heartbeat, Map.class);
        System.out.println(maps2);
    }

    @GetMapping("/testi")
    public void testi() {
        Map<String, String> map = new HashMap<>();
        map.put("age", "18");
        map.put("name", "小明");
        map.put("gender", "男");
        String string = JSON.toJSONString(map);
        heartbeatUtils.createHeartbeat("key", string);
    }

    private String objStr(HeartbeatVo heartbeatVoCH) {
        JSONObject obj = new JSONObject();
        //data
        obj.put("data", heartbeatVoCH);
        //code
        obj.put("code", 151);
        //log.info("【websocket消息】 机车地址信息:" + obj.toJSONString());
        return obj.toJSONString();
    }

//    public static void main(String[] args) {
//        JSONObject res = new JSONObject();
//        res.put("grantType", "1");
//        res.put("clientId", "1005");
//        String s = SM4Utils.encryptData_ECB(JSONObject.toJSONString(res), "4370780c9a8c43e5");
//        System.out.println(s);
//    }

    @PostMapping("/encryptionAlarm")
    public String encryptionAlarm(@RequestBody ReqMsgAlarmVo vo) {
        String s1 = JSONObject.toJSONString(vo);
        return SM4Utils.encryptData_ECB(s1, "4370780c9a8c43e5");
    }

    /**
     * 添加进路信息
     *
     * @return
     */
    @PostMapping("/api/addRouteMassage")
    public AjaxResults addRouteMassage(@RequestBody BaseRouteMassage baseRouteMassage) {
        if (!ObjectUtils.isEmpty(baseRouteMassage) && !ObjectUtils.isEmpty(baseRouteMassage.getStationCode())) {
            BaseRouteMassage one = baseRouteMassageService.getOne(new LambdaQueryWrapper<BaseRouteMassage>().eq(BaseRouteMassage::getStationCode, baseRouteMassage.getStationCode()));
            if (!ObjectUtils.isEmpty(one)) {
                return AjaxResults.error("车站编码已存在！");
            }
        }
        baseRouteMassage.setCreateTime(new Date());
        baseRouteMassage.setStationName("博野站");
        baseRouteMassage.setMileagePosition(11111);
        baseRouteMassageService.save(baseRouteMassage);
        return AjaxResults.success();
    }

    /**
     * 查询进路信息
     *
     * @return
     */
    @GetMapping("/api/getRouteMassageList")
    public List<BaseRouteMassage> getRouteMassageList() {
        List<BaseRouteMassage> list = baseRouteMassageService.list();
        for (BaseRouteMassage baseRouteMassage : list) {
            String mils = AppendUtils.stringAppend(baseRouteMassage.getMileagePosition());
            baseRouteMassage.setMileagePositionName(mils);
        }
        return list;
    }

    /**
     * 删除进路信息
     *
     * @return
     */
    @PostMapping("/api/deleteRouteMassage")
    public AjaxResults deleteRouteMassage(@RequestBody BaseRouteMassage baseRouteMassage) {
        if (!ObjectUtils.isEmpty(baseRouteMassage) && !ObjectUtils.isEmpty(baseRouteMassage.getId())) {
            baseRouteMassageService.removeById(baseRouteMassage.getId());
            return AjaxResults.success();
        } else {
            return AjaxResults.error("ID不存在");
        }
    }

    /**
     * ttt
     *
     * @return
     */
    @PostMapping("/api/ttt")
    public void ttt() {
        cameraUtil.heartbeatGetPlayFlv();
    }
}
