import { message } from 'ant-design-vue'

const BASE_URL = '/api'

function getNetworkErrorMessage(error) {
  if (!navigator.onLine) {
    return '网络连接已断开，请检查您的网络连接'
  }

  if (error.name === 'AbortError') {
    return '请求已超时或被取消，请稍后重试'
  }

  if (error.message?.includes('fetch') || error.message?.includes('network') || error.message?.includes('Failed to fetch') || error.message?.includes('NetworkError')) {
    return '网络连接中断，请检查：\n1. 网络连接是否正常\n2. 后端服务是否已启动\n3. 防火墙是否阻止了连接'
  }

  if (error.message?.includes('timeout') || error.message?.includes('超时')) {
    return 'AI服务响应超时，可能原因：\n1. 代理服务器超时断开\n2. 后端处理时间过长\n建议：简化问题或稍后重试'
  }

  if (error.message?.includes('CORS') || error.message?.includes('cors')) {
    return '跨域请求被拒绝，请联系管理员检查服务器配置'
  }

  if (error.message?.includes('ECONNRESET') || error.message?.includes('connection reset') || error.message?.includes('INCOMPLETE')) {
    return '网络连接被重置或中断，可能原因：\n1. 后端处理时间过长（>60秒）\n2. 代理服务器超时设置过短\n建议：联系管理员检查nginx/代理超时配置'
  }

  return `网络错误: ${error.message || '未知网络问题'}`
}

function getApiErrorMessage(error) {
  if (error.message?.includes('401') || error.message?.includes('未登录')) {
    return '登录已过期，请重新登录'
  }

  if (error.message?.includes('403') || error.message?.includes('权限')) {
    return '没有权限访问此功能'
  }

  if (error.message?.includes('500') || error.message?.includes('服务器')) {
    return 'AI服务内部错误，请稍后重试或联系技术支持'
  }

  return error.message || '请求失败，请稍后重试'
}

function processSseLine(line, callbacks, context) {
  const trimmedLine = line.trim()
  if (!trimmedLine || trimmedLine.startsWith('event:')) return false

  if (!trimmedLine.startsWith('data:')) return false

  const data = trimmedLine.slice(5).trim()
  if (!data || data === '[DONE]') return false

  try {
    const parsed = JSON.parse(data)
    const eventType = (parsed.type || '').toLowerCase().trim()
    const { onStart, onThinking, onSearching, onSources, onChunk, onFinish, onError } = callbacks
    const { sessionId, startTime } = context

    // 记录关键事件日志（不记录频繁的 chunk 事件避免刷屏）
    if (eventType !== 'chunk') {
      console.log(`[SSE] 收到事件: ${eventType}`, eventType === 'sources' ? `(${(parsed.sources || []).length} 条来源)` : '')
    }

    switch (eventType) {
      case 'start':
      case 'connected':
        onStart?.({
          type: eventType,
          message: parsed.message || '正在连接知识库...',
          timestamp: Date.now()
        })
        return false

      case 'thinking':
        onThinking?.({
          step: parsed.step || '',
          content: parsed.content || '正在思考...'
        })
        return false

      case 'searching':
        onSearching?.({
          step: parsed.step || '',
          collection: parsed.collection || ''
        })
        return false

      case 'sources':
        onSources?.({
          sources: parsed.sources || [],
          totalSources: (parsed.sources || []).length
        })
        return false

      case 'chunk': {
        const chunkContent = parsed.content || ''
        if (chunkContent) context.receivedContent += chunkContent
        onChunk?.({ content: chunkContent })
        return false
      }

      case 'finish':
      case 'result':
        onFinish?.({
          sessionId: parsed.session_id || sessionId,
          duration: Date.now() - startTime,
          answer: parsed.answer || '',
          sources: parsed.sources || [],
          citations: parsed.citations || [],
          images: parsed.images || [],
          metadata: parsed.metadata || {},
          complete: true
        })
        return true

      case 'error':
        onError?.(parsed.message || '服务器返回错误')
        return true

      default:
        if (parsed.content) {
          context.receivedContent += parsed.content
          onChunk?.({ content: parsed.content })
        }
        return false
    }
  } catch (e) {
    console.warn('[SSE] 解析行失败:', e.message, '原始数据:', data?.substring(0, 100))
    if (data && data !== '[DONE]') {
      onChunk?.({ content: data })
    }
    return false
  }
}

export const aiAPI = {
  sendMessage: async ({ message: messageContent, id, session_id, signal }, { onStart, onThinking, onSearching, onSources, onChunk, onFinish, onError }) => {
    const token = localStorage.getItem('token')

    if (!token) {
      onError?.('用户未登录，请先登录')
      return null
    }

    if (!messageContent || !messageContent.trim()) {
      onError?.('消息内容不能为空')
      return null
    }

    const requestId = id || `req_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
    const sessionId = session_id || `sess_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`

    const requestBody = {
      message: messageContent,
      id: requestId,
      session_id: sessionId
    }

    const startTime = Date.now()
    let hasReceivedData = false
    let receivedContent = ''
    let reader = null
    let finishCalled = false

    const callbacks = { onStart, onThinking, onSearching, onSources, onChunk, onFinish, onError }
    const context = { sessionId, startTime, receivedContent: '' }

    try {
      const response = await fetch(`${BASE_URL}/ai/chat/stream`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(requestBody),
        signal
      })

      if (!response.ok) {
        if (response.status === 401) {
          throw new Error('用户未登录或登录已过期，请重新登录')
        } else if (response.status === 403) {
          throw new Error('权限不足，无法访问该资源')
        } else {
          throw new Error(`服务器错误 (${response.status}): ${response.statusText}`)
        }
      }

      reader = response.body.getReader()
      const decoder = new TextDecoder()
      let buffer = ''

      while (true) {
        const { done, value } = await reader.read()

        if (done) {
          if (buffer.trim()) {
            const lines = buffer.split('\n')
            for (const line of lines) {
              const finished = processSseLine(line, callbacks, context)
              if (finished) {
                finishCalled = true
                break
              }
            }
          }

          if (!finishCalled) {
            finishCalled = true
            onFinish?.({
              sessionId,
              duration: Date.now() - startTime,
              complete: true
            })
          }
          break
        }

        hasReceivedData = true
        buffer += decoder.decode(value, { stream: true })
        const lines = buffer.split('\n')
        buffer = lines.pop() || ''

        let shouldBreak = false
        for (const line of lines) {
          const finished = processSseLine(line, callbacks, context)
          if (finished) {
            finishCalled = true
            shouldBreak = true
          }
        }

        if (shouldBreak) {
          try {
            await reader.cancel()
          } catch (e) {
            // ignore
          }
          break
        }
      }

      if (finishCalled && reader) {
        try {
          await reader.cancel()
        } catch (e) {
          // ignore
        }
        reader = null
      } else if (reader) {
        try {
          reader.releaseLock()
        } catch (e) {
          // ignore
        }
      }

      return null
    } catch (error) {
      if (reader) {
        try {
          reader.cancel()
        } catch (e) {
          // ignore
        }
        reader = null
      }

      const contentSoFar = context.receivedContent || receivedContent

      if (error.name === 'AbortError') {
        if (contentSoFar.length > 0) {
          if (!finishCalled) {
            finishCalled = true
            onFinish?.({
              sessionId,
              duration: Date.now() - startTime,
              answer: contentSoFar,
              sources: [],
              citations: [],
              complete: true,
              interrupted: true
            })
          }
        } else {
          onError?.('请求已取消')
        }
      } else if (hasReceivedData && contentSoFar.length > 0) {
        if (!finishCalled) {
          finishCalled = true
          onFinish?.({
            sessionId,
            duration: Date.now() - startTime,
            answer: contentSoFar,
            sources: [],
            citations: [],
            complete: true,
            interrupted: true
          })
        }
      } else if (hasReceivedData) {
        if (!finishCalled) {
          onError?.('AI回答生成中断，服务器在处理过程中断开了连接，请稍后重试。')
        }
      } else if (error.message === 'Failed to fetch' || error.message?.includes('network') || error.message?.includes('Network') || error.message?.includes('fetch')) {
        if (signal && signal.aborted) {
          onError?.('请求已取消')
        } else {
          onError?.(getNetworkErrorMessage(error))
        }
      } else {
        onError?.(getApiErrorMessage(error))
      }
      return null
    }
  },

  /**
   * 中断流式问答 - 通知后端清理资源
   * POST /api/ai/chat/stop?sessionId=xxx
   */
  stopStream: async (sessionId) => {
    const token = localStorage.getItem('token')
    if (!token) throw new Error('用户未登录')
    if (!sessionId) {
      console.warn('[aiAPI] stopStream: sessionId 为空，跳过调用后端停止接口')
      return null
    }
    try {
      const response = await fetch(`${BASE_URL}/ai/chat/stop?sessionId=${encodeURIComponent(sessionId)}`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })
      const result = await response.json()
      console.log('[aiAPI] 中断问答响应:', result)
      return result
    } catch (error) {
      console.warn('[aiAPI] 调用中断接口失败（不影响前端本地停止）:', error.message)
      return null
    }
  },

  getSessions: async (params = {}) => {
    const token = localStorage.getItem('token')

    if (!token) {
      throw new Error('用户未登录')
    }

    const { page = 1, pageSize = 10 } = params

    try {
      const response = await fetch(`${BASE_URL}/ai/sessions?page=${page}&pageSize=${pageSize}`, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      })

      if (!response.ok) {
        if (response.status === 401) {
          throw new Error('用户未登录或登录已过期')
        } else if (response.status === 403) {
          throw new Error('权限不足')
        } else {
          throw new Error(`获取会话列表失败 (${response.status})`)
        }
      }

      const result = await response.json()

      if (result.success === false) {
        throw new Error(result.message || '获取会话列表失败')
      }

      return result
    } catch (error) {
      throw error
    }
  },

  getSessionDetail: async (sessionId, params = {}) => {
    const token = localStorage.getItem('token')

    if (!token) {
      throw new Error('用户未登录')
    }

    if (!sessionId) {
      throw new Error('会话ID不能为空')
    }

    const { page = 1, pageSize = 20 } = params

    try {
      const response = await fetch(`${BASE_URL}/ai/session/${encodeURIComponent(sessionId)}?page=${page}&pageSize=${pageSize}`, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      })

      if (!response.ok) {
        if (response.status === 401) {
          throw new Error('用户未登录或登录已过期')
        } else if (response.status === 403) {
          throw new Error('无权访问该会话')
        } else if (response.status === 404) {
          throw new Error('会话不存在')
        } else {
          throw new Error(`获取会话详情失败 (${response.status})`)
        }
      }

      const result = await response.json()

      if (result.success === false) {
        throw new Error(result.message || '获取会话详情失败')
      }

      return result
    } catch (error) {
      throw error
    }
  },

  getMessageReferences: async (messageId) => {
    const token = localStorage.getItem('token')

    if (!token) {
      throw new Error('用户未登录')
    }

    if (!messageId) {
      throw new Error('消息ID不能为空')
    }

    try {
      const response = await fetch(`${BASE_URL}/ai/message/${messageId}/references`, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      })

      if (!response.ok) {
        if (response.status === 401) {
          throw new Error('用户未登录或登录已过期')
        } else if (response.status === 403) {
          throw new Error('权限不足')
        } else if (response.status === 404) {
          throw new Error('消息不存在')
        } else {
          throw new Error(`获取引用信息失败 (${response.status})`)
        }
      }

      const result = await response.json()

      if (result.success === false) {
        throw new Error(result.message || '获取引用信息失败')
      }

      return result
    } catch (error) {
      throw error
    }
  },

  getSessionReferences: async (sessionId) => {
    const token = localStorage.getItem('token')

    if (!token) {
      throw new Error('用户未登录')
    }

    if (!sessionId) {
      throw new Error('会话ID不能为空')
    }

    try {
      const response = await fetch(`${BASE_URL}/ai/session/${encodeURIComponent(sessionId)}/references`, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      })

      if (!response.ok) {
        if (response.status === 401) {
          throw new Error('用户未登录或登录已过期')
        } else if (response.status === 403) {
          throw new Error('无权访问该会话')
        } else if (response.status === 404) {
          throw new Error('会话不存在')
        } else {
          throw new Error(`获取会话引用失败 (${response.status})`)
        }
      }

      const result = await response.json()

      if (result.success === false) {
        throw new Error(result.message || '获取会话引用失败')
      }

      return result
    } catch (error) {
      throw error
    }
  },

  deleteSession: async (sessionId) => {
    const token = localStorage.getItem('token')

    if (!token) {
      throw new Error('用户未登录')
    }

    if (!sessionId) {
      throw new Error('会话ID不能为空')
    }

    try {
      const response = await fetch(`${BASE_URL}/ai/session/${encodeURIComponent(sessionId)}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      })

      if (!response.ok) {
        if (response.status === 401) {
          throw new Error('用户未登录或登录已过期')
        } else if (response.status === 403) {
          throw new Error('无权删除该会话')
        } else if (response.status === 404) {
          throw new Error('会话不存在')
        } else {
          throw new Error(`删除会话失败 (${response.status})`)
        }
      }

      const result = await response.json()

      if (result.success === false) {
        throw new Error(result.message || '删除会话失败')
      }

      return result
    } catch (error) {
      throw error
    }
  },

  batchDeleteSessions: async (sessionIds) => {
    const token = localStorage.getItem('token')

    if (!token) {
      throw new Error('用户未登录')
    }

    if (!sessionIds || !Array.isArray(sessionIds) || sessionIds.length === 0) {
      throw new Error('会话ID列表不能为空')
    }

    try {
      const response = await fetch(`${BASE_URL}/ai/sessions`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(sessionIds)
      })

      if (!response.ok) {
        if (response.status === 401) {
          throw new Error('用户未登录或登录已过期')
        } else if (response.status === 403) {
          throw new Error('无权删除部分会话')
        } else {
          throw new Error(`批量删除会话失败 (${response.status})`)
        }
      }

      const result = await response.json()

      if (result.success === false) {
        throw new Error(result.message || '批量删除会话失败')
      }

      return result
    } catch (error) {
      throw error
    }
  }
}

export default aiAPI
