import { BASE_URL } from "./constants";

// 获取路演配置数据
export const fetchRoadshowConfigs = async () => {
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), 10000); // 10秒超时
  
  try {
    console.log('开始请求接口数据...');
    const response = await fetch(BASE_URL + '/serversetting/roadshow-configs', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({}),
      signal: controller.signal,
    });

    clearTimeout(timeoutId);

    if (!response.ok) {
      throw new Error(`接口请求失败: HTTP ${response.status} - ${response.statusText}`);
    }

    const result = await response.json();
    console.log('接口返回数据:', result);
    
    // 验证返回数据格式
    if (result.code !== 0) {
      throw new Error(`接口错误: ${result.message || '未知错误'} (code: ${result.code})`);
    }
    
    if (!result.successful) {
      throw new Error(`接口调用不成功: ${result.message || '未知原因'}`);
    }
    
    if (!result.data || !Array.isArray(result.data) || result.data.length === 0) {
      throw new Error('接口返回数据格式错误或为空');
    }

    // 验证数据结构
    let validData: any[] = [];
    result.data.forEach((item: any) => {
      if (item) {
        validData.push(JSON.parse(item));
      }
    });

    if (validData.length === 0) {
      throw new Error('接口返回的数据格式不正确');
    }

    console.log('成功获取并验证接口数据:', validData);
    return validData;
    
  } catch (error: unknown) {
    clearTimeout(timeoutId);
    
    if (error instanceof Error && error.name === 'AbortError') {
      throw new Error('接口请求超时，请检查网络连接');
    }
    
    console.error('接口请求失败:', error);
    throw error;
  }
};
