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

import { get, post, put, del } from './request.js'

export const getPathList = async () => {
  const response = await get('/lifePath/listAll')
  return response
}

export const getPathPage = async ({ pageNum = 1, pageSize = 10 }) => {
  const response = await get('/lifePath/page', { pageNum, pageSize })
  return response
}

export const getPathByScriptId = async (scriptId) => {
  const response = await get('/lifePath/byScript', { scriptId })
  return response
}

export const getPathById = async (id) => {
  const response = await get('/lifePath/detail', { id })
  return response
}

export const createPath = async (pathData) => {
  const requestData = transformToBackendFormat(pathData)
  const response = await post('/lifePath/create', requestData)
  return response
}

export const updatePath = async (pathData) => {
  const requestData = transformToBackendFormat(pathData)
  const response = await put('/lifePath/update', requestData)
  return response
}

export const deletePath = async (id) => {
  const response = await del('/lifePath/delete', { id })
  return response
}

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
  }
}

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
  }
}

export const transformListToFrontend = (backendList) => {
  if (!Array.isArray(backendList)) return []
  return backendList.map(transformToFrontendFormat)
}

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