package com.centreproject.system.service.park.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.centreproject.common.constant.KeyConstants;
import com.centreproject.common.utils.DateUtils;
import com.centreproject.common.websocket.MyWebSocketHandler;
import com.centreproject.system.domain.kpi.park.MapCenter;
import com.centreproject.system.mapper.park.MapCenterMapper;
import com.centreproject.system.service.park.IMapCenterService;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zhonglei.xu
 * @description 园区中心服务实现类
 */
@Service
public class MapCenterServiceImpl extends ServiceImpl<MapCenterMapper, MapCenter>
        implements IMapCenterService {

    private final Logger logger = LoggerFactory.getLogger(SentimentAnalysisServiceImpl.class);
    @Autowired
    private MyWebSocketHandler myWebSocketHandler;

    @Scheduled(fixedRate = 30000) // 每30秒执行一次
    public void pushParkEventsToRedis() {
        // 带时区的获取当前日期
        LocalDate today = DateUtils.getNowLocalDate();
        LocalDateTime start = today.atStartOfDay();
        LocalDateTime end = today.plusDays(1).atStartOfDay();

        List<MapCenter> lists = this.baseMapper.selectList(new LambdaQueryWrapper<MapCenter>()
                .ge(MapCenter::getAnalysisDate, start)
                .lt(MapCenter::getAnalysisDate, end)
                .orderByAsc(MapCenter::getDisplayOrder)
        );
        if (CollectionUtils.isNotEmpty(lists)) {
            Map<String, List<MapCenter>> map = lists.stream().collect(Collectors.groupingBy(MapCenter::getParkCode));
            map.forEach((parkCode, mapCenter) -> {
                // 构建每个园区的独立消息
                Map<String, Object> message = new HashMap<>();
                message.put("module", KeyConstants.MAP_CENTER + parkCode);
                message.put("data", mapCenter);
                message.put("timestamp", System.currentTimeMillis());
                // 转换为JSON并推送
                String jsonData = JSON.toJSONString(message);
                myWebSocketHandler.broadcast(jsonData);
                logger.info("模块{}园区[{}]数据推送成功，数据: {}", KeyConstants.MAP_CENTER, parkCode, jsonData);
            });
        }

    }

}
