import api from './api';

/**
 * 爽文剧本服务
 * 处理剧本的增删改查
 */

/**
 * 获取当前用户的所有剧本
 * @returns {Promise<Array>} 剧本列表
 */
export const getScriptList = async () => {
  const response = await api.get('/epicScript/listAll');
  return response;
};

/**
 * 分页获取剧本
 * @param {Object} params - 分页参数
 * @param {number} params.pageNum - 页码
 * @param {number} params.pageSize - 每页数量
 * @returns {Promise<Object>} 分页结果
 */
export const getScriptPage = async ({ pageNum = 1, pageSize = 10 }) => {
  const response = await api.get('/epicScript/page', {
    params: { pageNum, pageSize }
  });
  return response;
};

/**
 * 根据ID获取剧本详情
 * @param {string} id - 剧本ID
 * @returns {Promise<Object>} 剧本详情
 */
export const getScriptById = async (id) => {
  const response = await api.get('/epicScript/detail', {
    params: { id }
  });
  return response;
};

/**
 * 创建剧本
 * @param {Object} scriptData - 剧本数据
 * @returns {Promise<Object>} 创建的剧本
 */
export const createScript = async (scriptData) => {
  const requestData = transformToBackendFormat(scriptData);
  const response = await api.post('/epicScript/create', requestData);
  return response;
};

/**
 * 更新剧本
 * @param {Object} scriptData - 剧本数据（必须包含 id）
 * @returns {Promise<Object>} 更新后的剧本
 */
export const updateScript = async (scriptData) => {
  const requestData = transformToBackendFormat(scriptData);
  const response = await api.put('/epicScript/update', requestData);
  return response;
};

/**
 * 选中剧本
 * @param {string} id - 剧本ID
 * @returns {Promise<Object>} 选中的剧本
 */
export const selectScript = async (id) => {
  const response = await api.put('/epicScript/select', null, {
    params: { id }
  });
  return response;
};

/**
 * 删除剧本
 * @param {string} id - 剧本ID
 * @returns {Promise<void>}
 */
export const deleteScript = async (id) => {
  const response = await api.delete('/epicScript/delete', {
    params: { id }
  });
  return response;
};

/**
 * 将前端数据格式转换为后端格式
 * @param {Object} frontendData - 前端数据
 * @returns {Object} 后端格式数据
 */
const transformToBackendFormat = (frontendData) => {
  const {
    id,
    theme,
    style,
    length,
    content,
    isSelected,
    character,
    events,
    regenerateContent = false
  } = frontendData;

  // 解析内容生成标题和各部分
  let title = theme || '我的剧本';
  let plotIntro = '';
  let plotTurning = '';
  let plotClimax = '';
  let plotEnding = '';

  if (content) {
    // 尝试从内容中提取各部分
    const sections = content.split(/【[^】]+】/);
    const titles = content.match(/【[^】]+】/g) || [];
    
    titles.forEach((t, index) => {
      const sectionContent = sections[index + 1]?.trim() || '';
      if (t.includes('序幕') || t.includes('低谷')) {
        plotIntro = sectionContent;
      } else if (t.includes('转折') || t.includes('契机')) {
        plotTurning = sectionContent;
      } else if (t.includes('高潮') || t.includes('抉择')) {
        plotClimax = sectionContent;
      } else if (t.includes('结局') || t.includes('开始')) {
        plotEnding = sectionContent;
      }
    });
  }

  // 格式化角色信息
  let characterInfo = '';
  if (character) {
    const parts = [
      `姓名：${character.nickname || '未设置'}`,
      `性别：${character.gender || '未设置'}`,
      `MBTI：${character.mbti || '未设置'}`,
      `星座：${character.zodiac || '未设置'}`,
      `职业：${character.profession || '未设置'}`,
      `兴趣爱好：${character.hobbies?.join(',') || '无'}`
    ];

    if (character.future) {
      if (character.future.vision) parts.push(`未来愿景：${character.future.vision}`);
      if (character.future.ideal) parts.push(`理想生活：${character.future.ideal}`);
    }

    characterInfo = parts.join('\n');
  }

  // 格式化过往经历
  let lifeEventsSummary = '';
  const eventParts = [];

  // 1. 核心记忆 (Childhood, Joy, Low from character data)
  if (character) {
    if (character.childhood?.text) {
      eventParts.push(`【童年记忆】(${character.childhood.date || '未知时间'}): ${character.childhood.text}`);
    }
    if (character.joy?.text) {
      eventParts.push(`【高光时刻】(${character.joy.date || '未知时间'}): ${character.joy.text}`);
    }
    if (character.low?.text) {
      eventParts.push(`【至暗时刻】(${character.low.date || '未知时间'}): ${character.low.text}`);
    }
  }

  // 2. 详细人生事件
  if (events && Array.isArray(events)) {
    events.forEach(e => {
      const dateStr = e.time || e.eventDate || '未知时间';
      const titleStr = e.title || '无标题';
      const contentStr = e.content || '';
      eventParts.push(`【人生事件】(${dateStr}) ${titleStr}${contentStr ? ': ' + contentStr : ''}`);
    });
  }

  lifeEventsSummary = eventParts.join('\n');

  return {
    id,
    title,
    theme,
    style,
    length,
    plotIntro,
    plotTurning,
    plotClimax,
    plotEnding,
    plotJson: content ? { fullContent: content } : null,
    isSelected,
    characterInfo,
    lifeEventsSummary,
    regenerateContent
  };
};

/**
 * 将后端数据格式转换为前端格式
 * @param {Object} backendData - 后端数据
 * @returns {Object} 前端格式数据
 */
export const transformToFrontendFormat = (backendData) => {
  if (!backendData) return null;

  const {
    id,
    userId,
    title,
    theme,
    style,
    length,
    plotIntro,
    plotTurning,
    plotClimax,
    plotEnding,
    plotJson,
    isSelected,
    createTime
  } = backendData;

  // 重建完整内容
  let content = '';
  if (plotJson?.fullContent) {
    content = plotJson.fullContent;
  } else {
    const parts = [];
    if (plotIntro) parts.push(`【序幕：低谷回响】\n${plotIntro}`);
    if (plotTurning) parts.push(`【转折：契机出现】\n${plotTurning}`);
    if (plotClimax) parts.push(`【高潮：命运抉择】\n${plotClimax}`);
    if (plotEnding) parts.push(`【结局：新的开始】\n${plotEnding}`);
    content = parts.join('\n\n');
  }

  return {
    id,
    userId,
    title: title || theme || '未命名剧本',
    theme: theme || '',
    style: style || '',
    length: length || 'medium',
    content,
    isSelected: isSelected || false,
    date: createTime ? new Date(createTime).toLocaleDateString() : new Date().toLocaleDateString()
  };
};

/**
 * 批量转换后端数据为前端格式
 * @param {Array} backendList - 后端数据列表
 * @returns {Array} 前端格式数据列表
 */
export const transformListToFrontend = (backendList) => {
  if (!Array.isArray(backendList)) return [];
  return backendList.map(transformToFrontendFormat);
};

export default {
  getScriptList,
  getScriptPage,
  getScriptById,
  createScript,
  updateScript,
  selectScript,
  deleteScript,
  transformToFrontendFormat,
  transformListToFrontend
};
