import api from './api';

/**
 * 实现路径服务
 * 处理路径的增删改查
 */

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

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

/**
 * 根据剧本ID获取路径
 * @param {string} scriptId - 剧本ID
 * @returns {Promise<Object>} 路径详情
 */
export const getPathByScriptId = async (scriptId) => {
  const response = await api.get('/lifePath/byScript', {
    params: { scriptId }
  });
  return response;
};

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

/**
 * 创建路径
 * @param {Object} pathData - 路径数据
 * @returns {Promise<Object>} 创建的路径
 */
export const createPath = async (pathData) => {
  const requestData = transformToBackendFormat(pathData);
  const response = await api.post('/lifePath/create', requestData);
  return response;
};

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

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

/**
 * 将前端数据格式转换为后端格式
 * @param {Object} frontendData - 前端数据
 * @returns {Object} 后端格式数据
 */
const transformToBackendFormat = (frontendData) => {
  const {
    id,
    scriptId,
    title,
    description,
    content,
    status = 'active',
    progress = 0
  } = frontendData;

  // 解析内容为步骤列表
  let steps = [];
  if (content) {
    // 尝试解析文本内容为步骤
    const stepMatches = content.match(/(\d+)\.\s*([^:：]+)[：:]\s*([^\n]+)/g);
    if (stepMatches) {
      steps = stepMatches.map((match, index) => {
        const parts = match.match(/(\d+)\.\s*([^:：]+)[：:]\s*(.+)/);
        return {
          phase: `阶段${index + 1}`,
          time: parts?.[2]?.trim() || '',
          content: parts?.[3]?.trim() || match,
          action: '',
          resources: '',
          habit: ''
        };
      });
    } else {
      // 按换行分割
      const lines = content.split('\n').filter(line => line.trim());
      steps = lines.map((line, index) => ({
        phase: `阶段${index + 1}`,
        time: '',
        content: line.trim(),
        action: '',
        resources: '',
        habit: ''
      }));
    }
  }

  return {
    id,
    scriptId,
    title: title || '实现路径',
    description,
    steps,
    status,
    progress
  };
};

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

  const {
    id,
    userId,
    scriptId,
    title,
    description,
    steps,
    status,
    progress,
    createTime
  } = backendData;

  // 将步骤列表转换为文本内容
  let content = '';
  if (Array.isArray(steps) && steps.length > 0) {
    content = steps.map((step, index) => {
      const phase = step.phase || `阶段${index + 1}`;
      const time = step.time ? `（${step.time}）` : '';
      return `${index + 1}. ${phase}${time}：${step.content || ''}`;
    }).join('\n');
  }

  return {
    id,
    userId,
    scriptId,
    title: title || '实现路径',
    description: description || '',
    content,
    steps: steps || [],
    status: status || 'active',
    progress: progress || 0,
    createTime
  };
};

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

export default {
  getPathList,
  getPathPage,
  getPathByScriptId,
  getPathById,
  createPath,
  updatePath,
  deletePath,
  transformToFrontendFormat,
  transformListToFrontend
};
