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

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.cmvr.common.enums.FileType;
import com.cmvr.common.exception.GlobalException;
import com.cmvr.edge.client.model.EdgeCommonVO;
import com.cmvr.edge.client.service.EdgeCameraService;
import com.cmvr.test.enums.ActionEnum;
import com.cmvr.test.flow.context.TaskInstHolder;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteMessage;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteResult;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class EdgeCameraOperateService implements EdgeOperateService {

    private final EdgeCameraService edgeCameraService;
    private final TaskInstHolder taskInstHolder;

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

    @Override
    public TaskNodeExecuteResult execute(TaskNodeExecuteMessage message) {
//        try {
//            Thread.sleep(3000);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }
        String instId = message.getInstId();
        String nodeId = message.getNodeId();
        ActionEnum action = message.getAction();
        JSONObject inputParams = message.getInputParams();
        String deviceId = inputParams.getString("deviceId");
        String terminalId = message.getTerminalId();
        JSONObject upstreamOutput = message.getUpStreamOutput();

        JSONObject output = new JSONObject();

        EdgeCommonVO edgeCommonVO = new EdgeCommonVO();
        edgeCommonVO.setDeviceId(deviceId);
        edgeCommonVO.setTerminalId(terminalId);

        switch (action) {
            case CAMERA_START: {
//                String result = edgeCameraService.start(terminalId, deviceId);
                String result = StrUtil.format("id为 [{}] 的相机开启了", deviceId);
                output.put("result", result);
                break;
            }

            case CAMERA_STOP: {
                String result = StrUtil.format("id为 [{}] 的相机关闭了", deviceId);
//                String result = edgeCameraService.stop(terminalId, deviceId);
                output.put("result", result);
                break;
            }

            case CAMERA_GETRGBIMAGE: {
//                String imageUrl;
//                String imageUrl = StrUtil.format("id为 [{}] 的相机拍照了", deviceId);
//                if (message.getLoopNum() <= 1) {
//                    // 车辆控制调节
//                    imageUrl = "http://192.168.1.100:9000/cmvr-iot/FILE/20250821/1755761816340.jpg";
//                } else {
//                    // 驾驶偏好
//                    imageUrl = "http://192.168.1.100:9000/cmvr-iot/FILE/20250822/1755849654731.jpg";
//                }
                String imageUrl = "http://192.168.1.100:9000/cmvr-iot/IMAGE/20250901/1756718594725.jpg";
//                 String imageUrl = edgeCameraService.getRGBDImages(terminalId, deviceId);

//                JSONArray imageUrls = new JSONArray();
//                if (ObjUtil.isNotEmpty(upstreamOutput)) {
//                    JSONArray upstream = upstreamOutput.getJSONArray("imageUrl");
//                    if (ObjUtil.isNotEmpty(upstream)) {
//                        imageUrls.addAll(upstream);
//                    }
//                }
//
//                imageUrls.add(imageUrl);
                output.put("imageUrl", imageUrl);
                output.put("type", FileType.IMAGE.code());
                break;
            }

            case CAMERA_RECORDING_START: {
                String videoUrl = edgeCameraService.startRecording(edgeCommonVO);
                videoUrl = StrUtil.format("{}/{}", "http://10.148.108.162/system/video", StrUtil.subAfter(videoUrl, "/", true));
//                String videoUrl = "http://10.148.108.162/system/video/cam4_1752225205349.mp4";
//                JSONArray videoUrls = new JSONArray();
//                if (ObjUtil.isNotEmpty(upstreamOutput)) {
//                    JSONArray upstream = upstreamOutput.getJSONArray("videoUrl");
//                    if (ObjUtil.isNotEmpty(upstream)) {
//                        videoUrls.addAll(upstream);
//                    }
//                }
//
//                videoUrls.add(videoUrl);
                output.put("videoUrl", videoUrl);
                output.put("isPlay", false);
                output.put("type", FileType.VIDEO.code());

                break;
            }

            case CAMERA_RECORDING_STOP: {
                edgeCameraService.stopRecording(edgeCommonVO);
                // todo 结束录像获取视频路径输出
//                // 获取视频录制开始节点的id
//                FlowNodeWrapper startRecordNode = message.getGraph()
//                        .getNodeMap()
//                        .values()
//                        .stream()
//                        .filter(node -> ActionEnum.CAMERA_RECORDING_START.equals(node.getAction()))
//                        .findFirst()
//                        .orElseThrow(() -> new IllegalStateException("未找到视频录制开始节点"));
//
//                // 从上下文获取上游节点存储的参数 获取视频地址
//                JSONObject pre = taskInstHolder.getNodeOutParams(instId, startRecordNode.getNodeId());
//                JSONArray videoUrl = pre.getJSONArray("videoUrl");
//                output.put("videoUrl", videoUrl);
//                output.put("isPlay", true);
//                output.put("type", FileType.VIDEO.code());
                break;
            }
            default:
                throw new GlobalException("不支持的相机操作类型: " + action);
        }

        return TaskNodeExecuteResult.success(output);
    }
}
