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

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONArray;
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.system.service.ISysFileService;
import com.cmvr.test.enums.ActionEnum;
import com.cmvr.test.flow.builder.FlowNodeWrapper;
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;

import java.util.concurrent.atomic.AtomicInteger;

@Service
@RequiredArgsConstructor
public class EdgeCameraOperateService implements EdgeOperateService {

    private final EdgeCameraService edgeCameraService;
    private final TaskInstHolder taskInstHolder;
    private final ISysFileService sysFileService;

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

    private static final String[] VIDEO_URLS = {
            "http://192.168.0.100:9000/cmvr-iot/VIDEO/20260205/1770257486644.mp4",  // 单次 东北话中的那疙瘩什么意思
            "http://192.168.0.100:9000/cmvr-iot/VIDEO/20260205/1770257510949.mp4",// 单次 打开视频
            "http://192.168.0.100:9000/cmvr-iot/VIDEO/20260205/1770257536282.mp4",   // 连续 导航到解放碑
            "http://192.168.0.100:9000/cmvr-iot/VIDEO/20260205/1770257552050.mp4"  // 连续 青花瓷
    };

    private AtomicInteger currentIndex = new AtomicInteger(0);

    @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.getRGBImage(edgeCommonVO);

                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);
//                String videoUrl = StrUtil.format("{}/{}_{}.mp4", "/home/share/assets/video", deviceId, System.currentTimeMillis());
                String videoUrl = "/home/xtkuang/Projects/models/assets/video/IMG_0524_silent.mp4";
                // 创建一个新的 JSONObject 来保存视频路径和其他信息
                JSONObject videoInfo = new JSONObject();
                videoInfo.put("videoUrl", videoUrl);
                videoInfo.put("isPlay", false);  // 初始状态为不可播放
                videoInfo.put("type", FileType.VIDEO.code());  // 文件类型为视频

                // 将视频路径数组保存到 output 中
                output.put("videoInfo", videoInfo);
                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 preStart = taskInstHolder.getNodeOutParams(instId, startRecordNode.getNodeId(), message.getIterations());

                JSONObject videoInfo = preStart.getJSONObject("videoInfo");
                videoInfo.put("isPlay", true);
//                String videoUrl = videoInfo.getString("videoUrl");
//                String url = sysFileService.uploadFile(new File(videoUrl), FileType.VIDEO.code());
//                videoInfo.put("videoUrl", url);
                String videoUrl = VIDEO_URLS[currentIndex.getAndUpdate(i -> (i + 1) % VIDEO_URLS.length)];
                videoInfo.put("videoUrl", videoUrl);
                // 将视频路径数组保存到 output 中
                output.put("videoUrl", videoInfo);
                break;
            }
            default:
                throw new GlobalException("不支持的相机操作类型: " + action);
        }

        return TaskNodeExecuteResult.success(output);
    }
}
