import { createSlice } from '@reduxjs/toolkit';

// 定义初始状态类型
interface IDEContainerState {
  info: any;
  menuData: any;
  flowData: any;
  canvasDataMap: any;
  projectComponentData: any;
  currentAppData: any;
  eventListOld: any;
  eventList: any;
  eventTopicList: any;
  logBarStatus?: boolean;
  socketId: string;
  nodeStatusMap: Record<string, string>; // 节点状态映射
  isRunning: boolean; // 是否正在运行
  // 应用运行状态和日志数据，按应用ID隔离存储
  appRuntimeData: Record<string, {
    nodeStatusMap: Record<string, string>;
    isRunning: boolean;
    logs: any[];
    runId: string;
    eventSendNodeList: any[], // [{nodeID:topic}]
    eventlisteneList: any[] //  [{nodeID:topic}]
  }>;
  gloBalVarList: any;
  // 组件开发相关状态
  componentCoding: {
    localProjectPath: string; // code-server路径
    name: string; // 组件名称
    projectId: string; // 组件标识
    id: string,// 组件id
  };
}

// 初始状态
const initialState: IDEContainerState = {
  info: {}, // 项目信息
  menuData: {}, // 菜单数据
  flowData: {}, // 编排数据，即流程图的渲染数据
  canvasDataMap: {}, // 每个画布的缓存信息
  projectComponentData: {}, // 工程下的组件列表
  currentAppData: {}, // 当前选中的应用数据
  eventListOld: [], // 工程下的事件列表
  eventList: [], // 工程下的事件列表
  eventTopicList: [], // 应用编排使用的事件名和topic列表
  logBarStatus: false,
  socketId: '', // 工程的socketId
  nodeStatusMap: {}, // 初始化节点状态映射
  isRunning: false, // 默认未运行
  appRuntimeData: {}, // 按应用ID隔离的应用运行状态和日志数据
  gloBalVarList: [],  // 工程级全局变量列表
  componentCoding: {
    localProjectPath: '',
    name: '',
    projectId: '',
    id: ''
  }
};

// 辅助函数：获取当前应用/子流程的唯一标识符
// 对于子流程，使用 key（如 sub_xxx）；对于主流程，使用 id
const getCurrentAppKey = (currentAppData: any) => {
  if (!currentAppData) return null;
  // 如果是子流程（key包含'sub'），使用key作为标识符
  if (currentAppData.key && currentAppData.key.includes('sub')) {
    return currentAppData.key;
  }
  // 否则使用id
  return currentAppData.id;
};

// 创建切片
const ideContainerSlice = createSlice({
  name: 'ideContainer',
  initialState,
  reducers: {
    updateInfo(state, action) {
      state.info = action.payload;
    },
    updateMenuData(state, action) {
      state.menuData = action.payload;
    },
    updateFlowData(state, action) {
      state.flowData = { ...state.flowData, ...action.payload };
    },
    updateCanvasDataMap(state, action) {
      state.canvasDataMap = { ...state.canvasDataMap, ...action.payload };
    },
    updateProjectComponentData(state, action) {
      state.projectComponentData = { ...state.projectComponentData, ...action.payload };
    },
    updateCurrentAppData(state, action) {
      state.currentAppData = action.payload;
    },
    updateEventList(state, action) {
      state.eventList = action.payload;
    },
    updateEventListOld(state, action) {
      state.eventListOld = action.payload;
    },
    updateEventTopicList(state, action) {
      state.eventTopicList = action.payload;
    },
    updateLogBarStatus(state, action) {
      state.logBarStatus = action.payload;
    },
    updateSocketId(state, action) {
      state.socketId = action.payload;
    },
    updateGlobalVarList(state, action) {
      state.gloBalVarList = action.payload;
    },
    // 更新节点状态
    updateNodeStatus: (state, { payload }) => {
      const { nodeId, status, actionType } = payload;
      // 如果是运行时更新，不记录到历史记录中
      if (actionType !== 'RUNTIME_UPDATE') {
        state.nodeStatusMap[nodeId] = status;
      }
      else {
        // 对于运行时更新，我们仍然更新状态但标记为运行时状态
        state.nodeStatusMap[nodeId] = status;
      }

      // 同时更新当前应用的节点状态
      const appKey = getCurrentAppKey(state.currentAppData);
      if (appKey) {
        if (!state.appRuntimeData[appKey]) {
          state.appRuntimeData[appKey] = {
            nodeStatusMap: {},
            isRunning: false,
            logs: [],
            runId: '',
            eventSendNodeList: [],
            eventlisteneList: []
          };
        }
        state.appRuntimeData[appKey].nodeStatusMap[nodeId] = status;
      }
    },
    // 重置节点状态
    resetNodeStatus: (state) => {
      state.nodeStatusMap = {};

      // 同时重置当前应用的节点状态
      const appKey = getCurrentAppKey(state.currentAppData);
      if (appKey && state.appRuntimeData[appKey]) {
        state.appRuntimeData[appKey].nodeStatusMap = {};
      }
    },
    // 更新运行状态
    updateIsRunning: (state, { payload }) => {
      state.isRunning = payload;

      // 同时更新当前应用的运行状态
      const appKey = getCurrentAppKey(state.currentAppData);
      if (appKey) {
        if (!state.appRuntimeData[appKey]) {
          state.appRuntimeData[appKey] = {
            nodeStatusMap: {},
            isRunning: false,
            logs: [],
            runId: '',
            eventSendNodeList: [],
            eventlisteneList: []
          };
        }
        state.appRuntimeData[appKey].isRunning = payload;
      }
    },
    // 添加运行id
    updateRuntimeId: (state, { payload }) => {
      const appKey = getCurrentAppKey(state.currentAppData);
      if (!state.appRuntimeData[appKey]) {
        state.appRuntimeData[appKey] = {
          nodeStatusMap: {},
          isRunning: false,
          logs: [],
          runId: '',
          eventSendNodeList: [],
          eventlisteneList: []
        };
      }
      state.appRuntimeData[appKey].runId = payload;
    },
    // 更新事件节点列表
    updateEventNodeList: (state, { payload }) => {
      const appKey = getCurrentAppKey(state.currentAppData);
      if (!state.appRuntimeData[appKey]) {
        state.appRuntimeData[appKey] = {
          nodeStatusMap: {},
          isRunning: false,
          logs: [],
          runId: '',
          eventSendNodeList: [],
          eventlisteneList: []
        };
      }
      state.appRuntimeData[appKey] = { ...state.appRuntimeData[appKey], ...payload };
    },
    // 添加运行日志
    addRuntimeLog: (state, { payload }) => {
      const { log, appId } = payload;
      if (!state.appRuntimeData[appId]) {
        state.appRuntimeData[appId] = {
          nodeStatusMap: {},
          isRunning: false,
          logs: [],
          runId: '',
          eventSendNodeList: [],
          eventlisteneList: []
        };
      }
      state.appRuntimeData[appId].logs.push(log);
    },
    // 清空指定应用的运行日志
    clearRuntimeLogs: (state, { payload }) => {
      const { appId } = payload;
      if (state.appRuntimeData[appId]) {
        state.appRuntimeData[appId].logs = [];
      }
    },
    // 更新组件编码路径
    updateComponentCodingPath(state, action) {
      state.componentCoding = { ...action.payload };
    }
  }
});

// 导出动作 creators
export const {
  updateInfo,
  updateMenuData,
  updateFlowData,
  updateCanvasDataMap,
  updateProjectComponentData,
  updateCurrentAppData,
  updateEventList,
  updateEventListOld,
  updateEventTopicList,
  updateLogBarStatus,
  updateSocketId,
  updateGlobalVarList,
  updateNodeStatus,
  resetNodeStatus,
  updateIsRunning,
  updateRuntimeId,
  updateEventNodeList,
  addRuntimeLog,
  clearRuntimeLogs,
  updateComponentCodingPath
} = ideContainerSlice.actions;

// 默认导出 reducer
export default ideContainerSlice.reducer;