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.NewVogMeasurements;
import com.centreproject.system.domain.kpi.park.SentimentAnalysis;
import com.centreproject.system.mapper.park.SentimentAnalysisMapper;
import com.centreproject.system.service.park.ISentimentAnalysisService;
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.function.Function;
import java.util.stream.Collectors;

/**
 * 用户情感分析
 * @author zhonglei.xu
 */
@Service
public class SentimentAnalysisServiceImpl extends ServiceImpl<SentimentAnalysisMapper, SentimentAnalysis>
        implements ISentimentAnalysisService {

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

    }

}
