package com.ruoyi.web.controller.gas;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.ElasticConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.config.ElasticSearchClient;
import com.ruoyi.system.domain.AisShip;
import com.ruoyi.system.domain.DeviceBo;
import com.ruoyi.system.domain.IllegalInfo;
import com.ruoyi.system.domain.IllegalShipData;
import com.ruoyi.system.domain.MonitorInfo;
import com.ruoyi.system.domain.SyncPost;
import com.ruoyi.system.domain.vo.AisShipInfo;
import com.ruoyi.system.domain.vo.ShipEepReportRecInfo;
import com.ruoyi.system.service.IAisDatabase;
import com.ruoyi.system.service.IAisInfoService;
import com.ruoyi.system.service.IAisShipService;
import com.ruoyi.system.service.IHeiYanService;
import com.ruoyi.system.service.IIllegalShipDataService;
import com.ruoyi.system.service.ISo2Service;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.web.controller.tool.SMSUtil;
import com.ruoyi.web.service.IGasCommonService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

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.TreeSet;
import java.util.stream.Collectors;

/**
 * @Description: 公共提出接口
 * @Author: huangcheng
 * @Date: 2021/8/30
 * @Version V1.0
 */
@RestController
@RequestMapping("/gas/common")
@Api(tags = "公共接口")
public class GasCommonController {

    @Autowired
    private IGasCommonService gasCommonService;
    @Autowired
    private ElasticSearchClient client;
    @Autowired
    private ISo2Service so2Service;
    @Autowired
    private IAisDatabase aisDatabase;
    @Autowired
    private IHeiYanService heiYanService;
    @Autowired
    private IAisShipService aisShipService;
    @Value("${spring.profiles.active}")
    private String env;
    @Autowired
    private IAisInfoService aisInfoService;
    @Autowired
    private IIllegalShipDataService illegalShipDataService;
    @Autowired
    private ISysConfigService configService;
    @Value("${black.snapImgUrl}")
    private String blackImgUrl;
    @Autowired
    private RedisCache redisCache;

    @PreAuthorize("@ss.hasPermi('system:gas:sync')")
    @PostMapping("/sync")
    @ApiOperation("第三方表数据同步ES")
    public AjaxResult sync(@RequestBody SyncPost syncPost) {
        gasCommonService.sync(syncPost);
        return AjaxResult.success("同步中...");
    }

    @GetMapping("/illegalShipStatic")
    @ApiOperation("获取硫、黑烟超标数量统计")
    public AjaxResult illegalShipStatic() {
//        Map<String, Object> params = baseEntity.getParams();
//        if (ObjectUtil.isNotEmpty(params.get("beginTime"))) {
//            params.put("beginTime", params.get("beginTime") + " 00:00:00");
//        }
//        if (ObjectUtil.isNotEmpty(params.get("endTime"))) {
//            params.put("endTime", params.get("endTime") + " 23:59:59");
//        }
//        Map<String, Object> so2RangeCondition = new HashMap<>();
//        so2RangeCondition.put("createTime", StrUtil.concat(true, "[", Convert.toStr(params.get("beginTime")), ",", Convert.toStr(params.get("endTime")), "]"));
//        so2RangeCondition.put("peakTime", StrUtil.concat(true, "[", Convert.toStr(params.get("beginTime")), ",", Convert.toStr(params.get("endTime")), "]"));
        Map<String, Object> equalsCondition = new HashMap<>();
        equalsCondition.put("illegalStatus", 2);
        long so2Count = client.count(equalsCondition, null, ElasticConstants.SO2_ALERT, ElasticConstants.AIS_ILLEGAL_SHIP);
        equalsCondition.put("illegalStatus", 3);
        long blackCount = client.count(equalsCondition, null, ElasticConstants.HEIYAN_SHIP_RECOGNITION);
        Map<String, Object> result = new HashMap<>();
        result.put("so2Count", so2Count);
        result.put("blackCount", blackCount);
        return AjaxResult.success(result);
    }

    @GetMapping("/queryIllegalInfoList")
    @ApiOperation("获取嫌疑或违规船舶信息")
    public AjaxResult queryIllegalInfoList(@RequestParam String illegalStatus, @RequestParam(required = false, defaultValue = "20") Integer size) {
        Map<String, Object> equalsCondition = new HashMap<>();
        equalsCondition.put("illegalStatus", illegalStatus);
        List<String> orderBy = new ArrayList<>();
        orderBy.add("-createTime");
        Map<String, Object> stringObjectMap = client.searchDocument(equalsCondition,
                null,
                orderBy,
                1,
                size,
                ElasticConstants.AIS_ILLEGAL_SHIP,
                ElasticConstants.SO2_ALERT,
                ElasticConstants.HEIYAN_SHIP_RECOGNITION);

        return AjaxResult.success(Convert.toList(IllegalInfo.class, stringObjectMap.get("pageList")));
    }

    @GetMapping("/queryDeviceList")
    @ApiOperation("获取所有设备数据")
    public AjaxResult queryDeviceList(@RequestParam(required = false) String monitor) {
        if (redisCache.hasKey(CacheConstants.DEVICE_LIST_STATIC)) {
            return AjaxResult.success(redisCache.getCacheMap(CacheConstants.DEVICE_LIST_STATIC));
        }
        List<DeviceBo> njsanq = new ArrayList<>();
        List<DeviceBo> njsiq = new ArrayList<>();
        List<DeviceBo> ry = new ArrayList<>();
        List<DeviceBo> tz = new ArrayList<>();
        List<DeviceBo> jy = new ArrayList<>();
        List<DeviceBo> st = new ArrayList<>();
        Map<String, Object> data = new HashMap<>();
        List<DeviceBo> so2 = so2Service.queryDeviceList(monitor);
        List<DeviceBo> ais = aisDatabase.queryDeviceList(monitor);
        List<DeviceBo> heiyan = heiYanService.queryDeviceList(monitor);
        for (DeviceBo deviceBo : so2) {
            deviceBo.setOrgName(orgMap.get(deviceBo.getMonitorName()));
            switch (deviceBo.getMonitorName()) {
                case "南京三桥":
                    njsanq.add(deviceBo);
                    break;
                case "南京四桥":
                    njsiq.add(deviceBo);
                    break;
                case "润扬大桥":
                    ry.add(deviceBo);
                    break;
                case "泰州大桥":
                    tz.add(deviceBo);
                    break;
                case "江阴大桥":
                    jy.add(deviceBo);
                    break;
                case "苏通大桥":
                    st.add(deviceBo);
                    break;
            }
        }
        for (DeviceBo deviceBo : ais) {
            deviceBo.setOrgName(orgMap.get(deviceBo.getMonitorName()));
            switch (deviceBo.getMonitorName()) {
                case "南京三桥":
                    njsanq.add(deviceBo);
                    break;
                case "南京四桥":
                    njsiq.add(deviceBo);
                    break;
                case "润扬大桥":
                    ry.add(deviceBo);
                    break;
                case "泰州大桥":
                    tz.add(deviceBo);
                    break;
                case "江阴大桥":
                    jy.add(deviceBo);
                    break;
                case "苏通大桥":
                    st.add(deviceBo);
                    break;
            }
        }
        for (DeviceBo deviceBo : heiyan) {
            switch (deviceBo.getMonitorName()) {
                case "南京三桥":
                    njsanq.add(deviceBo);
                    break;
                case "南京四桥":
                    njsiq.add(deviceBo);
                    break;
                case "润扬大桥":
                    ry.add(deviceBo);
                    break;
                case "泰州大桥":
                    tz.add(deviceBo);
                    break;
                case "江阴大桥":
                    jy.add(deviceBo);
                    break;
                case "苏通大桥":
                    st.add(deviceBo);
                    break;
            }
        }
        data.put("南京三桥", njsanq);
        data.put("南京四桥", njsiq);
        data.put("润扬大桥", ry);
        data.put("泰州大桥", tz);
        data.put("江阴大桥", jy);
        data.put("苏通大桥", st);

        redisCache.setCacheMap(CacheConstants.DEVICE_LIST_STATIC, data);
        return AjaxResult.success(data);
    }

    @GetMapping("/queryShipByDeviceId")
    @ApiOperation("根据设备id获取设备的嫌疑或违规船舶数据")
    public AjaxResult queryShipByDeviceId(@RequestParam String deviceId, @RequestParam String illegalStatus, @RequestParam(required = false) Integer size, @RequestParam String... index) {
        Map<String, Object> equalsCondition = new HashMap<>();
        equalsCondition.put("illegalStatus", illegalStatus);
        equalsCondition.put("deviceId", deviceId);
        List<String> orderBy = new ArrayList<>();
        orderBy.add("-createTime");
        if (ObjectUtil.isEmpty(size)) {
            size = 20;
        }
        Map<String, Object> stringObjectMap = client.searchDocument(equalsCondition,
                null,
                orderBy,
                1,
                size,
                index);
        return AjaxResult.success(Convert.toList(IllegalInfo.class, stringObjectMap.get("pageList")));
    }

    @GetMapping("/queryShipList")
    @ApiOperation("获取所有船舶数据-用于地图展示船舶")
    public AjaxResult queryShipList(@RequestParam(required = false) String monitor, @RequestParam(required = false) String startTime) {
        Map<String, Object> equalsCondition = new HashMap<>();
        if (StrUtil.isNotBlank(monitor)) {
            equalsCondition.put("monitorPointName", monitor);
            equalsCondition.put("snapPos", monitor);
        }
        equalsCondition.put("mmsi", "!0");
        Map<String, Object> rangeCondition = new HashMap<>();
        if (StrUtil.isBlank(startTime)) {
            startTime = DateUtil.formatDateTime(DateUtil.offsetDay(new Date(), -1));
        }
        rangeCondition.put("createTime", StrUtil.concat(true, "[", startTime, ",", DateUtil.now(), "]"));
        List<String> orderBy = new ArrayList<>();
        orderBy.add("-createTime");
        Map<String, Object> stringObjectMap = client.searchDocument(equalsCondition,
                rangeCondition,
                orderBy,
                1,
                10000,
                ElasticConstants.AIS_ILLEGAL_SHIP,
                ElasticConstants.SO2_ALERT,
                ElasticConstants.HEIYAN_SHIP_RECOGNITION);
        List<IllegalInfo> pageList = Convert.toList(IllegalInfo.class, stringObjectMap.get("pageList"));
        // 查询船舶的实时经纬度
        Map<String, AisShip> aisShipMap = aisShipService.queryDynamicShip(1);
        for (IllegalInfo illegalInfo : pageList) {
            if (StrUtil.isNotBlank(illegalInfo.getMmsi())) {
                AisShip aisShip = aisShipMap.get(illegalInfo.getMmsi());
                if (aisShip != null) {
                    illegalInfo.setLat(aisShip.getLat());
                    illegalInfo.setLng(aisShip.getLng());
                    illegalInfo.setReceive(aisShip.getReceive());
                    illegalInfo.setHead(ObjectUtil.isEmpty(aisShip.getHead()) ? "-" : aisShip.getHead() + "");
                    illegalInfo.setSpeed(ObjectUtil.isEmpty(aisShip.getSpeed()) ? "-" : aisShip.getSpeed() + "节");
                    illegalInfo.setCourse(ObjectUtil.isEmpty(aisShip.getCourse()) ? "-" : aisShip.getCourse() + "");
                }
            }
        }
        pageList =
                pageList.stream().filter(ship -> ObjectUtil.isNotEmpty(ship.getLat())).collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getMmsi() + ";" + o.getIllegalType()))),
                        ArrayList::new));
        return AjaxResult.success(pageList);
    }

    @GetMapping("/queryShipMonitorInfo")
    @ApiOperation("获取船舶监测数据")
    public AjaxResult queryShipMonitorInfo(@RequestParam String mmsi) {
        Map<String, Object> map = new HashMap<>(4);
        List<MonitorInfo> minor = new ArrayList<>();
        // 硫的监测数据（监测点、硫含量、监测时间、so2浓度、no2浓度、co2浓度、硫碳比）
        // 查询so2系统
        Map<String, Object> equalsCondition = new HashMap<>();
        equalsCondition.put("mmsi", mmsi);
        List<String> orderBy = new ArrayList<>();
        orderBy.add("-createTime");
        Map<String, Object> monitorMap = client.searchDocument(equalsCondition,
                null,
                orderBy,
                1,
                100,
                ElasticConstants.AIS_ILLEGAL_SHIP,
                ElasticConstants.SO2_ALERT,
                ElasticConstants.HEIYAN_SHIP_RECOGNITION);
        List<MonitorInfo> pageList = Convert.toList(MonitorInfo.class, monitorMap.get("pageList"));
        // 处理数据
        for (MonitorInfo monitorInfo : pageList) {
            if (StrUtil.isBlank(monitorInfo.getMonitorPointName()) && StrUtil.isNotBlank(monitorInfo.getSnapPos())) {
                monitorInfo.setMonitorPointName(monitorInfo.getSnapPos());
            }
            if (ObjectUtil.isNotEmpty(monitorInfo.getCo2Concentration())) {
                minor.add(monitorInfo);
            }
        }
        map.put("main", pageList);
        map.put("minor", minor);
        return AjaxResult.success(map);
    }

    public final static Map<String, String> orgMap = new HashMap<String, String>() {{
        put("南京三桥", "南京海事局");
        put("南京四桥", "南京海事局");
        put("润扬大桥", "扬州海事局");
        put("泰州大桥", "泰州海事局");
        put("江阴大桥", "江阴海事局");
        put("苏通大桥", "常熟海事局");
    }};
    public final static Map<String, String> heiyanDeviceMap = new HashMap<String, String>() {{
        put("南京三桥", "1106");
        put("润扬大桥", "2104");
        put("江阴大桥", "6106");
        put("苏通大桥", "9108");
    }};

    @GetMapping("/queryData")
    @ApiOperation("查询ES数据")
    public Object queryData(@RequestParam(required = false) String id, @RequestParam(required = false) Integer size, @RequestParam(required = false) String orderKey, @RequestParam String... index) {
        if (size == null) {
            size = 200;
        }
        Map<String, Object> equalsCondition = new HashMap<>();
        if (StrUtil.isNotBlank(id)) {
            equalsCondition.put("id", id);
        }
        List<String> orderBy = new ArrayList<>();
        if (StrUtil.isNotBlank(orderKey)) {
            orderBy.add("-" + orderKey);
        }
        Map<String, Object> map = client.searchDocument(equalsCondition,
                null,
                orderBy,
                1,
                size,
                index);
        return map.get("pageList");
    }

    @DeleteMapping("/deleteIndexOneData")
    @ApiOperation("删除ES中某个数据")
    public void deleteIndexData(@RequestParam String index, @RequestParam String id) {
        client.deleteDocument(index, id);
    }

    @PostMapping("/sendSms")
    @ApiOperation("发送短信")
    public AjaxResult sendSms(@RequestBody JSONObject jsonObject) {
        String content = jsonObject.getString("content");
        String phone = jsonObject.getString("phone");
        if (StrUtil.hasBlank(content, phone)) {
            return AjaxResult.error("存在参数为空");
        }
        SMSUtil smsUtil = new SMSUtil();
        smsUtil.sendMessage(content, phone);
        return AjaxResult.success();
    }

    @SneakyThrows
    @PostMapping("/reSyncOneData")
    @ApiOperation("重新同步某一个数据")
    public void reSyncOneData(@RequestParam String index, @RequestParam String id) {
        client.deleteDocument(index, id);
        String so2ThresholdVal = configService.selectConfigByKey("so2.so2");
        String blackThresholdVal = configService.selectConfigByKey("black.rcgSoot");
        if (ElasticConstants.AIS_ILLEGAL_SHIP.equals(index)) {
            Map<String, Object> afterDataMap = aisDatabase.queryById(id);
            // 嗅探系统-违规船舶
            if ("prod".equals(env)) {
                // 查询检测点和船舶信息、船舶进出港记录
                AisShipInfo shipInfo = aisInfoService.getShipInfo("", Convert.toStr(afterDataMap.get("mmsi")), "", "");
                if (shipInfo != null) {
                    afterDataMap.put("shipName", shipInfo.getShipName());
                    afterDataMap.put("shipRegionType", shipInfo.getShipRegionType());
                }
            }
            if (ObjectUtil.isNotEmpty(afterDataMap.get("sPercent")) && NumberUtil.isGreaterOrEqual(Convert.toBigDecimal(afterDataMap.get("sPercent")), Convert.toBigDecimal(so2ThresholdVal))) {
                // 查询检测点和船舶信息、船舶进出港记录
                ShipEepReportRecInfo eepReportRecInfo = aisInfoService.getShipEepReportRecInfo(DateUtil.formatDate(DateUtil.offsetDay(new Date(), -20)), DateUtil.formatDate(DateUtil.tomorrow()), Convert.toStr(afterDataMap.get("mmsi")), "", "");
                if (eepReportRecInfo != null) {
                    afterDataMap.put("destination", eepReportRecInfo.getNextPortName());
                    afterDataMap.put("berthName", eepReportRecInfo.getBerthName());
                }
                afterDataMap.put("deviceId", afterDataMap.get("semId"));
                // 查询站点信息
                Map<String, Object> sem = client.getDocById(ElasticConstants.AIS_SEM_INSTRUMENT, Convert.toStr(afterDataMap.get("semId")), "name,category");
                if (sem != null && ObjectUtil.equal(sem.get("code"), 200)) {
                    Map<String, String> data = Convert.toMap(String.class, String.class, sem.get("data"));
                    afterDataMap.put("semName", data.get("name"));
                    afterDataMap.put("monitorPointName", data.get("category"));
                    afterDataMap.put("orgName", orgMap.get(data.get("category")));
                }

                // 嫌疑船舶
                afterDataMap.put("illegalStatus", 2);
                afterDataMap.put("uploadFlag", 0);
                // TODO 上报行政检查系统

            } else {
                afterDataMap.put("uploadFlag", 0);
                afterDataMap.put("illegalStatus", 1);
            }
            if (ObjectUtil.isNotEmpty(afterDataMap.get("mmsi"))) {
                aisInfoService.getDynamicShipInfo(Convert.toStr(afterDataMap.get("mmsi")));
            }
            afterDataMap.put("illegalType", "xiutan");
            // 保存数据
            saveIllegalData(afterDataMap, ElasticConstants.AIS_ILLEGAL_SHIP);
            client.createDocument(ElasticConstants.AIS_ILLEGAL_SHIP, Convert.toStr(afterDataMap.get("id")), afterDataMap);

        } else if (ElasticConstants.SO2_ALERT.equals(index)) {
            Map<String, Object> afterDataMap = so2Service.queryById(id);

            // 船舶记录
            if ("prod".equals(env)) {
                AisShipInfo shipInfo = aisInfoService.getShipInfo("", Convert.toStr(afterDataMap.get("mmsi")), "", "");
                if (shipInfo != null) {
                    afterDataMap.put("shipName", shipInfo.getShipName());
                    afterDataMap.put("shipRegionType", shipInfo.getShipRegionType());
                }
            }
            // 判断是否大于阈值
            if (ObjectUtil.isNotEmpty(afterDataMap.get("so2Percent")) && NumberUtil.isGreaterOrEqual(Convert.toBigDecimal(afterDataMap.get("so2Percent")), Convert.toBigDecimal(so2ThresholdVal))) {
                // 查询检测点和船舶信息、船舶进出港记录
                ShipEepReportRecInfo eepReportRecInfo = aisInfoService.getShipEepReportRecInfo(DateUtil.formatDate(DateUtil.offsetDay(new Date(), -20)), DateUtil.formatDate(DateUtil.tomorrow()), Convert.toStr(afterDataMap.get("mmsi")), "", "");
                if (eepReportRecInfo != null) {
                    afterDataMap.put("destination", eepReportRecInfo.getNextPortName());
                    afterDataMap.put("berthName", eepReportRecInfo.getBerthName());
                }

                // 嫌疑船舶
                afterDataMap.put("illegalStatus", 2);
                afterDataMap.put("uploadFlag", 0);
                // TODO 上报行政检查系统

            } else {
                afterDataMap.put("uploadFlag", 0);
                afterDataMap.put("illegalStatus", 1);
            }
            Map<String, Object> monitor = client.getDocById(ElasticConstants.SO2_MONITOR_POINT, Convert.toStr(afterDataMap.get("monitorPointId")), "name");
            if (monitor != null && ObjectUtil.equal(monitor.get("code"), 200)) {
                Map<String, String> data = Convert.toMap(String.class, String.class, monitor.get("data"));
                afterDataMap.put("monitorPointName", data.get("name"));
                afterDataMap.put("orgName", orgMap.get(data.get("name")));
            }
            if (ObjectUtil.isNotEmpty(afterDataMap.get("mmsi"))) {
                aisInfoService.getDynamicShipInfo(Convert.toStr(afterDataMap.get("mmsi")));
            }
            afterDataMap.put("illegalType", "guangpu");
            // 保存数据
            saveIllegalData(afterDataMap, ElasticConstants.SO2_ALERT);
            client.createDocument(ElasticConstants.SO2_ALERT, Convert.toStr(afterDataMap.get("id")), afterDataMap);

        } else if (ElasticConstants.HEIYAN_SHIP_RECOGNITION.equals(index)) {
            Map<String, Object> afterDataMap = heiYanService.queryById(id);

            if (ObjectUtil.isEmpty(afterDataMap.get("mmsi"))) {
                return;
            }
            // 判断数据状态
            if (ObjectUtil.isNotEmpty(afterDataMap.get("rcgSoot")) && NumberUtil.isGreaterOrEqual(Convert.toBigDecimal(afterDataMap.get("rcgSoot")),
                    Convert.toBigDecimal(blackThresholdVal))) {
                // 查询黑烟图片
                if ("prod".equals(env)) {
                    String imgUrl = HttpUtil.get(blackImgUrl + Convert.toStr(afterDataMap.get("id")));
                    JSONObject response = JSON.parseObject(imgUrl);
                    if (200 == response.getInteger("code")) {
                        List<String> newImgList = new ArrayList<>();
                        JSONArray imgUrlList = response.getJSONObject("data").getJSONArray("imgUrlList");
                        String sootImgUrl = response.getJSONObject("data").getString("sootImgUrl");
                        for (Object o : imgUrlList) {
                            // 只保存细节、全貌开头的图片
                            String s = Convert.toStr(o);
//                            if (StrUtil.containsAny(s, "全貌", "细节")) {
                            newImgList.add("http://" + s);
//                            }
                        }
                        afterDataMap.put("sootImgUrl", StrUtil.isNotBlank(sootImgUrl) ? "http://" + sootImgUrl : "");
                        afterDataMap.put("allImgUrl", newImgList);
                    }
                }
                // 查询检测点和船舶信息、船舶进出港记录
                ShipEepReportRecInfo eepReportRecInfo = aisInfoService.getShipEepReportRecInfo(DateUtil.formatDate(DateUtil.offsetDay(new Date(), -20)), DateUtil.formatDate(DateUtil.tomorrow()), Convert.toStr(afterDataMap.get("mmsi")), "", "");
                if (eepReportRecInfo != null) {
                    afterDataMap.put("destination", eepReportRecInfo.getNextPortName());
                    afterDataMap.put("berthName", eepReportRecInfo.getBerthName());
                }
                // 超过阈值后直接判定为违规船舶
                afterDataMap.put("illegalStatus", 3);
                afterDataMap.put("uploadFlag", 0);
                // TODO 上报行政检查系统

            } else {
                afterDataMap.put("uploadFlag", 0);
                afterDataMap.put("illegalStatus", 1);
            }
            if (ObjectUtil.isNotEmpty(afterDataMap.get("mmsi")) && Convert.toStr(afterDataMap.get("mmsi")).length() == 9) {
                aisInfoService.getDynamicShipInfo(Convert.toStr(afterDataMap.get("mmsi")));
            }
            afterDataMap.put("illegalType", "heiyan");
            // 查询检测点和船舶信息
            if (ObjectUtil.isNotEmpty(afterDataMap.get("mmsi")) && !"0".equals(Convert.toStr(afterDataMap.get("mmsi")))) {
                AisShipInfo shipInfo = aisInfoService.getShipInfo("", Convert.toStr(afterDataMap.get("mmsi")), "", "");
                if (shipInfo != null) {
                    afterDataMap.put("shipName", shipInfo.getShipName());
                    afterDataMap.put("shipRegionType", shipInfo.getShipRegionType());
                }
            }
            // 对于没有从ais系统拿到船名的情况下，直接取rcgShipName
            if (ObjectUtil.isEmpty(afterDataMap.get("shipName"))) {
                afterDataMap.put("shipName", afterDataMap.get("rcgShipName"));
            }
            if (ObjectUtil.isNotEmpty(afterDataMap.get("snapPos"))) {
                afterDataMap.put("orgName", orgMap.get(Convert.toStr(afterDataMap.get("snapPos"))));
                afterDataMap.put("deviceId", heiyanDeviceMap.get(Convert.toStr(afterDataMap.get("snapPos"))));
            }
            // 保存数据
            saveIllegalData(afterDataMap, ElasticConstants.HEIYAN_SHIP_RECOGNITION);
            client.createDocument(ElasticConstants.HEIYAN_SHIP_RECOGNITION, Convert.toStr(afterDataMap.get("id")), afterDataMap);
        }
    }

    private void saveIllegalData(Map<String, Object> afterDataMap, String indexName) {
        if (Convert.toInt(afterDataMap.get("illegalStatus")) != 1) {
            IllegalShipData illegalShipData = new IllegalShipData();
            BeanUtil.fillBeanWithMap(afterDataMap, illegalShipData, CopyOptions.create().setIgnoreProperties("id"));
            illegalShipData.setId(IdUtils.fastSimpleUUID());
            illegalShipData.setSystemId(Convert.toStr(afterDataMap.get("id")));
            illegalShipData.setSystemEsIndex(indexName);
            try {
                illegalShipDataService.insertIllegalShipData(illegalShipData);
            } catch (Exception ignored) {
                ignored.printStackTrace();
            }

        }
    }

}
