import axios from 'axios'

const API_BASE_URL = 'http://localhost:8001'

const apiClient = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json',
  },
})

export const api = {
  // 上传文件
  uploadFile: async (file) => {
    const formData = new FormData()
    formData.append('file', file)
    const response = await axios.post(`${API_BASE_URL}/api/upload`, formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
    return response.data
  },

  // 执行OCR
  performOCR: async (fileId) => {
    const response = await apiClient.post(`/api/ocr/${fileId}`)
    return response.data
  },

  // 分析报告
  analyzeReport: async (fileId) => {
    const response = await apiClient.post(`/api/analyze/${fileId}`)
    return response.data
  },

  // 整合报告
  integrateReports: async (fileIds) => {
    const response = await apiClient.post('/api/integrate', fileIds)
    return response.data
  },

  // 获取所有报告
  getReports: async () => {
    const response = await apiClient.get('/api/reports')
    return response.data
  },

  // 获取报告详情
  getReportDetail: async (fileId) => {
    const response = await apiClient.get(`/api/report/${fileId}`)
    return response.data
  },

  // 删除报告
  deleteReport: async (fileId) => {
    const response = await apiClient.delete(`/api/report/${fileId}`)
    return response.data
  },

  // 生成PDF报告
  generatePDF: async (fileId) => {
    const response = await apiClient.post(`/api/report/${fileId}/pdf`)
    return response.data
  },

  // 下载PDF报告
  downloadPDF: (fileId) => {
    window.open(`${API_BASE_URL}/api/report/${fileId}/pdf/download`, '_blank')
  },

  // 批量上传并生成综合报告
  generateComprehensiveReport: async (files, patientName = '患者') => {
    const formData = new FormData()
    
    // 添加所有文件
    files.forEach(file => {
      formData.append('files', file)
    })
    
    // 添加患者姓名
    formData.append('patient_name', patientName)
    
    const response = await axios.post(
      `${API_BASE_URL}/api/comprehensive-report`,
      formData,
      {
        headers: { 'Content-Type': 'multipart/form-data' }
      }
    )
    return response.data
  },

  // 下载综合报告
  downloadComprehensiveReport: (pdfFilename) => {
    window.open(`${API_BASE_URL}/api/comprehensive-report/download/${pdfFilename}`, '_blank')
  },
}
