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

import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.module.infra.api.websocket.WebSocketSenderApi;
import cn.iocoder.yudao.module.system.api.robot.dto.FloorZoneDTO;
import cn.iocoder.yudao.module.system.api.robot.dto.RobotObstaclesStatusDTO;
import cn.iocoder.yudao.module.system.api.robot.vo.RobotUpdatePalletHeightDTO;
import cn.iocoder.yudao.module.system.constant.CommonConstant;
import cn.iocoder.yudao.module.system.constant.robot.RobotTaskChcheConstant;
import cn.iocoder.yudao.module.system.constant.webSocket.WebSocketConstant;
import cn.iocoder.yudao.module.system.controller.admin.robot.vo.RobotWarnMsgSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.robot.RobotWarnMsgDO;
import cn.iocoder.yudao.module.system.enums.robot.RobotWarnType;
import cn.iocoder.yudao.module.system.service.robot.RobotInformationService;
import cn.iocoder.yudao.module.system.service.robot.RobotWarnMsgService;
import cn.iocoder.yudao.module.system.util.redis.RedisUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@Slf4j
@RestController // 提供 RESTful API 接口，给 Feign 调用
@Validated
public class RobotObstaclesStatusApiImpl implements RobotObstaclesStatusApi{

    @Resource
    private RedisUtil redisUtil;

    @Resource
    public WebSocketSenderApi webSocketSenderApi;

    @Resource
    private RobotWarnMsgService warnMsgService;

    @Autowired
    private RobotInformationService robotInformationService;

    @Override
    public void robotObstaclesStatus(String message) {
        log.info("111111障碍物状态上报 :{}" ,message);

        RobotObstaclesStatusDTO data = JSON.parseObject(message, RobotObstaclesStatusDTO.class);
        if (!data.getObstacles()) {
            return;
        }

        String floorAreaKey = RobotTaskChcheConstant.ROBOT_FLOOR_AREA + data.getMac();
        Object floorAreaObject = redisUtil.get(floorAreaKey);
        FloorZoneDTO floorZoneDTO = JSONUtil.toBean((String) floorAreaObject, FloorZoneDTO.class);

        String robotNo = robotInformationService.getRobotNoByMac(data.getMac());

        RobotWarnMsgSaveReqVO warnMsg = new RobotWarnMsgSaveReqVO();
        warnMsg.setWarnLevel(4);
        warnMsg.setRobotNo(robotNo);
        warnMsg.setWarnType(RobotWarnType.ROBOT_WARN.getType());
        warnMsg.setWarnMsg(robotNo +" 机器人遇到障碍物");
        warnMsgService.createWarnMsg(warnMsg);

        webSocketSenderApi.sendObject(floorZoneDTO.getFloor() + CommonConstant.SYMBOL + floorZoneDTO.getArea(),
                WebSocketConstant.AGV_WARN, warnMsg.getWarnMsg());
    }
}
