package com.centreproject.system.service.guestExperience.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.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.KpiTransport;
import com.centreproject.system.domain.vo.KpiTransportDetailVo;
import com.centreproject.system.domain.vo.KpiTransportVo;
import com.centreproject.system.mapper.kpi.KpiTransportMapper;
import com.centreproject.system.service.guestExperience.IKpiTransportService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
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.math.BigDecimal;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * Guest Experience KPI Transport Service Implementation
 * @author zhonglei.xu
 */
@Service
public class KpiTransportServiceImpl extends ServiceImpl<KpiTransportMapper, KpiTransport>
        implements IKpiTransportService {

    private Logger logger = LoggerFactory.getLogger(KpiTransportServiceImpl.class);
    @Autowired
    private KpiTransportMapper mapper;
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;
    // WebSocket消息发送器
    @Autowired
    private MyWebSocketHandler myWebSocketHandler;

    /**
     * get Guest Experience Transport KPI
     * @return
     */
    @Override
    public KpiTransportVo getTransport() {
        String redisKey = KeyConstants.TRANSPORT + DateUtils.getRiDate() + GuestConstants.LATEST_60_DAYS;

        // 1. 查缓存
        KpiTransportVo cached = (KpiTransportVo) redisTemplate.opsForValue().get(redisKey);
        if (cached != null) {
            return cached;
        }

        KpiTransportVo vo=mapper.getTransportByLast60Days();
        if(ObjectUtils.isNotEmpty(vo)){
            KpiTransportVo preVo = mapper.getTransportByPrevious60Days();
            vo.setOnTimeRateChange(BigDecimal.ZERO);
            if(ObjectUtils.isNotEmpty(preVo) ){
                if(vo.getOnTimeRate().compareTo(BigDecimal.ZERO)>0 && preVo.getOnTimeRate().compareTo(BigDecimal.ZERO)>0){
                    vo.setOnTimeRateChange(vo.getOnTimeRate().subtract(preVo.getOnTimeRate()));
                }
            }
            vo.setDataDate(DateUtils.getShortYearDate());
            // 计算日期范围
            List<KpiTransportDetailVo> detailVo=mapper.getTransportByLast60DaysDetail();
            vo.setPassengers(detailVo);
            redisTemplate.opsForValue().set(redisKey, vo, 1, TimeUnit.HOURS);
        }
        return vo;
    }


    /**
     * 模拟定时任务往websocket发送消息
     * transportDailyDays daily
     * detail 返回最近 7days
     */
    @Scheduled(fixedRate = 30000) // 每30秒执行一次
    public void transportDailyDays() {
        try {
            // 1. 从数仓获取最新数据（示例）
            //    取当天的数据
            LambdaQueryWrapper<KpiTransport> wrapper = new LambdaQueryWrapper<KpiTransport>().eq(KpiTransport::getDataDate, DateUtils.getDate());
            wrapper= wrapper.last("LIMIT 1");
            KpiTransport kpiTransport = this.baseMapper.selectOne(wrapper);
            if(ObjectUtils.isNotEmpty(kpiTransport)){
                KpiTransportVo vo = new KpiTransportVo();
                vo.setLineCount(kpiTransport.getLineCount());
                vo.setOnScheduleRate(kpiTransport.getOnScheduleRate());
                vo.setOnTimeRate(kpiTransport.getOnTimeRate());
                vo.setOnTimeRateChange(kpiTransport.getOnTimeRateChange());
                List<KpiTransportDetailVo> detailVo=mapper.getTransportByLast7DaysDetail();
                vo.setPassengers(detailVo);
                vo.setDataDate(DateUtils.getShortYearDate());
                // 2. 推送到WebSocket
                Map<String, Object> message = new HashMap<>();
                message.put("module", KeyConstants.TRANSPORT);
                message.put("data", vo);
                message.put("timestamp", System.currentTimeMillis());
                // 转换为JSON并推送
                String jsonData = JSON.toJSONString(message);
                myWebSocketHandler.broadcast(jsonData);
                logger.info("模块{}数据推送成功，data: {}", KeyConstants.TRANSPORT, jsonData);
            }

        } catch (Exception e) {
            logger.error("数据获取或推送异常", e);
        }
    }

}
