import axios from 'axios';

// 定义API响应的类型接口
interface Article {
  id: string;
  articleType: string;
  title: string;
  summary: string;
  coverUrl: string;
  sliderImage: string | null;
  video: string | null;
  content: string;
  subContent: string | null;
  orderNum: number;
  status: string;
  remark: string | null;
  createTime: number;
  lang: string;
  relationList: any | null;
}

interface ApiResponse {
  code: number;
  data: {
    list: Article[];
    total: number;
    totalDes: string | null;
  };
  msg: string;
}

// API响应缓存配置
const CACHE_EXPIRATION = 10 * 60 * 1000; // 10分钟

// 缓存接口定义
interface CacheItem {
  data: ApiResponse;
  timestamp: number;
}

// 缓存对象
const cache: Record<string, CacheItem> = {};

// 生成缓存键
const generateCacheKey = (url: string, params: Record<string, any>): string => {
  const sortedParams = Object.keys(params).sort().reduce((acc, key) => {
    acc[key] = params[key];
    return acc;
  }, {} as Record<string, any>);
  return `${url}?${JSON.stringify(sortedParams)}`;
};

// 获取缓存数据
const getCachedData = (key: string): ApiResponse | null => {
  const cachedItem = cache[key];
  if (!cachedItem) return null;
  
  const now = Date.now();
  if (now - cachedItem.timestamp > CACHE_EXPIRATION) {
    delete cache[key];
    return null;
  }
  
  return cachedItem.data;
};

// 设置缓存数据
const setCachedData = (key: string, data: ApiResponse): void => {
  cache[key] = {
    data,
    timestamp: Date.now()
  };
};

// 获取热门文章列表
export const fetchHotArticles = async (lang: number, pageSize: number): Promise<ApiResponse> => {
  try {
    const baseUrl = import.meta.env.VITE_SHIP_API_BASE_URL || 'http://localhost:48080';
    const apiPath = import.meta.env.VITE_SHIP_API_PATH || '/ship-api';
    const url = `${baseUrl}${apiPath}/cms/article/portal/page-list`;
    const params = {
      lang,
      'type.remark': 'hot',
      pageSize
    };
    
    // 生成缓存键
    const cacheKey = generateCacheKey(url, params);
    
    // 检查缓存
    const cachedData = getCachedData(cacheKey);
    if (cachedData) {
      return cachedData;
    }
    
    // 发起API请求
    const response = await axios.get<ApiResponse>(url, { params });
    
    // 缓存响应数据
    setCachedData(cacheKey, response.data);
    
    return response.data;
  } catch (error) {
    console.error('Failed to fetch hot articles:', error);
    throw error;
  }
};

// 从文章数据中提取轮播图URL
export const extractHeroImagesFromArticles = (articlesData: ApiResponse): string[] => {
  // 检查API响应是否成功
  if (articlesData.code !== 0 || !articlesData.data || !articlesData.data.list) {
    return [];
  }

  // 从文章列表中提取coverUrl作为轮播图
  return articlesData.data.list
    .filter(article => article.coverUrl) // 确保coverUrl存在
    .map(article => article.coverUrl);
};

// 获取视频内容
export const fetchVideoContent = async (lang: number): Promise<ApiResponse> => {
  try {
    const baseUrl = import.meta.env.VITE_SHIP_API_BASE_URL || 'http://localhost:48080';
    const apiPath = import.meta.env.VITE_SHIP_API_PATH || '/ship-api';
    const url = `${baseUrl}${apiPath}/cms/article/portal/page-list`;
    const params = {
      lang,
      'type.id': '2001571782243946498'
    };
    
    // 生成缓存键
    const cacheKey = generateCacheKey(url, params);
    
    // 检查缓存
    const cachedData = getCachedData(cacheKey);
    if (cachedData) {
      return cachedData;
    }
    
    // 发起API请求
    const response = await axios.get<ApiResponse>(url, { params });
    
    // 缓存响应数据
    setCachedData(cacheKey, response.data);
    
    return response.data;
  } catch (error) {
    console.error('Failed to fetch video content:', error);
    throw error;
  }
};

// 获取游轮航线数据
export const fetchCruiseRoutes = async (lang: number = 1): Promise<ApiResponse> => {
  try {
    const baseUrl = import.meta.env.VITE_SHIP_API_BASE_URL || 'http://localhost:48080';
    const apiPath = import.meta.env.VITE_SHIP_API_PATH || '/ship-api';
    const url = `${baseUrl}${apiPath}/cms/article/portal/page-list`;
    const params = {
      lang,
      'type.id': '1955559122615775234'
    };
    
    // 生成缓存键
    const cacheKey = generateCacheKey(url, params);
    
    // 检查缓存
    const cachedData = getCachedData(cacheKey);
    if (cachedData) {
      return cachedData;
    }
    
    // 发起API请求
    const response = await axios.get<ApiResponse>(url, { params });
    
    // 缓存响应数据
    setCachedData(cacheKey, response.data);
    
    return response.data;
  } catch (error) {
    console.error('Failed to fetch cruise routes:', error);
    throw error;
  }
};

// 从文章数据中提取视频内容
export const extractVideoContentFromArticles = (articlesData: ApiResponse): {
  title: string;
  titleItalic: string;
  description: string;
  thumbnail: string;
  video?: string;
} | null => {
  // 检查API响应是否成功
  if (articlesData.code !== 0 || !articlesData.data || !articlesData.data.list || articlesData.data.list.length === 0) {
    return null;
  }

  // 获取第一篇文章作为视频内容
  const videoArticle = articlesData.data.list[0];
  
  // 提取视频内容
  return {
    title: videoArticle.title || '',
    titleItalic: '', // API中没有直接的titleItalic字段，可能需要从title中提取或使用默认值
    description: videoArticle.summary || '',
    thumbnail: videoArticle.coverUrl || '',
    video: videoArticle.video || undefined
  };
};

// 定义subContent条目的接口
interface SubContentItem {
  tid: number;
  title: string;
  content: string;
}

// 解析subContent字段
export const parseSubContent = (subContent: string | null): Record<string, string> => {
  if (!subContent) {
    return {};
  }
  
  try {
    const parsedItems: SubContentItem[] = JSON.parse(subContent);
    const result: Record<string, string> = {};
    
    // 从每个条目提取内容（去除HTML标签）
    parsedItems.forEach(item => {
      // 去除HTML标签并保留文本内容
      const textContent = item.content.replace(/<[^>]*>/g, '').trim();
      result[item.title] = textContent;
    });
    
    return result;
  } catch (error) {
    console.error('Failed to parse subContent:', error);
    return {};
  }
};

// 从文章数据中提取游轮航线信息
export const extractCruiseRoutesFromArticles = (articlesData: ApiResponse): any[] => {
  // 检查API响应是否成功
  if (articlesData.code !== 0 || !articlesData.data || !articlesData.data.list) {
    return [];
  }

  // 转换文章数据为游轮航线格式
  return articlesData.data.list.map(article => {
    // 解析subContent获取详细信息
    const subContentData = parseSubContent(article.subContent);
    
    // 提取天数信息（从title或summary中尝试提取）
    let days = 0;
    const daysMatch = article.title.match(/\d+天/) || article.summary.match(/\d+天/);
    if (daysMatch) {
      days = parseInt(daysMatch[0]);
    }
    
    // 构建游轮航线对象
    return {
      id: article.id,
      title: article.title || '',
      days,
      price: subContentData['价格'] || '价格待定',
      image: article.coverUrl || '',
      video: article.video || undefined,
      route: subContentData['目的地'] || '',
      description: article.summary || '',
      highlights: [
        // 从summary中提取亮点，或者使用默认值
        ...(article.summary ? [article.summary] : [])
      ],
      itinerary: [], // 默认空行程，可能需要从content字段进一步解析
      schedule: subContentData['航期'] || ''
    };
  });
};
