package cn.iocoder.yudao.module.system.schedul;


import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.module.infra.api.websocket.WebSocketSenderApi;
import cn.iocoder.yudao.module.system.constant.CommonConstant;
import cn.iocoder.yudao.module.system.constant.area.FloorAreaConstant;
import cn.iocoder.yudao.module.system.constant.webSocket.WebSocketConstant;
import cn.iocoder.yudao.module.system.dal.dataobject.positionmap.PositionMapDO;
import cn.iocoder.yudao.module.system.service.positionmap.PositionMapService;
import cn.iocoder.yudao.module.system.util.redis.RedisUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@EnableScheduling
@Component
@Slf4j
public class RcsMapScheduled {

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private PositionMapService positionMapService;

    @Resource
    public WebSocketSenderApi webSocketSenderApi;

    private static final ExecutorService FIXED_THREAD_POOL = Executors.newFixedThreadPool(10);

    // 这个方法将每200毫秒执行一次
    @Scheduled(fixedDelay = 150, timeUnit = TimeUnit.MILLISECONDS)
    public void executeTask() {
        FIXED_THREAD_POOL.execute(this::sendRobotInformationToRcsMap);
    }

    private void sendRobotInformationToRcsMap() {

        TenantContextHolder.setTenantId(1L);
        Object o = redisUtil.get(FloorAreaConstant.FLOOR_AREA_ALL);

        List<PositionMapDO> allMap = null;
        if (ObjectUtil.isEmpty(o)) {
            allMap = positionMapService.getAllMap();
            if (ObjectUtil.isEmpty(allMap)) {
                return;
            }
            redisUtil.set(FloorAreaConstant.FLOOR_AREA_ALL, JSON.toJSONString(allMap),600);
        }else {
            allMap = JSON.parseArray(String.valueOf(o), PositionMapDO.class);
        }

        for (PositionMapDO positionMap : allMap) {
            String floorArea = positionMap.getFloor() + CommonConstant.SYMBOL + positionMap.getArea();
            String key = FloorAreaConstant.FLOOR_AREA_ROBOT + floorArea;
            Map<Object, Object> data = redisUtil.hmget(key);
            if (ObjectUtil.isEmpty(data)) {
                continue;
            }
            webSocketSenderApi.sendObject(floorArea, WebSocketConstant.MAP_PUSH, data);
        }
    }
}
