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

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.centreproject.common.constant.GuestConstants;
import com.centreproject.common.constant.KeyConstants;
import com.centreproject.common.utils.DateUtils;
import com.centreproject.common.websocket.MyWebSocketHandler;
import com.centreproject.system.domain.kpi.guestExperience.KpiJourneyTouchPoint;
import com.centreproject.system.mapper.kpi.KpiJourneyTouchPointMapper;
import com.centreproject.system.service.guestExperience.IKpiJourneyTouchPointService;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


/**
 * Journey_Touch_Point kpi last 60 days
 * @author zhonglei.xu
 */
@Service
public class KpiJourneyTouchPointServiceImpl extends ServiceImpl<KpiJourneyTouchPointMapper, KpiJourneyTouchPoint>
        implements IKpiJourneyTouchPointService {

    private Logger logger = LoggerFactory.getLogger(KpiJourneyTouchPointServiceImpl.class);
    @Autowired
    private KpiJourneyTouchPointMapper mapper;

    @Autowired
    private RedisTemplate<String, List<KpiJourneyTouchPoint>> redisTemplate;
    // WebSocket消息发送器
    @Autowired
    private MyWebSocketHandler myWebSocketHandler;

    /**
     * Journey_Touch_Point last 60 days
     * 查询60天的数据
     * @param parkCode
     * @return 查询60天的数据
     */
    @Override
    public List<KpiJourneyTouchPoint> getJourneyTouchPoint(String parkCode) {
        String redisKey = KeyConstants.JOURNEY_TOUCH_POINT + DateUtils.getRiDate() +parkCode+ GuestConstants.LATEST_60_DAYS;

        // 1. 查缓存
        List<KpiJourneyTouchPoint> cached =  redisTemplate.opsForValue().get(redisKey);
        if (CollectionUtils.isNotEmpty(cached)) {
            return cached;
        }

        // 2. 根据类型处理数据
        List<KpiJourneyTouchPoint> results= mapper.getJourneyTouchPointLast60Days(parkCode);


        // 3. 写缓存（仅60天数据需要缓存）
        if (results != null ) {
            redisTemplate.opsForValue().set(redisKey, results, 1, TimeUnit.HOURS);
        }
        return results;
    }

    /**
     * Journey_Touch_Point daily
     * 查询当日的数据 并由ws推给前端
     * @return
     */
    // 模拟定时任务往websocket发送消息
    @Scheduled(fixedRate = 30000) // 每30秒执行一次
    public void fetchAndPushData() {
        try {
            // 1. 从数仓获取最新数据（示例）
            List<KpiJourneyTouchPoint> results = mapper.getJourneyTouchPointDaily();

            if(CollectionUtils.isNotEmpty(results)) {

                Map<String, List<KpiJourneyTouchPoint>> map = results.stream().collect(Collectors.groupingBy(KpiJourneyTouchPoint::getParkCode));
                // 2. 转换为JSON

                // 3. 按园区分组推送
                map.forEach((parkCode, parkData) -> {
                    // 构建每个园区的独立消息
                    Map<String, Object> message = new HashMap<>();
                    message.put("module", KeyConstants.JOURNEY_TOUCH_POINT+parkCode);
                    message.put("data", parkData);
                    message.put("timestamp", System.currentTimeMillis());
                    // 转换为JSON并推送
                    String jsonData = JSON.toJSONString(message);
                    myWebSocketHandler.broadcast(jsonData);
                    logger.info("模块{}园区[{}]数据推送成功，项目数量: {}",KeyConstants.JOURNEY_TOUCH_POINT, parkCode, parkData.size());
                });
            }
        } catch (Exception e) {
            logger.error("数据获取或推送异常", e);
        }
    }
}