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


import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.module.system.config.ratelimiter.SystemRateLimiter;
import cn.iocoder.yudao.module.system.constant.CommonConstant;
import cn.iocoder.yudao.module.system.controller.admin.path.dto.GraphMatchDataDTO;
import cn.iocoder.yudao.module.system.controller.admin.positionmap.vo.PositionMapSaveReqVO;
import cn.iocoder.yudao.module.system.controller.admin.robot.vo.RobotWarnMsgSaveReqVO;
import cn.iocoder.yudao.module.system.service.path.PathPlanningService;
import cn.iocoder.yudao.module.system.service.positionmap.PositionChangePointBindingService;
import cn.iocoder.yudao.module.system.service.robot.RobotTaskService;
import cn.iocoder.yudao.module.system.service.robot.RobotWarnMsgService;
import cn.iocoder.yudao.module.system.service.tool.ToolsService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.UUID;

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

    @Resource
    private PathPlanningService pathPlanningService;

    @Resource
    private ToolsService toolsService;

    @Resource
    private RobotTaskService taskService;

    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;

    @Resource
    private RobotWarnMsgService warnMsgService;


    /**
     * 发送初始化信息给PP
     */
    @Override
    @SystemRateLimiter(time = 15, count = 1, keyArg = "pathInitData", message = "路径规划初始化数据频繁")
    public void pathInitData() {
        taskExecutor.execute(() -> {
            TenantContextHolder.setTenantId(1L);
            log.info("初始化数据发送个PP---开始");
            pathPlanningService.synchronousStart();
            //同步点位信息
            PositionMapSaveReqVO positionMapSaveReqVO = new PositionMapSaveReqVO();
            pathPlanningService.synchronousAllItem(positionMapSaveReqVO);
            //同步区域变更点的绑定信息
            pathPlanningService.sendPositionChangePointBinding();
            //同步线的信息
            pathPlanningService.synchronousPoint(positionMapSaveReqVO);
            //车辆尺寸
            pathPlanningService.robotDimensions();
            //距离、优先级、时间权重
            toolsService.sendPPsortConfig();

            log.info("初始化数据发送个PP---完成");
        });
    }

    /**
     * PP分配任务
     *
     * @param message
     */
    @Override
    public void ppDistributionTask(String message) {
        taskExecutor.execute(() -> {
            TenantContextHolder.setTenantId(1L);
            String requestId = UUID.randomUUID().toString().replace("-", "");
            MDC.put(CommonConstant.REQUEST_ID, requestId);
            try {
                taskService.assignTasks(message);
            } finally {
                MDC.clear();
            }
        });
    }

    /**
     * PP处理任务失败
     *
     * @param message
     */
    @Override
    public void ppDistributionTaskFail(String message) {
        log.info("111111路径规划上报失败的消息");
        TenantContextHolder.setTenantId(1L);
        RobotWarnMsgSaveReqVO data = JSON.parseObject(message, RobotWarnMsgSaveReqVO.class);
        warnMsgService.createWarnMsg(data);
        if (ObjectUtil.isNotEmpty(data.getWarnLevel()) && data.getWarnLevel() > 3) {
            warnMsgService.sendWarnMsgToWebsocket(message);
        }
    }

    @Override
    public void pathPlanningMove(String message) {
        log.info("111111路径规划发给车机的消息 :{}", message);
        taskExecutor.execute(() -> {
            TenantContextHolder.setTenantId(1L);
            pathPlanningService.sendPosedsToRobot(message);
        });
    }

    /**
     * 车辆即将走的点位
     *
     * @param message
     */
    @Override
    public void pathPlanningMovePose(String message) {
        TenantContextHolder.setTenantId(1L);
        pathPlanningService.pathPlanningMovePose(message);
    }

    /**
     * 仿真点位信息
     *
     * @param message
     */
    @Override
    public void simulationRobotPoseRequest(String message) {
        TenantContextHolder.setTenantId(1L);
        pathPlanningService.simulationRobotPoseRequest();
    }

    /**
     * 路网匹配实时数据
     *
     * @param message
     */
    @Override
    public void graphMatchData(String message) {
        TenantContextHolder.setTenantId(1L);
//        log.info("111111路径规划匹配路网的消息 :{}",message);
        pathPlanningService.graphMatchData(message);
    }


}
