import axios from 'axios'

// 统一使用相对路径，通过 Vite 代理转发到后端

// 删除记录的通用函数
export const deleteRecords = async (pagetype: string, names: string[]): Promise<{ success: boolean; message?: string }> => {
  try {
    if (!names || names.length === 0) {
      return { success: false, message: '未提供要删除的记录' }
    }
    
    const response = await axios.post(
      `/jingrow/bulk-delete`,
      { 
        pagetype: pagetype,
        names: names
      },
      {
        validateStatus: (status) => status === 200 || status === 207  // 允许207状态码
      }
    )
    
    const result = response.data
    // 207 状态码表示部分成功
    const isPartialSuccess = response.status === 207
    
    return { 
      success: !isPartialSuccess,
      message: result?.message || (isPartialSuccess ? '部分删除成功' : '删除完成')
    }
  } catch (error: any) {
    return { success: false, message: error.response?.data?.detail || error.message || '删除失败' }
  }
}

// 创建记录的通用函数
export const createRecord = async (pagetype: string, data: Record<string, any>): Promise<{ success: boolean; data?: any; message?: string }> => {
  try {
    const response = await axios.post(
      `/api/data/${pagetype}`, data)

    const message = response.data?.message
    return { success: true, data: message || response.data, message: 'Created successfully' }
  } catch (error: any) {
    return { success: false, message: error.response?.data?.message || error.message || '创建失败' }
  }
}

// 更新记录的通用函数
export const updateRecord = async (pagetype: string, name: string, data: Record<string, any>): Promise<{ success: boolean; data?: any; message?: string }> => {
  try {
    const response = await axios.put(
      `/api/data/${pagetype}/${name}`, data)

    const message = response.data?.message
    return { success: true, data: message || response.data, message: 'Updated successfully' }
  } catch (error: any) {
    return { success: false, message: error.response?.data?.message || error.message || '更新失败' }
  }
}

// 获取记录的通用函数
export const getRecord = async (pagetype: string, name: string): Promise<{ success: boolean; data?: any; message?: string }> => {
  try {
    const response = await axios.get(
      `/api/data/${pagetype}/${name}`)
    return { success: true, data: response.data.data }
  } catch (error: any) {
    return { success: false, message: error.response?.data?.message || error.message || '获取失败' }
  }
}

// 获取记录的附件列表
export const getRecordAttachments = async (pagetype: string, name: string): Promise<{ success: boolean; data?: any[]; message?: string }> => {
  try {
    const response = await axios.get(
      `/api/data/File`,
      {
        params: { 
          filters: JSON.stringify({
            attached_to_pagetype: pagetype,
            attached_to_name: name
          }),
          fields: JSON.stringify(['name', 'file_name', 'file_url', 'is_private'])
        }
      }
    )
    return { success: true, data: response.data.data || [] }
  } catch (error: any) {
    return { success: false, message: error.response?.data?.message || error.message || '获取附件失败' }
  }
}

// 上传附件
export const uploadAttachment = async (
  file: File, 
  pagetype: string, 
  docname: string, 
  isPrivate: boolean = false
): Promise<{ success: boolean; data?: any; message?: string }> => {
  try {
    const formData = new FormData()
    formData.append('file', file)
    formData.append('pagetype', pagetype)
    formData.append('docname', docname)
    formData.append('is_private', isPrivate ? '1' : '0')
    formData.append('folder', 'Home')
    
    const response = await axios.post(
      `/jingrow/upload_file`,
      formData,
      {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
    )
    
    return { success: true, data: response.data.message }
  } catch (error: any) {
    return { 
      success: false, 
      message: error.response?.data?.message || error.message || '上传附件失败' 
    }
  }
}

// 删除附件
export const deleteAttachment = async (attachmentName: string): Promise<{ success: boolean; message?: string }> => {
  try {
    await axios.delete(
      `/api/data/File/${attachmentName}`)
    return { success: true, message: '附件删除成功' }
  } catch (error: any) {
    return { success: false, message: error.response?.data?.message || error.message || '删除附件失败' }
  }
}

// 获取 Workspace 配置
export const getWorkspace = async (name: string): Promise<{ success: boolean; data?: any; message?: string }> => {
  return getRecord('Workspace', name)
}

// 获取记录总数的通用函数
export const getCount = async (pagetype: string): Promise<{ success: boolean; count?: number; message?: string }> => {
  try {
    const response = await axios.post(
      `/jingrow/get-count`,
      null,
      {
        params: {
          pagetype: pagetype
        }
      }
    )
    
    const count = response.data?.message
    return { success: true, count: count || 0 }
  } catch (error: any) {
    return { 
      success: false, 
      count: 0,
      message: error.response?.data?.detail || error.response?.data?.message || error.message || '获取记录总数失败' 
    }
  }
}

// 获取Local Job总数的专用函数 - 通过专用端点获取
export const getLocalJobCount = async (): Promise<{ success: boolean; count?: number; message?: string }> => {
  try {
    const response = await axios.get(
      `/jingrow/local-job-count`)
    
    const count = response.data?.count || 0
    return { 
      success: true, 
      count: count,
      message: '获取Local Job总数成功'
    }
  } catch (error: any) {
    return { 
      success: false, 
      count: 0,
      message: error.response?.data?.detail || error.response?.data?.message || error.message || '获取Local Job总数失败' 
    }
  }
}

// 获取记录列表的通用函数
export const getRecords = async (pagetype: string, filters: any[] = [], fields: string[] = [], orderBy: string = 'modified desc', limitStart: number = 0, limitPageLength: number = 20): Promise<{ success: boolean; data?: any[]; total?: number; message?: string }> => {
  try {
    const response = await axios.get(
      `/api/data/${pagetype}`,
      {
        params: {
          fields: JSON.stringify(fields),
          filters: JSON.stringify(filters),
          order_by: orderBy,
          limit_start: limitStart,
          limit_page_length: limitPageLength
        }
      }
    )
    
    const data = response.data
    if (data?.error) {
      const errorMsg = typeof data.error === 'object' ? JSON.stringify(data.error) : data.error
      throw new Error(errorMsg)
    }

    return {
      success: true,
      data: data?.data || [],
      total: data?.total || data?.data?.length || 0
    }
  } catch (error: any) {
    return { 
      success: false, 
      message: error.response?.data?.message || error.message || '获取记录列表失败' 
    }
  }
}

// 下载图片到本地
export const downloadImageToLocal = async (
  imageUrl: string, 
  filename?: string
): Promise<{ success: boolean; local_path?: string; error?: string }> => {
  try {
    const response = await axios.post(
      `/jingrow.utils.fs.download_image_to_local`,
      {
        image_url: imageUrl,
        filename: filename
      },
      {
        timeout: 30000
      }
    )
    
    if (response.data?.data?.success) {
      return {
        success: true,
        local_path: response.data.data.local_path
      }
    } else {
      return {
        success: false,
        error: response.data?.data?.error || '下载失败'
      }
    }
  } catch (error: any) {
    return {
      success: false,
      error: error.response?.data?.message || error.message || '下载失败'
    }
  }
}

// 上传文件到 Jingrow 服务器
export const uploadFileToJingrow = async (
  file: File, 
  attachedToPagetype?: string, 
  attachedToName?: string, 
  attachedToField?: string
): Promise<{ success: boolean; file_url?: string; file_name?: string; local_path?: string; error?: string }> => {
  try {
    const formData = new FormData()
    formData.append('file', file)
    formData.append('file_name', file.name)
    formData.append('is_private', '0')
    
    // 如果有关联记录，添加到请求数据中
    if (attachedToPagetype && attachedToName) {
      formData.append('pagetype', attachedToPagetype)
      formData.append('docname', attachedToName)
    }
    
    if (attachedToField) {
      formData.append('fieldname', attachedToField)
    }

    const response = await axios.post(
      `/jingrow/upload_file`,
      formData,
      {
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        timeout: 30000
      }
    )

    if (response.status === 200) {
      const result = response.data
      
      // 检查session是否过期
      if (result.session_expired) {
        return { success: false, error: 'Session已过期，请重新登录' }
      }
      
      if (result.message) {
        const uploadResult: { success: boolean; file_url: string; file_name: string; local_path?: string } = {
          success: true,
          file_url: result.message.file_url,
          file_name: result.message.file_name
        }
        
        // 上传成功后，自动下载图片到本地
        const downloadResult = await downloadImageToLocal(result.message.file_url, result.message.file_name)
        if (downloadResult.success) {
          uploadResult.local_path = downloadResult.local_path
        }
        
        return uploadResult
      } else {
        return { success: false, error: 'API响应格式错误' }
      }
    } else {
      return { success: false, error: `API请求失败 (HTTP ${response.status}): ${response.statusText}` }
    }
  } catch (error: any) {
    return { 
      success: false, 
      error: error.response?.data?.message || error.message || '上传文件失败' 
    }
  }
}

