package com.cmvr.test.flow.runtime.operator.edge;

import cmvr.msgs.Agv;
import com.alibaba.fastjson2.JSONObject;
import com.cmvr.common.exception.GlobalException;
import com.cmvr.edge.client.model.EdgeCommonVO;
import com.cmvr.edge.client.service.EdgeAgvService;
import com.cmvr.test.enums.ActionEnum;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteMessage;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * AGV边缘操作服务
 * 处理AGV相关的设备行为，如移动到指定位置
 *
 * @author cmvr-iot
 * @since 2026-07-02
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class EdgeAgvOperateService implements EdgeOperateService {

    private final EdgeAgvService edgeAgvService;

    @Override
    public boolean supports(ActionEnum action) {
        return action.name().startsWith("AGV_");
    }

    @Override
    public TaskNodeExecuteResult execute(TaskNodeExecuteMessage message) {
        ActionEnum action = message.getAction();
        JSONObject inputParams = message.getInputParams();
        String terminalId = message.getTerminalId();
        
        // 从输入参数中获取机器人ID
        String deviceId = inputParams.getString("deviceId");
        
        if (deviceId == null || deviceId.isEmpty()) {
            throw new GlobalException("机器人ID(deviceId)不能为空");
        }

        switch (action) {
            case AGV_MOVE_TO_POINT: {
                log.info("执行AGV移动到指定位置操作，机器人ID: {}", deviceId);
                
                // 从输入参数中获取坐标信息
                Double x = inputParams.getDouble("x");
                Double y = inputParams.getDouble("y");
                Double theta = inputParams.getDouble("theta");
                
                // 参数验证
                if (x == null || y == null) {
                    throw new GlobalException("X和Y坐标不能为空");
                }
                
                // 构建目标位姿
                Agv.AgvPose2d pose = Agv.AgvPose2d.newBuilder()
                    .setX(x)
                    .setY(y)
                    .setTheta(theta != null ? theta : 0.0)
                    .build();
                
                // 构建边缘端通用参数
                EdgeCommonVO edgeCommonVO = new EdgeCommonVO();
                edgeCommonVO.setTerminalId(terminalId);
                edgeCommonVO.setDeviceId(deviceId);
                
                // 直接调用边缘端AGV服务执行导航
                edgeAgvService.navigateToPose(edgeCommonVO, pose);
                
                log.info("AGV移动任务下发成功");
                
                break;
            }

            default:
                throw new GlobalException("不支持的AGV操作类型: " + action);
        }
        
        return TaskNodeExecuteResult.success();
    }
}
