package com.ozs.web.controller.sdk;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ozs.common.core.domain.AjaxResult;
import com.ozs.common.core.domain.entity.SysUser;
import com.ozs.common.core.redis.RedisCache;
import com.ozs.common.exception.base.BaseException;
import com.ozs.common.utils.ApiTokenUtils;
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.entity.BaseCameraManagement;
import com.ozs.entity.BaseDeviceDynamicManagement;
import com.ozs.entity.BaseRailwayManagement;
import com.ozs.entity.BaseTerminal;
import com.ozs.entity.BaseUser;
import com.ozs.entity.BaseVehicleTerminal;
import com.ozs.entity.CameraTree;
import com.ozs.entity.MsgAlarm;
import com.ozs.entity.MsgAlarmExt;
import com.ozs.entity.MsgAlarmFrequency;
import com.ozs.entity.SvcAddress;
import com.ozs.entity.TerminalIgnoreAlarm;
import com.ozs.entity.VehiclePosition;
import com.ozs.entity.vo.AlarmFilesVo;
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.Files;
import com.ozs.entity.vo.HeartbeatVo;
import com.ozs.entity.vo.MsgAlarmResp;
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.RespMsgAlarmVo;
import com.ozs.entity.vo.TerminalIgnoreVo;
import com.ozs.framework.config.ServerConfig;
import com.ozs.service.BaseCameraManagementService;
import com.ozs.service.BaseDeviceDynamicManagementService;
import com.ozs.service.BaseRailwayManagementService;
import com.ozs.service.BaseTerminalService;
import com.ozs.service.BaseUserService;
import com.ozs.service.BaseVehicleTerminalService;
import com.ozs.service.MsgAlarmExtService;
import com.ozs.service.MsgAlarmFrequencyService;
import com.ozs.service.MsgAlarmService;
import com.ozs.service.SvcAddressService;
import com.ozs.service.TerminalIgnoreAlarmService;
import com.ozs.service.VehiclePositionService;
import com.ozs.system.domain.SysUserOnline;
import com.ozs.system.mapper.SysUserMapper;
import com.ozs.web.controller.monitor.SysUserOnlineController;
import com.ozs.web.controller.websocket.WebSocketServer;
import com.ozs.web.core.util.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.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 1. 获取身份认证控制层
 *
 * @author Administrator
 */
@RestController
@Slf4j
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]*$";
    @Resource
    private ApiTokenUtils apiTokenUtils;
    @Autowired
    WebSocketServer webSocketServer;
    @Autowired
    MsgAlarmService msgAlarmService;
    @Autowired
    MsgAlarmFrequencyService msgAlarmFrequencyService;
    @Autowired
    SvcAddressService svcAddressService;
    @Autowired
    BaseCameraManagementService baseCameraManagementService;
    @Autowired
    SysUserOnlineController sysUserOnlineController;
    //    @Value("${sdk.publish}")
//    private String sdkUrl;
    @Autowired
    private BaseUserService baseUserService;
    @Autowired
    private MsgAlarmExtService msgAlarmExtService;
    @Autowired
    private BaseTerminalService baseTerminalService;
    @Autowired
    private VehiclePositionService vehiclePositionService;
    @Autowired
    private HeartbeatUtils heartbeatUtils;
    @Autowired
    private TerminalIgnoreAlarmService terminalIgnoreAlarmService;
    @Autowired
    private IgnoreUtils ignoreUtils;
    @Autowired
    private BaseRailwayManagementService baseRailwayManagementService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private BaseVehicleTerminalService baseVehicleTerminalService;
    @Resource
    private SysUserMapper sysUserMapper;

    /**
     * 获取web访问令牌
     *
     * @return
     */
    @PostMapping("/api/token")
    public String getWebToken(@RequestBody SvcAddress svcAddress) {
        // 生成令牌
        JSONObject jsonObject = new JSONObject();
        LambdaQueryWrapper<SvcAddress> lw = new LambdaQueryWrapper<SvcAddress>();
        if (!ObjectUtils.isEmpty(svcAddress.getClientId())) {
            lw.eq(SvcAddress::getClientId, svcAddress.getClientId());
        } else {
            jsonObject.put("resultCode", 0);
            jsonObject.put("message", "失败");
            jsonObject.put("data", "客户端编号不能为空");
            return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
        }
        if (!ObjectUtils.isEmpty(svcAddress.getGrantType())) {
            if (!svcAddress.getGrantType().toString().matches(PATTERNS)) {
                jsonObject.put("resultCode", 0);
                jsonObject.put("message", "失败");
                jsonObject.put("data", "授权类型填写错误");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
            }
        } else {
            jsonObject.put("resultCode", 0);
            jsonObject.put("message", "失败");
            jsonObject.put("data", "授权类型不能为空");
            return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
        }
        SvcAddress serviceOne = svcAddressService.getOne(lw);
        if (!ObjectUtils.isEmpty(serviceOne)) {
            String clientSecret = SM4Utils.decryptData_ECB(serviceOne.getClientSecret(), "4370780c9a8c43e5");
            if (clientSecret.equals(svcAddress.getClientSecret())) {
                ArrayList<String> objects = apiTokenUtils.createGeoHazardMonitorToken(svcAddress.getGrantType().toString(), svcAddress.getClientId(), svcAddress.getClientSecret());
                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("令牌类型");
                    jsonObject.put("resultCode", 1);
                    jsonObject.put("message", "ok");
                    jsonObject.put("data", respGeoHazardMonitorVo);
                    return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
                } else {
                    jsonObject.put("resultCode", 0);
                    jsonObject.put("message", "失败");
                    jsonObject.put("data", "生成token失败");
                    return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
                }
            } else {
                jsonObject.put("resultCode", 0);
                jsonObject.put("message", "失败");
                jsonObject.put("data", "客户端密钥错误");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
            }
        } else {
            jsonObject.put("resultCode", 0);
            jsonObject.put("message", "失败");
            jsonObject.put("data", "参数验证失败");
            return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
        }
    }

    /**
     * 报警信息数据传输
     */
    @PostMapping("/api/alarm")
    @Transactional
    public String alarm(@RequestBody ParameterVo parameterVo, HttpServletRequest request) {
        String token = apiTokenUtils.getGeoHazardMonitorToken(request);
        log.info("token:{}", token);
        log.info("parameter:{}", parameterVo);
        JSONObject jsonObject = new JSONObject();
        if (StringUtils.isNotEmpty(token)) {
            String s = SM4Utils.decryptData_ECB(parameterVo.getParameter(), "4370780c9a8c43e5");
            ReqMsgAlarmVo reqMsgAlarmVo = JSON.parseObject(s, ReqMsgAlarmVo.class);
            if (!ObjectUtils.isEmpty(reqMsgAlarmVo.getAlarmAttr())) {
                if (!reqMsgAlarmVo.getAlarmAttr().matches(PATTERN)) {
                    jsonObject.put("resultCode", 0);
                    jsonObject.put("message", "失败");
                    jsonObject.put("data", "你填写的报警病害属性不符合规则!!!");
                    return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
                }
            }
            if (!reqMsgAlarmVo.getAlarmMile().toString().matches(PATTERNS)) {
                jsonObject.put("resultCode", 0);
                jsonObject.put("message", "失败");
                jsonObject.put("data", "报警里程位置填写错误");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
            }
            if (reqMsgAlarmVo.getLineDir() != 1 && reqMsgAlarmVo.getLineDir() != 2) {
                jsonObject.put("resultCode", 0);
                jsonObject.put("message", "失败");
                jsonObject.put("data", "行别填写错误");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
            }
            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)) {
                jsonObject.put("resultCode", 0);
                jsonObject.put("message", "失败");
                jsonObject.put("data", "填写的报警线路编码不存在");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
            }
            if (ObjectUtils.isEmpty(reqMsgAlarmVo.getAlarmId())) {
                jsonObject.put("resultCode", 0);
                jsonObject.put("message", "失败");
                jsonObject.put("data", "报警的唯一标识不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
            }
            if (ObjectUtils.isEmpty(reqMsgAlarmVo.getAlarmTime())) {
                jsonObject.put("resultCode", 0);
                jsonObject.put("message", "失败");
                jsonObject.put("data", "报警时间不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
            }
            if (reqMsgAlarmVo.getAlarmType() < 1 || reqMsgAlarmVo.getAlarmType() > 3) {
                jsonObject.put("resultCode", 0);
                jsonObject.put("message", "失败");
                jsonObject.put("data", "报警病害类型填写错误");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
            }
            if (!reqMsgAlarmVo.getAlarmLevel().toString().matches(PATTERNS)) {
                jsonObject.put("resultCode", 0);
                jsonObject.put("message", "失败");
                jsonObject.put("data", "报警级别填写错误");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
            }
            if (reqMsgAlarmVo.getAlarmTime().toString().length() == 10) {
                reqMsgAlarmVo.setAlarmTime(reqMsgAlarmVo.getAlarmTime() * 1000);
            }
            log.info("reqMsgAlarmVo:{}", reqMsgAlarmVo);

            RespMsgAlarmVo respMsgAlarmVo = new RespMsgAlarmVo();
            LambdaQueryWrapper<BaseCameraManagement> wrapper = new LambdaQueryWrapper<BaseCameraManagement>();
            if (!ObjectUtils.isEmpty(reqMsgAlarmVo.getAlarmMile())) {
                wrapper.ge(BaseCameraManagement::getBeginMile, reqMsgAlarmVo.getAlarmMile());
                wrapper.le(BaseCameraManagement::getEndMile, reqMsgAlarmVo.getAlarmMile());
            }
            List<BaseCameraManagement> baseCameraManagementList = baseCameraManagementService.list(wrapper);
            log.info("baseCameraManagement:{}", baseCameraManagementList);
            if (baseCameraManagementList.size() <= 0) {
                jsonObject.put("resultCode", 0);
                jsonObject.put("message", "失败");
                jsonObject.put("data", "报警里程位置没有可用的相机!!!");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
            }
            LambdaQueryWrapper<MsgAlarm> lw = new LambdaQueryWrapper<MsgAlarm>();
            if (!ObjectUtils.isEmpty(reqMsgAlarmVo.getAlarmId())) {
                lw.eq(MsgAlarm::getAlarmId, reqMsgAlarmVo.getAlarmId());
            }
            MsgAlarm alarm = msgAlarmService.getOne(lw);
            if (ObjectUtils.isEmpty(alarm)) {
                jsonObject.put("resultCode", 0);
                jsonObject.put("message", "失败");
                jsonObject.put("data", "没有该报警唯一标识的报警信息");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
            }
            log.info("alarm:{}", alarm);
            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());
                msgAlarmService.save(msgAlarm);
                Files[] files1 = reqMsgAlarmVo.getFiles();
                if (files1.length > 0) {
                    for (int i = 0; i < files1.length; i++) {
                        if (ObjectUtils.isEmpty(files1[i].fileUrl)) {
                            jsonObject.put("resultCode", 0);
                            jsonObject.put("message", "失败");
                            jsonObject.put("data", "上传文件地址不能为空");
                            return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
                        }
                        if (files1[i].fileType < 1 || files1[i].fileType > 3) {
                            jsonObject.put("resultCode", 0);
                            jsonObject.put("message", "失败");
                            jsonObject.put("data", "文件类型填写错误");
                            return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
                        }
                        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);
                for (BaseCameraManagement baseCameraManagement : baseCameraManagementList) {
                    String invite = CameraUtil.invite(baseCameraManagement.getCameraCode(), baseCameraManagement.getChannel());
                    if ("304".equals(invite) || "200".equals(invite)) {
                        String start = HttpUtils.sendGet(CameraUtil.startRecording(baseCameraManagement.getCameraCode(), baseCameraManagement.getChannel()));
                        log.info("startRecording------------" + start);
                        if (start.startsWith(baseCameraManagement.getCameraCode() + "/" + baseCameraManagement.getChannel())) {
                            baseCameraManagement.setTaskId(start);
                            baseCameraManagement.setUpdateBy(admin.getUserId());
                        } else {
                            jsonObject.put("resultCode", 0);
                            jsonObject.put("message", "失败");
                            jsonObject.put("data", "视频录制失败:请确认流是否存在!!!");
                            return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
                        }
                        if (!baseCameraManagementService.updateById(baseCameraManagement)) {
                            jsonObject.put("resultCode", 0);
                            jsonObject.put("message", "失败");
                            jsonObject.put("data", "开启录制视频失败!!!");
                            return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
                        }
                    } else {
                        jsonObject.put("resultCode", 0);
                        jsonObject.put("message", "失败");
                        jsonObject.put("data", "视频邀约失败,视频中心没有该相机编码或通道编码的摄像头!!!");
                        return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
                    }
                }

            } 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);
            }
//            try {
//                MsgAlarm alarms = msgAlarmService.getOne(lw);
//                log.info("sdkUrl：{}", sdkUrl);
//                log.info("alarmJSON ：{}", JSON.toJSONString(alarms));
////                String result = HttpClientUtil.postJson(sdkUrl, JSON.toJSONString(alarms));
////                log.info("result：{}", result);
//            } catch (Exception e) {
//                log.info(e.getMessage());
//                e.printStackTrace();
//                jsonObject.put("resultCode", 0);
//                jsonObject.put("message", "失败");
//                jsonObject.put("data", "消息推送失败");
//                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
//            }
            jsonObject.put("resultCode", 1);
            jsonObject.put("message", "ok");
            jsonObject.put("data", null);
            return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
        } else {
            jsonObject.put("resultCode", 2);
            jsonObject.put("message", "失败");
            jsonObject.put("data", "token验证失败");
            return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
        }
    }

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

    /**
     * 车载心跳机制交互
     *
     * @param parameterVo
     * @param request
     * @return
     */
    @PostMapping("/api/terminal/heartbeat")
    @Transactional
    public String heartbeat(@RequestBody ParameterVo parameterVo, HttpServletRequest request) {
        Map<String, Object> twoMap = new HashMap<>();
        int distance = 0;
        RespHeartbeatVo respHeartbeatVo = new RespHeartbeatVo();
        String token = apiTokenUtils.getGeoHazardMonitorToken(request);
        log.info("token:{}", token);
        log.info("parameter:{}", parameterVo);
        JSONObject jsonObject = new JSONObject();
        if (StringUtils.isNotEmpty(token)) {
            String s = SM4Utils.decryptData_ECB(parameterVo.getParameter(), "4370780c9a8c43e5");
            HeartbeatVo heartbeatVo = JSON.parseObject(s, HeartbeatVo.class);
            if (ObjectUtils.isEmpty(heartbeatVo.getTerminalCode())) {
                jsonObject.put("resultCode", 0);
                jsonObject.put("message", "失败");
                jsonObject.put("data", "车载终端编码不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
            }
            if (!heartbeatVo.getCurrentMile().toString().matches(PATTERNS)) {
                jsonObject.put("resultCode", 0);
                jsonObject.put("message", "失败");
                jsonObject.put("data", "当前里程位置填写错误");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
            }
            if (ObjectUtils.isEmpty(heartbeatVo.getLatitude())) {
                jsonObject.put("resultCode", 0);
                jsonObject.put("message", "失败");
                jsonObject.put("data", "当前所在纬度不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
            }
            if (ObjectUtils.isEmpty(heartbeatVo.getLongitude())) {
                jsonObject.put("resultCode", 0);
                jsonObject.put("message", "失败");
                jsonObject.put("data", "当前所在经度不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
            }
            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)) {
                jsonObject.put("resultCode", 0);
                jsonObject.put("message", "失败");
                jsonObject.put("data", "填写的线路编码不存在");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
            }
            if (heartbeatVo.getLineDir() != 1 && heartbeatVo.getLineDir() != 2) {
                jsonObject.put("resultCode", 0);
                jsonObject.put("message", "失败");
                jsonObject.put("data", "行别填写错误");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
            }
            if (!heartbeatVo.getVisualDistance().toString().matches(PATTERNS)) {
                jsonObject.put("resultCode", 0);
                jsonObject.put("message", "失败");
                jsonObject.put("data", "司机目视距离填写错误");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
            }
            if (heartbeatVo.getSignalStrength() != 1 && heartbeatVo.getSignalStrength() != 2) {
                jsonObject.put("resultCode", 0);
                jsonObject.put("message", "失败");
                jsonObject.put("data", "信号强度填写错误");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
            }
            VehiclePosition vehiclePosition = new VehiclePosition();
            BeanUtils.copyProperties(heartbeatVo, vehiclePosition);
            LambdaQueryWrapper<BaseTerminal> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(BaseTerminal::getTerminalCode, vehiclePosition.getTerminalCode());
            BaseTerminal baseTerminal = baseTerminalService.getOne(wrapper);
            if (ObjectUtils.isEmpty(baseTerminal)) {
                jsonObject.put("resultCode", 0);
                jsonObject.put("message", "失败");
                jsonObject.put("data", "关联表中没有改终端编码的信息");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
            }
            vehiclePosition.setTravelMile(heartbeatVo.getCurrentMile());
            vehiclePosition.setVehicleCode(baseTerminal.getVehicleCode());
            vehiclePosition.setTerminalLatitude(heartbeatVo.getLatitude());
            vehiclePosition.setTerminalLongitude(heartbeatVo.getLongitude());
            //机车行驶表添加数据
            boolean save = vehiclePositionService.save(vehiclePosition);
            //修改车载终端经度纬度
            BaseVehicleTerminal baseVehicleTerminal = new BaseVehicleTerminal();
            baseVehicleTerminal.setTerminalLatitude(heartbeatVo.getLatitude());
            baseVehicleTerminal.setTerminalLongitude(heartbeatVo.getLongitude());
            LambdaQueryWrapper<BaseVehicleTerminal> terminal = new LambdaQueryWrapper<>();
            terminal.eq(BaseVehicleTerminal::getTerminalCode, vehiclePosition.getTerminalCode());
            boolean update = baseVehicleTerminalService.update(baseVehicleTerminal, terminal);
            //*******获取终端经度纬度，将车载终端code改为机车的code，便是机车的位置
            HeartbeatVo heartbeatVoCH = new HeartbeatVo();
            BeanUtils.copyProperties(heartbeatVo, heartbeatVoCH);
            //*******将终端关联的机车编码赋值给推送信息对象
            heartbeatVoCH.setVehicleCode(baseTerminal.getVehicleCode());
            String content = objStr(heartbeatVoCH);
            //获取在线用户
            List<SysUserOnline> rows = (List<SysUserOnline>) sysUserOnlineController.list(null, null).getRows();
            if (!ObjectUtils.isEmpty(rows)) {
                //拿到用户userNameList
                List<String> userNameList = rows.stream().map(SysUserOnline::getUserName).collect(Collectors.toList());
                LambdaQueryWrapper<SysUser> userWrapper = new LambdaQueryWrapper<>();
                userWrapper.in(SysUser::getUserName, userNameList);
                List<SysUser> sysUsers = sysUserMapper.selectList(userWrapper);
                //拿到用户userIdList
                List<Long> userIdList = sysUsers.stream().map(SysUser::getId).collect(Collectors.toList());
                for (Long userid : userIdList) {
                    //推送给在线用户
                    webSocketServer.sendOneMessage(String.valueOf(userid), content);
                }
            }

            //目视距离和里程位置
            if (save && update) {
                LambdaQueryWrapper<MsgAlarm> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.ge(MsgAlarm::getAlarmMile, heartbeatVo.getCurrentMile());
                queryWrapper.le(MsgAlarm::getAlarmMile, (heartbeatVo.getCurrentMile() + 10000));
                queryWrapper.eq(MsgAlarm::getLineDir, heartbeatVo.getLineDir());
                queryWrapper.orderByAsc(MsgAlarm::getAlarmMile);
                List<MsgAlarm> list = msgAlarmService.list(queryWrapper);
                //有报警信息的时候
                if (list.size() > 0) {
                    //获取报警里程所监控的所有相机
                    LambdaQueryWrapper<BaseCameraManagement> camera = new LambdaQueryWrapper<BaseCameraManagement>();
                    camera.ge(BaseCameraManagement::getBeginMile, list.get(0).getAlarmMile());
                    camera.le(BaseCameraManagement::getEndMile, list.get(0).getAlarmMile());
                    camera.eq(BaseCameraManagement::getLineDir, heartbeatVo.getLineDir());
                    camera.eq(BaseCameraManagement::getRailwayCode, heartbeatVo.getRailwayCode());
                    camera.orderByAsc(BaseCameraManagement::getInstallMile);
                    List<BaseCameraManagement> baseCameraManagementList = baseCameraManagementService.list(camera);
                    List<AlarmListVo> listVos = new ArrayList<>();
                    if (baseCameraManagementList.size() > 0) {
                        //获取视频点播地址
                        String playFlv = CameraUtil.getPlayFlvRtsp(baseCameraManagementList.get(0).getCameraCode(), baseCameraManagementList.get(0).getChannel(), false);
                        respHeartbeatVo.setCurrentStream(playFlv);
                        respHeartbeatVo.setIsAlarm(1);
                        respHeartbeatVo.setCameraCode(baseCameraManagementList.get(0).getCameraCode());
                        twoMap.put(respHeartbeatVo.getCameraCode(), respHeartbeatVo.getCurrentStream());
                        //alarmInfo对象
                        AlarmInfoVo alarmInfoVo = new AlarmInfoVo();
                        alarmInfoVo.setAlarmId(list.get(0).getAlarmId());
                        alarmInfoVo.setAlarmMile(list.get(0).getAlarmMile());
                        alarmInfoVo.setAlarmTime(list.get(0).getAlarmTime().getTime());
                        alarmInfoVo.setAlarmContent(list.get(0).getContent());
                        alarmInfoVo.setAlarmType(list.get(0).getAlarmType());
                        alarmInfoVo.setAlarmLevel(list.get(0).getAlarmLevel());
                        AlarmFilesVo[] files = new AlarmFilesVo[1];
                        LambdaQueryWrapper<MsgAlarmExt> ext = new LambdaQueryWrapper<>();
                        ext.eq(MsgAlarmExt::getAlarmId, list.get(0).getAlarmId());
                        MsgAlarmExt one = msgAlarmExtService.getOne(ext);
                        if (ObjectUtils.isEmpty(one)) {
                            jsonObject.put("resultCode", 0);
                            jsonObject.put("message", "失败");
                            jsonObject.put("data", "没有该报警ID的关联信息");
                            return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
                        }
                        files[0] = new AlarmFilesVo();
                        files[0].setAlarmAttType(one.getAlarmAttType());
                        files[0].setAlarmAttPath(one.getAlarmAttPath());
                        //返回结果
                        alarmInfoVo.setAlarmFiles(files);
                        respHeartbeatVo.setAlarmInfo(alarmInfoVo);
                    } else {
                        jsonObject.put("resultCode", 0);
                        jsonObject.put("message", "失败");
                        jsonObject.put("data", "报警里程无可用相机");
                        return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
                    }
                    for (int i = 0; i < list.size(); i++) {
                        //获取剩余的报警信息
                        LambdaQueryWrapper<BaseCameraManagement> ment = new LambdaQueryWrapper<BaseCameraManagement>();
                        ment.ge(BaseCameraManagement::getBeginMile, list.get(i).getAlarmMile());
                        ment.le(BaseCameraManagement::getEndMile, list.get(i).getAlarmMile());
                        ment.eq(BaseCameraManagement::getLineDir, heartbeatVo.getLineDir());
                        ment.eq(BaseCameraManagement::getRailwayCode, heartbeatVo.getRailwayCode());
                        ment.orderByAsc(BaseCameraManagement::getInstallMile);
                        if (i == 0) {
                            wrapper.last("limit 1,1000000");
                        }
                        //获取所有报警安装里程位置的相机
                        List<BaseCameraManagement> baseList = baseCameraManagementService.list(camera);
                        if (baseList.size() > 0) {
                            for (int o = 0; o < baseList.size(); o++) {
                                String flv = CameraUtil.getPlayFlvRtsp(baseList.get(o).getCameraCode(), baseList.get(o).getChannel(), false);
                                AlarmListVo alarmListVo = new AlarmListVo();
                                //alarmList对象
                                alarmListVo.setCameraStream(flv);
                                alarmListVo.setCameraCode(baseList.get(o).getCameraCode());
                                twoMap.put(alarmListVo.getCameraCode(), alarmListVo.getCameraStream());
                                //alarmInfo对象
                                AlarmInfoVo alarmInfoVo1 = new AlarmInfoVo();
                                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(0).getAlarmId());
                                List<MsgAlarmExt> list1 = msgAlarmExtService.list(alarm);
                                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);
                            }
                        } else {
                            jsonObject.put("resultCode", 0);
                            jsonObject.put("message", "失败");
                            jsonObject.put("data", "报警里程无可用相机");
                            return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
                        }
                    }
                    AlarmListVo[] array = listVos.toArray(new AlarmListVo[]{});
                    respHeartbeatVo.setAlarmList(array);
                } else {
                    //没有报警信息的时候
                    distance = heartbeatVo.getVisualDistance() + heartbeatVo.getCurrentMile();
                    LambdaQueryWrapper<BaseCameraManagement> base = new LambdaQueryWrapper<>();
                    base.gt(BaseCameraManagement::getInstallMile, distance);
                    base.eq(BaseCameraManagement::getLineDir, heartbeatVo.getLineDir());
                    base.orderByAsc(BaseCameraManagement::getInstallMile);
                    base.last("limit 4");
                    List<BaseCameraManagement> list1 = baseCameraManagementService.list(base);
                    CameraUtil.invite(list1.get(0).getCameraCode(), list1.get(0).getChannel());
                    String flv = CameraUtil.getPlayFlvRtsp(list1.get(0).getCameraCode(), list1.get(0).getChannel(), false);
                    for (BaseCameraManagement baseCameraManagement : list1) {
                        String flv1 = CameraUtil.getPlayFlvRtsp(baseCameraManagement.getCameraCode(), baseCameraManagement.getChannel(), false);
                        twoMap.put(baseCameraManagement.getCameraCode(), flv1);
                        CameraUtil.invite(baseCameraManagement.getCameraCode(), baseCameraManagement.getChannel());
                    }
                    respHeartbeatVo.setCurrentStream(flv);
                    respHeartbeatVo.setIsAlarm(2);
                    respHeartbeatVo.setCameraCode(list1.get(0).getCameraCode());
                    respHeartbeatVo.setAlarmList(null);
                    respHeartbeatVo.setAlarmInfo(null);
                }
                heartbeatUtils.createHeartbeat(heartbeatVo.getTerminalCode(), twoMap);
                jsonObject.put("resultCode", 1);
                jsonObject.put("message", "ok");
                jsonObject.put("data", respHeartbeatVo);
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
            } else {
                jsonObject.put("resultCode", 0);
                jsonObject.put("message", "失败");
                jsonObject.put("data", "心跳机制交互失败");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
            }
        } else {
            jsonObject.put("resultCode", 2);
            jsonObject.put("message", "失败");
            jsonObject.put("data", "token验证失败");
            return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
        }

    }

    /**
     * 司机忽略报警接口
     *
     * @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);
        JSONObject jsonObject = new JSONObject();
        if (StringUtils.isNotEmpty(token)) {
            String s = SM4Utils.decryptData_ECB(parameterVo.getParameter(), "4370780c9a8c43e5");
            TerminalIgnoreVo terminalIgnoreVo = JSON.parseObject(s, TerminalIgnoreVo.class);
            if (ObjectUtils.isEmpty(terminalIgnoreVo.getTerminalCode())) {
                jsonObject.put("resultCode", 0);
                jsonObject.put("message", "失败");
                jsonObject.put("data", "车载终端编码不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
            }
            if (ObjectUtils.isEmpty(terminalIgnoreVo.getAlarmId())) {
                jsonObject.put("resultCode", 0);
                jsonObject.put("message", "失败");
                jsonObject.put("data", "报警唯一UUID不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
            }
            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);
                jsonObject.put("resultCode", 0);
                jsonObject.put("message", "失败");
                jsonObject.put("data", map);
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
            }
            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);
                jsonObject.put("resultCode", 1);
                jsonObject.put("message", "ok");
                jsonObject.put("data", map);
            } else {
                map.put("isIgnore", 3);
                jsonObject.put("resultCode", 0);
                jsonObject.put("message", "失败");
                jsonObject.put("data", map);
            }
            return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
        } else {
            jsonObject.put("resultCode", 2);
            jsonObject.put("message", "失败");
            jsonObject.put("data", "token验证失败");
            return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
        }
    }

    /**
     * 获取所有的相机列表接口定义
     *
     * @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);
        JSONObject jsonObject = new JSONObject();
        if (StringUtils.isNotEmpty(token)) {
            String s = SM4Utils.decryptData_ECB(parameterVo.getParameter(), "4370780c9a8c43e5");
            CameraVo cameraVo = JSON.parseObject(s, CameraVo.class);
            if (ObjectUtils.isEmpty(cameraVo.getTerminalCode())) {
                jsonObject.put("resultCode", 0);
                jsonObject.put("message", "失败");
                jsonObject.put("data", "车载终端编码不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
            }
            LambdaQueryWrapper<BaseCameraManagement> wrapper = new LambdaQueryWrapper<>();
            if (!ObjectUtils.isEmpty(cameraVo.getRailwayCode())) {
                wrapper.eq(BaseCameraManagement::getRailwayCode, cameraVo.getRailwayCode());
            }
            if (!ObjectUtils.isEmpty(cameraVo.getLineDir())) {
                wrapper.eq(BaseCameraManagement::getLineDir, cameraVo.getLineDir());
            }
            List<BaseCameraManagement> list = baseCameraManagementService.list(wrapper);
            if (list.size() <= 0) {
                jsonObject.put("resultCode", 0);
                jsonObject.put("message", "失败");
                jsonObject.put("data", "没有该线路编码或行别的相机信息");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
            }
            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)) {
                    jsonObject.put("resultCode", 0);
                    jsonObject.put("message", "失败");
                    jsonObject.put("data", "没有该线路编码的线路信息");
                    return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
                }
                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);
                respCameraVo.setRailwayCame(baseCameraManagement.getRailwayName());
                cameraVos.add(respCameraVo);
            }

            jsonObject.put("resultCode", 1);
            jsonObject.put("message", "ok");
            jsonObject.put("data", cameraVos);
            return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
        } else {
            jsonObject.put("resultCode", 2);
            jsonObject.put("message", "失败");
            jsonObject.put("data", "token验证失败");
            return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
        }
    }

    /**
     * 点播功能接口定义(直播流)
     *
     * @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);
        JSONObject jsonObject = new JSONObject();
        if (StringUtils.isNotEmpty(token)) {
            String s = SM4Utils.decryptData_ECB(parameterVo.getParameter(), "4370780c9a8c43e5");
            CameraPlayVo cameraPlayVo = JSON.parseObject(s, CameraPlayVo.class);
            if (ObjectUtils.isEmpty(cameraPlayVo.getTerminalCode())) {
                jsonObject.put("resultCode", 0);
                jsonObject.put("message", "失败");
                jsonObject.put("data", "车载终端编码不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
            }
            if (ObjectUtils.isEmpty(cameraPlayVo.getCameraCode())) {
                jsonObject.put("resultCode", 0);
                jsonObject.put("message", "失败");
                jsonObject.put("data", "相机编码不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
            }
            LambdaQueryWrapper<BaseCameraManagement> lw = new LambdaQueryWrapper<BaseCameraManagement>();
            lw.eq(BaseCameraManagement::getCameraCode, cameraPlayVo.getCameraCode());
            BaseCameraManagement one = baseCameraManagementService.getOne(lw);
            if (ObjectUtils.isEmpty(one)) {
                jsonObject.put("resultCode", 0);
                jsonObject.put("message", "失败");
                jsonObject.put("data", "没有该相机编码的相机");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
            }
            String flv = CameraUtil.getPlayFlvRtsp(one.getCameraCode(), one.getChannel(), false);
            map.put("url", flv);
            jsonObject.put("resultCode", 1);
            jsonObject.put("message", "ok");
            jsonObject.put("data", map);
            return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
        } else {
            jsonObject.put("resultCode", 2);
            jsonObject.put("message", "失败");
            jsonObject.put("data", "token验证失败");
            return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
        }
    }


    /**
     * 获取报警列表（已解除和未解除）
     *
     * @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);
        JSONObject jsonObject = new JSONObject();
        if (StringUtils.isNotEmpty(token)) {
            String s = SM4Utils.decryptData_ECB(parameterVo.getParameter(), "4370780c9a8c43e5");
            CameraVo cameraVo = JSON.parseObject(s, CameraVo.class);
            if (ObjectUtils.isEmpty(cameraVo.getTerminalCode())) {
                jsonObject.put("resultCode", 0);
                jsonObject.put("message", "失败");
                jsonObject.put("data", "车载终端编码不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
            }
            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());
            }
            List<MsgAlarm> list = msgAlarmService.list(wrapper);
            if (list.size() <= 0) {
                jsonObject.put("resultCode", 0);
                jsonObject.put("message", "失败");
                jsonObject.put("data", "没有该报警线路或行别的报警信息");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
            }
            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());
                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);
            jsonObject.put("resultCode", 1);
            jsonObject.put("message", "ok");
            jsonObject.put("data", queryAlarmVo);
            return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
        } else {
            jsonObject.put("resultCode", 2);
            jsonObject.put("message", "失败");
            jsonObject.put("data", "token验证失败");
            return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
        }
    }

    /**
     * 获取报警回放
     *
     * @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);
        JSONObject jsonObject = new JSONObject();
        if (StringUtils.isNotEmpty(token)) {
            String s = SM4Utils.decryptData_ECB(parameterVo.getParameter(), "4370780c9a8c43e5");
            TerminalIgnoreVo terminalIgnoreVo = JSON.parseObject(s, TerminalIgnoreVo.class);
            if (ObjectUtils.isEmpty(terminalIgnoreVo.getTerminalCode())) {
                jsonObject.put("resultCode", 0);
                jsonObject.put("message", "失败");
                jsonObject.put("data", "车载终端编码不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
            }
            if (ObjectUtils.isEmpty(terminalIgnoreVo.getAlarmId())) {
                jsonObject.put("resultCode", 0);
                jsonObject.put("message", "失败");
                jsonObject.put("data", "报警唯一UUID不能为空");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
            }
            LambdaQueryWrapper<MsgAlarm> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(MsgAlarm::getAlarmId, terminalIgnoreVo.getAlarmId());
            MsgAlarm one = msgAlarmService.getOne(wrapper);
            if (ObjectUtils.isEmpty(one)) {
                jsonObject.put("resultCode", 0);
                jsonObject.put("message", "失败");
                jsonObject.put("data", "没有该报警唯一UUID的报警数据");
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
            } else {
                //获取报警里程所监控的所有相机
                LambdaQueryWrapper<BaseCameraManagement> camera = new LambdaQueryWrapper<BaseCameraManagement>();
                camera.ge(BaseCameraManagement::getBeginMile, one.getAlarmMile());
                camera.le(BaseCameraManagement::getEndMile, one.getAlarmMile());
                camera.eq(BaseCameraManagement::getLineDir, one.getLineDir());
                camera.orderByAsc(BaseCameraManagement::getInstallMile);
                List<BaseCameraManagement> baseCameraManagementList = baseCameraManagementService.list(camera);
                if (baseCameraManagementList.size() > 0) {
                    BaseCameraManagement baseCameraManagement = baseCameraManagementList.get(0);
                    Object cacheObject = redisCache.getCacheObject("STREAMING_ALARM_VIDEO:" + baseCameraManagement.getCameraCode());
                    if (ObjectUtils.isEmpty(cacheObject)) {
                        String url = null;
                        if ("1".equals(one.getIsRelease().toString())) {
                            url = CameraUtil.historyPlayListStr(baseCameraManagement.getChannel(),
                                    one.getAlarmTime(),
                                    one.getReleasedTime(),
                                    true);
                            redisCache.setCacheObject("STREAMING_ALARM_VIDEO:" + baseCameraManagement.getCameraCode(), url);
                            redisCache.expire("STREAMING_ALARM_VIDEO:" + baseCameraManagement.getCameraCode(), 365L, TimeUnit.DAYS);
                        } else {
                            url = CameraUtil.historyPlayListStr(baseCameraManagement.getChannel(),
                                    one.getAlarmTime(),
                                    new Date(),
                                    false);
                        }
                        urls = serverConfig.getUrl() + url;
                    } else {
                        urls = serverConfig.getUrl() + cacheObject;
                    }
                } else {
                    jsonObject.put("resultCode", 0);
                    jsonObject.put("message", "失败");
                    jsonObject.put("data", "没有该报警里程位置的相机");
                    return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
                }
                map.put("url", urls);
                jsonObject.put("resultCode", 1);
                jsonObject.put("message", "ok");
                jsonObject.put("data", map);
                return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
            }
        } else {
            jsonObject.put("resultCode", 2);
            jsonObject.put("message", "失败");
            jsonObject.put("data", "token验证失败");
            return SM4Utils.encryptData_ECB(JSONObject.toJSONString(jsonObject), "4370780c9a8c43e5");
        }
    }

    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("terminalCode", "001");
        res.put("currentMile", 2000);
        res.put("longitude", "200");
        res.put("latitude", "300");
        res.put("railwayCode", "JT01");
        res.put("lineDir", 1);
        res.put("visualDistance", 500);
        res.put("signalStrength", 1);
        String s = SM4Utils.encryptData_ECB(JSONObject.toJSONString(res), "4370780c9a8c43e5");
        System.out.println(s);
    }
}
