package cn.iocoder.yudao.module.system.api.robot.processor;

import cn.hutool.core.map.MapUtil;
import cn.iocoder.yudao.module.infra.api.websocket.WebSocketSenderApi;
import cn.iocoder.yudao.module.system.constant.webSocket.WebSocketConstant;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class RequestProcessor {
    private final ConcurrentHashMap<String, ConcurrentHashMap<String, String>> cache = new ConcurrentHashMap<>();
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    @Resource
    public WebSocketSenderApi webSocketSenderApi;

    public RequestProcessor() {
        // 每秒执行一次 - 处理并发送数据 - 避免数据丢失
        scheduler.scheduleAtFixedRate(this::processAndSend, 300, 300, TimeUnit.MILLISECONDS);
    }

    public void handleRequest(String map, String mac, String data) {
        cache.computeIfAbsent(map, k -> new ConcurrentHashMap<>()).put(mac, data);
    }


    private void processAndSend() {
        Map<String, ConcurrentHashMap<String, String>> snapshot = new ConcurrentHashMap<>(cache); // 创建快照
        cache.clear(); // 先清理缓存
        for (Map.Entry<String, ConcurrentHashMap<String, String>> entry : snapshot.entrySet()) {
            if (!MapUtil.isEmpty(entry.getValue())) {
                sendData(entry.getKey(), entry.getValue());
            }
        }
    }

    private void sendData(String map, Map<String, String> data) {
        // -- 发送给对应的websocket
//        System.out.println("key:" + map + "发送数据：" + data);
//        log.info("key:" + map + "发送数据：" + data);
        webSocketSenderApi.sendObject(map, WebSocketConstant.MAP_PUSH, data);
    }

    public void shutdown() {
        scheduler.shutdown();
    }

    @PreDestroy
    public void destroy() {
        // 在Bean销毁前关闭去啊
        shutdown();
    }
}
