import { TimeDimension, QuarterFormat, DateFormatter, QuarterFormatter, ApiDataConverter, IndustryDataItem, AreaDataItem } from '@/types/analysis/industry';

export const formatQuarter: QuarterFormatter = (dateStr: string): QuarterFormat => {
  if (dateStr.includes('第')) return dateStr as QuarterFormat;
  
  const [year, quarterPart] = dateStr.includes('-Q') 
    ? dateStr.split('-Q') 
    : dateStr.split('-');

  const quarterNum = quarterPart.replace('季度', '');
  const quarterMap: Record<string, string> = {
    '1': '第一季度',
    '2': '第二季度',
    '3': '第三季度',
    '4': '第四季度'
  };
  return `${year}-${quarterMap[quarterNum] || quarterPart}` as QuarterFormat;
};

export const formatDateForDisplay: DateFormatter = (dateStr: string, dimension: TimeDimension): string => {
  try {
    if (dimension === '年') return dateStr.split('-')[0];
    if (dimension === '季度') {
      if (dateStr.includes('第')) {
        const [year, quarter] = dateStr.split('-');
        return `${year}年${quarter}`;
      }
      const [year, quarterNum] = dateStr.split('-');
      const quarterMap: Record<string, string> = {
        '1': '第一季度',
        '2': '第二季度',
        '3': '第三季度',
        '4': '第四季度',
        'Q1': '第一季度',
        'Q2': '第二季度',
        'Q3': '第三季度',
        'Q4': '第四季度'
      };
      return `${year}年${quarterMap[quarterNum] || quarterNum}`;
    }
    const [year, month] = dateStr.split('-');
    return `${year}年${month}月`;
  } catch (e) {
    console.error('日期格式化错误:', e);
    return dateStr;
  }
};

export const convertApiData: ApiDataConverter = (apiData: any) => {
  if (!apiData) return [];
  try {
    if (Array.isArray(apiData)) {
      return apiData.map(item => ({
        date: item.time || item.date,
        category: item.name || item.category || '未知行业',
        value: Number(item.data || item.value) || 0
      }));
    }
    if (typeof apiData === 'object') {
      const result: IndustryDataItem[] = [];
      Object.entries(apiData).forEach(([date, items]) => {
        if (Array.isArray(items)) {
          items.forEach((item: any) => {
            result.push({
              date,
              category: item.name || item.category || '未知行业',
              value: Number(item.data || item.value) || 0
            });
          });
        }
      });
      return result;
    }
    return [];
  } catch (error) {
    console.error('数据转换错误:', error);
    return [];
  }
};

export const convertAreaApiData = (apiData: any): AreaDataItem[] => {
  if (!apiData?.data) {
    console.warn('convertAreaApiData: apiData.data 为空');
    return [];
  }

  try {
    const result: AreaDataItem[] = [];
    
    // 处理嵌套的月份数据
    if (typeof apiData.data === 'object' && !Array.isArray(apiData.data)) {
      Object.entries(apiData.data).forEach(([time, items]) => {
        if (Array.isArray(items)) {
          items.forEach((item: any) => {
            if (!item) return;
            const uniqueName = items.filter((i: any) => i.name === item.name).length > 1 
              ? `${item.name}_${index}` 
              : item.name;
            result.push({
              name: item.name || '未知区域',
              value: Number(item.data) || 0,
              time: item.time || time,
              x:uniqueName,
              y:time,
              category: item.name,
              originalData: item 
            });
          });
        }
      });
      return result;
    }
     if (Array.isArray(apiData.data)) {
      return apiData.data.map((item: any) => ({
        name: item.name || '未知区域',
        value: Number(item.data) || 0,
        time: item.time || '未知时间',
        x: item.name,
        y: item.time,
        category: item.name,
        originalData: item
      }));
    }
    return [];
  } catch (error) {
    console.error('数据转换错误:', error);
    return [];
  }
};

export const convertSalaryData: ApiDataConverter = (apiData: any) => {
  if (!apiData) return [];
  try {
    if (Array.isArray(apiData)) {
      return apiData.map(item => ({
        date: item.time || item.date,
        category: item.name || item.category || '未知薪资区间',
        value: Number(item.data || item.value) || 0
      }));
    }
    if (typeof apiData === 'object') {
      const result: IndustryDataItem[] = [];
      Object.entries(apiData).forEach(([date, items]) => {
        if (Array.isArray(items)) {
          items.forEach((item: any) => {
            result.push({
              date,
              category: item.name || item.category || '未知薪资区间',
              value: Number(item.data || item.value) || 0
            });
          });
        }
      });
      return result;
    }
    return [];
  } catch (error) {
    console.error('薪资数据转换错误:', error);
    return [];
  }
};

export const convertWorkYearData: ApiDataConverter = (apiData: any) => {
  if (!apiData) return [];
  try {
    if (Array.isArray(apiData)) {
      return apiData.map(item => ({
        date: item.time || item.date || '',
        category: item.name || item.category || '未知经验要求',
        value: Number(item.data || item.value || 0) // 确保数值不为null/undefined
      }));
    }
    if (typeof apiData === 'object') {
      const result: IndustryDataItem[] = [];
      Object.entries(apiData).forEach(([date, items]) => {
        if (Array.isArray(items)) {
          items.forEach((item: any) => {
            result.push({
              date: date || '',
              category: item.name || item.category || '未知经验要求',
              value: Number(item.data || item.value || 0) // 确保数值不为null/undefined
            });
          });
        }
      });
      return result;
    }
    return [];
  } catch (error) {
    console.error('工作经验数据转换错误:', error);
    return [];
  }
};
export const convertEducationData: ApiDataConverter = (apiData: any) => {
  if (!apiData) return [];
  try {
    const result: any[] = [];
    
    // 处理嵌套的月份数据
    if (typeof apiData === 'object' && !Array.isArray(apiData)) {
      Object.entries(apiData).forEach(([date, items]) => {
        if (Array.isArray(items)) {
          items.forEach((item: any) => {
            if (!item) return; // 跳过空项
            result.push({
              date: date || '', // 确保日期不为undefined
              category: item.name || item.category || '不限', // 默认值
              value: Number(item.data || item.value || 0), // 确保数值有效
              originalData: item
            });
          });
        }
      });
      return result;
    }
    
    // 处理数组格式的响应
    if (Array.isArray(apiData)) {
      return apiData.map(item => ({
        date: item.time || item.date || '',
        category: item.name || item.category || '不限',
        value: Number(item.data || item.value || 0),
        originalData: item
      }));
    }
    
    return [];
  } catch (error) {
    console.error('学历数据转换错误:', error);
    return [];
  }
};