package com.ltgk.boat.service.impl;


import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.ltgk.boat.config.websocket.WebSocketSessionMap;
import com.ltgk.boat.domain.entity.BoatAlarmInfo;
import com.ltgk.boat.domain.entity.RadarSolrEntity;
import com.ltgk.boat.domain.vo.RadarWakeVo;
import com.ltgk.boat.service.BoatAlarmInfoService;
import com.ltgk.boat.service.IThreeNoBoatWebsocketService;
import com.ltgk.common.common.SolrCommon;
import com.ltgk.common.constant.CacheConstants;
import com.ltgk.common.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.solr.core.query.Criteria;
import org.springframework.data.solr.core.query.SimpleQuery;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 疑似三无船只图层数据推送接口实现
 *
 * @author Qi ChengBin
 * @date 2025/07/04
 */
@Slf4j
@Service
public class ThreeNoBoatWebsocketServiceImpl implements IThreeNoBoatWebsocketService {
    @Resource
    private BoatAlarmInfoService boatAlarmInfoService;

    private final Map<String, WebSocketSession> threeNoBoatWebSocketSessionMap = new WebSocketSessionMap().sharedMap();

    @Override
    public void saveWebsocketSession(WebSocketSession session) {
        if (!this.threeNoBoatWebSocketSessionMap.containsKey(session.getId())) {
            // 将 session 存储起来，要不发送时，不知道给谁发
            this.threeNoBoatWebSocketSessionMap.put(session.getId(), session);
        }
        // 连接成功后直接给前端推送一次数据
        if (session.isOpen()) {
            // 组装告警数据和疑似三无船只数据用来推送给前端
            List<BoatAlarmInfo> resList = this.pushThreeNoBoatData();
            try {
                session.sendMessage(
                        new TextMessage(JSONUtil.toJsonStr(resList)));
            } catch (IOException e) {
                log.error(">>>>>>疑似三无船只图层数据 websocket 连接成功后推送数据失败！:::" + e.getMessage());
            }
        }
    }

    /**
     * 推送给websocket 疑似三无船只 及其尾迹
     *
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author Qi ChengBin
     * @date 2025/7/4
     */
    @Override
    public List<BoatAlarmInfo> pushThreeNoBoatData() {
        // 从数据库中获取疑似三无船只数据
        List<BoatAlarmInfo> threeNoBoatList = boatAlarmInfoService.lambdaQuery()
                .eq(BoatAlarmInfo::getAlarmType, "疑似三无船只")
                // 查询大于等于1分钟之前到现在的数据
                .ge(BoatAlarmInfo::getUpdateAt, DateUtil.offsetMinute(new Date(), -1))
//                .isNotNull(BoatAlarmInfo::getImgUrl)
                .list();
        // 获取雷达目标id
        List<String> targetSourceIdList = threeNoBoatList.stream()
                .map(BoatAlarmInfo::getTargetSourceId)
                .collect(Collectors.toList());

        // 使用当前时间查询轨迹数据
        String nowStr = DateUtil.formatDate(new Date());


        // 直接查询solr的轨迹数据   从solr 中查询2h内的轨迹数据
        Criteria criteria = new Criteria("targetSourceId")
                .in(targetSourceIdList)
                .and("locationTime")
                .between(DateUtils.toDate(DateUtil.offsetMinute(new Date(), -240).toString()), DateUtils.toDate(nowStr));
        SimpleQuery query = new SimpleQuery(criteria);
        query.addSort(Sort.by(Sort.Direction.DESC, "locationTime"));
        query.setRows(100000);
        Page page = SolrCommon.solrSearchByQuery(CacheConstants.radarPoint, query, RadarSolrEntity.class);

        // key 为 目标id   value 为 尾迹的数据
        List<RadarWakeVo> radarWakeVoList = new ArrayList<>();
        for (Object item : page.getContent()) {
            RadarSolrEntity pointSolrEntity = (RadarSolrEntity) item;
            RadarWakeVo radarWakeVo = new RadarWakeVo();
            radarWakeVo.setLatitude(Double.valueOf(pointSolrEntity.getLatitude()))
                    .setLongitude(Double.valueOf(pointSolrEntity.getLongitude()))
                    .setTime(pointSolrEntity.getLocationTime())
                    .setTargetSourceId(pointSolrEntity.getTargetSourceId())
            ;
            radarWakeVoList.add(radarWakeVo);
        }

        log.info(">>><<<<<<<疑似三无船只尾迹从solr 中获取的数据：{}", JSONUtil.toJsonStr(radarWakeVoList));

        // 将数据转换成Map 并且根据定位时间倒叙排列
        Map<String, List<RadarWakeVo>> radarWakeVoMap = radarWakeVoList.stream()
                .collect(Collectors.groupingBy(RadarWakeVo::getTargetSourceId));

        log.info(">>><<<<从solr 中获取的尾迹数据转换成 map：：：{}", JSONUtil.toJsonStr(radarWakeVoMap));

        threeNoBoatList.forEach(item -> {
            if (radarWakeVoMap.containsKey(item.getTargetSourceId())) {
                item.setWakeVoList(radarWakeVoMap.get(item.getTargetSourceId()));
            }
        });

        return threeNoBoatList;
    }

    // 定时推送前端告警信息
    @Scheduled(cron = "0/30 * * * * ?")
    public void sendTwinBoatDynamic() {
        // 组装告警数据和疑似三无船只数据用来推送给前端
        List<BoatAlarmInfo> resList = this.pushThreeNoBoatData();
        this.threeNoBoatWebSocketSessionMap.forEach((key, value) -> {
            if (value.isOpen()) {
                try {
                    value.sendMessage(
                            new TextMessage(JSONUtil.toJsonStr(resList)));
                } catch (IOException e) {
                    log.error(">>>>>>疑似三无图层数据及其尾迹数据 websocket 定时推送失败！:::" + e.getMessage());
                }
            }
        });
    }
}
