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.KpiHotel;
import com.centreproject.system.domain.kpi.park.SentimentAnalysis;
import com.centreproject.system.mapper.park.KpiHotelMapper;
import com.centreproject.system.service.park.IKpiHotelService;
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 KpiHotelServiceImpl extends ServiceImpl<KpiHotelMapper, KpiHotel>
        implements IKpiHotelService {

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

    }

}
