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

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.EdgeMicrophoneService;
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 EdgeMicrophoneOperateService implements EdgeOperateService {

    private final EdgeMicrophoneService edgeMicrophoneService;
    private final TaskInstHolder taskInstHolder;
    private final ISysFileService sysFileService;

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

    private static final String[] AUDIO_URLS = {
            "http://192.168.0.100:9000/cmvr-iot/AUDIO/20260205/1770257444584.wav",  // 单次 东北话中的那疙瘩什么意思
            "http://192.168.0.100:9000/cmvr-iot/AUDIO/20260205/1770255964713.wav",// 单次 打开视频
            "http://192.168.0.100:9000/cmvr-iot/AUDIO/20260205/1770257150877.wav",   // 连续 导航到解放碑
            "http://192.168.0.100:9000/cmvr-iot/AUDIO/20260205/1770257188864.wav"  // 连续 青花瓷
    };

    private AtomicInteger currentIndex = new AtomicInteger(0);

    @Override
    public TaskNodeExecuteResult execute(TaskNodeExecuteMessage message) {
        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 output = new JSONObject();
        EdgeCommonVO edgeCommonVO = new EdgeCommonVO();
        edgeCommonVO.setDeviceId(deviceId);
        edgeCommonVO.setTerminalId(terminalId);
        switch (action) {
            case MICROPHONE_START: {
//                String audioPath = edgeMicrophoneService.startRecord(edgeCommonVO);

//                String audioPath = StrUtil.format("{}/{}_{}.wav", "/home/share/assets/audio", deviceId, System.currentTimeMillis());
                String audioPath = "/home/xtkuang/Projects/models/assets/video/IMG_0524_audio.wav";
                output.put("audioUrl", audioPath);

                // 创建一个新的 JSONObject 来保存音频路径和其他信息
                JSONObject audioInfo = new JSONObject();
                audioInfo.put("audioUrl", audioPath);
                audioInfo.put("isPlay", false);  // 初始状态为不可播放
                audioInfo.put("type", FileType.AUDIO.code());

                output.put("audioInfo", audioInfo);
                break;
            }

            case MICROPHONE_STOP: {
//                edgeMicrophoneService.stopRecord(edgeCommonVO);
                // 获取视频录制开始节点的id
                FlowNodeWrapper startRecordNode = message.getGraph()
                        .getNodeMap()
                        .values()
                        .stream()
                        .filter(node -> ActionEnum.MICROPHONE_START.equals(node.getAction()))
                        .findFirst()
                        .orElseThrow(() -> new IllegalStateException("未找到音频录制开始节点"));

                // 从上下文获取上游节点存储的参数 获取音频地址
                JSONObject preStart = taskInstHolder.getNodeOutParams(instId, startRecordNode.getNodeId(), message.getIterations());

                JSONObject audioInfo = preStart.getJSONObject("audioInfo");
                audioInfo.put("isPlay", true);
//                String audioUrl = audioInfo.getString("audioUrl");
//                String url = sysFileService.uploadFile(new File(audioUrl), FileType.AUDIO.code());
//                audioInfo.put("audioUrl", url);
                String audioUrl = AUDIO_URLS[currentIndex.getAndUpdate(i -> (i + 1) % AUDIO_URLS.length)];
                audioInfo.put("audioUrl", audioUrl);
                // 将视频路径数组保存到 output 中
                output.put("audioUrl", audioInfo);
                break;
            }

            default:
                throw new GlobalException("不支持的麦克风操作类型: " + action);
        }

        return TaskNodeExecuteResult.success(output);
    }
}
