import { 
  TaskObject, 
  SketchItem, 
  VideoItem,
  getRandomMockData
} from './constants';

// 当前选择的mock数据
let selectedMockData: any = null;

// 加载mock数据的辅助函数
const loadMockData = async () => {
  if (!selectedMockData) {
    try {
      selectedMockData = await getRandomMockData();
    } catch (error) {
      // 如果API失败，使用本地fallback数据
      const { MOCK_DATA } = await import('./constants');
      const randomIndex = Math.floor(Math.random() * MOCK_DATA.length);
      selectedMockData = MOCK_DATA[randomIndex];
      console.log('使用本地fallback数据:', selectedMockData);
    }
  }
  return selectedMockData;
};

// 模拟接口请求 获取任务详情
export const getTaskDetail = async (taskId: string): Promise<TaskObject> => {
  // 确保已经加载了数据
  await loadMockData();
  
  const data: TaskObject = {
    projectId: selectedMockData.detail.projectId,
    projectName: selectedMockData.detail.projectName,
    taskId: taskId,
    taskName: selectedMockData.detail.taskName,
    taskDescription: selectedMockData.detail.taskDescription,
    taskStatus: selectedMockData.detail.taskStatus,
    taskProgress: 0,
    mode: selectedMockData.detail.mode,
    resolution: selectedMockData.detail.resolution.toString(),
  };
  return data;
};

// 模拟接口请求 每次获取一个分镜草图 轮询获取
export const getTaskSketch = async (
  taskId: string,
  onProgress: (sketch: SketchItem, index: number) => void
): Promise<void> => {
  // 确保已经加载了数据
  await loadMockData();
  
  const sketchData = selectedMockData.sketch;
  const totalSketches = sketchData.length;
  
  // 模拟分批获取分镜草图
  for (let i = 0; i < totalSketches; i++) {
    await new Promise(resolve => setTimeout(resolve, 2000)); // 模拟2秒延迟
    
    const newSketch: SketchItem = {
      id: `sketch-${i}`,
      url: sketchData[i].url,
      script: sketchData[i].script,
      status: 'done'
    };
    
    onProgress(newSketch, i);
  }
};

// 模拟接口请求 每次获取一个角色 轮询获取
export const getTaskRole = async (taskId: string): Promise<void> => {
  await new Promise(resolve => setTimeout(resolve, 2000)); // 模拟2秒延迟
};

// 模拟接口请求 获取背景音
export const getTaskBackgroundAudio = async (taskId: string): Promise<void> => {
  await new Promise(resolve => setTimeout(resolve, 2000)); // 模拟2秒延迟
};

// 模拟接口请求 获取最终成品
export const getTaskFinalProduct = async (taskId: string): Promise<void> => {
  await new Promise(resolve => setTimeout(resolve, 2000)); // 模拟2秒延迟
};

// 模拟接口请求 每次获取一个分镜视频 轮询获取
export const getTaskVideo = async (
  taskId: string,
  sketchCount: number,
  onProgress: (video: VideoItem, index: number) => void
): Promise<void> => {
  // 确保已经加载了数据
  await loadMockData();
  
  const videoData = selectedMockData.video;
  const totalVideos = videoData.length;
  
  // 模拟分批获取分镜视频
  for (let i = 0; i < totalVideos; i++) {
    await new Promise(resolve => setTimeout(resolve, 5000)); // 模拟5秒延迟
    
    const newVideo: VideoItem = {
      id: `video-${i}`,
      url: videoData[i].url,
      script: videoData[i].script,
      status: 'done'
    };
    
    onProgress(newVideo, i);
  }
}; 