import { create } from 'zustand';
import useChatBoxStore from '../Mid/ChatBoxSlice';

/**
 * 任务队列 Store
 * 管理并行任务（生图、动态表格维护等）的状态
 */
const useTasksStore = create((set, get) => ({
  // ==================== 状态 ====================
  
  // 任务列表
  tasks: [],
  
  // ==================== Actions ====================

  /**
   * 添加任务
   * @param {Object} task - 任务对象 {taskId, taskType, chatId}
   */
  addTask: (task) => set((state) => ({
    tasks: [...state.tasks, { ...task, status: 'pending' }]
  })),

  /**
   * 批量添加任务
   * @param {Array} newTasks - 新任务数组
   */
  addTasks: (newTasks) => set((state) => ({
    tasks: [...state.tasks, ...newTasks.map(t => ({ ...t, status: 'pending' }))]
  })),

  /**
   * 更新任务状态
   * @param {string} taskId - 任务ID
   * @param {string} status - 新状态
   * @param {Object} metadata - 额外元数据
   */
  updateTaskStatus: (taskId, status, metadata = null) => set((state) => ({
    tasks: state.tasks.map(task => 
      task.taskId === taskId 
        ? { ...task, status, ...(metadata && { metadata }) }
        : task
    )
  })),

  /**
   * 取消任务
   * @param {string} taskId - 任务ID
   */
  cancelTask: async (taskId) => {
    const { wsConnection } = useChatBoxStore.getState();
    if (wsConnection) {
      wsConnection.send(JSON.stringify({
        type: 'cancel_task',
        taskId: taskId
      }));
      
      // 乐观更新UI
      set((state) => ({
        tasks: state.tasks.map(task =>
          task.taskId === taskId ? { ...task, status: 'cancelled' } : task
        )
      }));
    }
  },

  /**
   * 清理已完成的任务
   */
  clearCompleted: () => set((state) => ({
    tasks: state.tasks.filter(task => 
      !['completed', 'failed', 'cancelled'].includes(task.status)
    )
  })),

  /**
   * 设置任务列表（用于全量更新）
   * @param {Array} tasks - 任务列表
   */
  setTasks: (tasks) => set({ tasks }),

  /**
   * 清空所有任务
   */
  clearAll: () => set({ tasks: [] })
}));

export default useTasksStore;
