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

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

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

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

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

export const createScript = async (scriptData) => {
  const requestData = transformToBackendFormat(scriptData)
  const response = await post('/epicScript/create', requestData)
  return response
}

export const updateScript = async (scriptData) => {
  const requestData = transformToBackendFormat(scriptData)
  const response = await put('/epicScript/update', requestData)
  return response
}

export const selectScript = async (id) => {
  const response = await put('/epicScript/select', { id })
  return response
}

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

const transformToBackendFormat = (frontendData) => {
  const {
    id,
    theme,
    style,
    length,
    content,
    isSelected,
    character,
    events
  } = 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 = []

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

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

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

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

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