import axios from 'axios'
import { t } from '@/shared/i18n'

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

// 通用的 API 调用函数 - 兼容 Jingrow 的 jingrow.call 风格
export const api = {
  call: async (method: string, args?: Record<string, any>): Promise<any> => {
    try {
      const response = await axios.post('/api/action/' + method, args || {})
      return response.data
    } catch (error: any) {
      throw new Error(error.response?.data?.message || error.message || 'API call failed')
    }
  }
}

export const deleteRecord = async (pagetype: string, name: string): Promise<{ success: boolean; message?: string }> => {
  try {
    await api.call('jingrow.client.delete', {
      pagetype: pagetype,
      name: name
    })
    
    return { 
      success: true,
      message: t('Deleted successfully')
    }
  } catch (error: any) {
    return { success: false, message: error.response?.data?.message || error.message || t('Deletion failed') }
  }
}

export const deleteRecords = async (pagetype: string, names: string[]): Promise<{ success: boolean; message?: string }> => {
  if (!names || names.length === 0) {
    return { success: false, message: t('No records provided for deletion') }
  }
  
  let succeeded = 0
  let failed = 0
  
  // 直接调用 jingrow.client.delete RPC 接口，避免 REST API 层包装
  for (const name of names) {
    try {
      await api.call('jingrow.client.delete', {
        pagetype: pagetype,
        name: name
      })
      succeeded++
    } catch {
      failed++
    }
  }
  
  if (failed === 0) {
    return { success: true, message: t('Successfully deleted {count} records', { count: succeeded }) }
  } else if (succeeded > 0) {
    return { success: true, message: t('Deleted {succeeded} of {total} records, {failed} failed', { succeeded, total: names.length, failed }) }
  } else {
    return { success: false, message: t('Deletion failed') }
  }
}

// 创建记录的通用函数
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 || '获取失败' }
  }
}

// 获取带__onload数据的记录（会调用文档的onload方法）
// 用于需要__onload数据的场景，如User pagetype的all_modules
export const getRecordWithOnload = async (pagetype: string, name: string): Promise<{ success: boolean; data?: any; message?: string }> => {
  try {
    // 使用getdoc RPC方法，它会调用onload方法并返回__onload数据
    const result = await api.call('jingrow.desk.form.load.getdoc', { pagetype, name })
    
    // getdoc返回的是{ docs: [pg], docinfo: {...} }
    const pg = result.docs?.[0]
    if (pg) {
      return { success: true, data: pg }
    } else {
      return { success: false, message: '文档不存在' }
    }
  } catch (error: any) {
    return { success: false, message: error.message || '获取失败' }
  }
}

// 获取PageType元数据的专用函数 - 通过 REST API v2 获取完整元数据
export const getPageTypeMeta = async (pagetype: string): Promise<{ success: boolean; data?: any; message?: string }> => {
  try {
    const response = await axios.get(
      `/api/v2/pagetype/${pagetype}/meta`
    )

    const meta = response.data?.data
    if (meta) {
      return { success: true, data: meta }
    } else {
      return { success: false, message: '获取元数据失败' }
    }
  } 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('doctype', pagetype)
    formData.append('docname', docname)
    formData.append('is_private', isPrivate ? '1' : '0')
    formData.append('folder', 'Home')
    
    const response = await axios.post(
      '/api/action/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)
}

// Save Workspace layout
export const saveWorkspaceLayout = async (
  title: string, 
  isPublic: boolean, 
  content: any[],
  newWidgets: any = {}
): Promise<{ success: boolean; data?: any; message?: string }> => {
  try {
    const response = await axios.post(
      '/api/action/jingrow.desk.pagetype.workspace.workspace.save_page',
      {
        title,
        public: isPublic ? 1 : 0,
        new_widgets: JSON.stringify(newWidgets),
        blocks: JSON.stringify(content)
      }
    )
    return { success: true, data: response.data?.message, message: 'Workspace saved successfully' }
  } catch (error: any) {
    console.error('Save workspace error:', error.response?.data)
    return { 
      success: false, 
      message: error.response?.data?.exception || error.response?.data?.message || error.message || 'Failed to save workspace' 
    }
  }
}

// 获取记录总数的通用函数
export const getCount = async (pagetype: string): Promise<{ success: boolean; count?: number; message?: string }> => {
  try {
    const response = await axios.get(
      '/api/action/jingrow.client.get_count',
      {
        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?.message || error.message || '获取记录总数失败' 
    }
  }
}

// 获取Local Job总数的专用函数 - 通过专用端点获取
export const getLocalJobCount = async (): Promise<{ success: boolean; count?: number; message?: string }> => {
  try {
    const response = await axios.get(
      `/api/action/jingrow.core.pagetype.local_job.local_job.get_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 || '获取记录列表失败' 
    }
  }
}

// 上传文件到 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('doctype', attachedToPagetype)
      formData.append('docname', attachedToName)
    }
    
    if (attachedToField) {
      formData.append('fieldname', attachedToField)
    }

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

    if (response.status === 200) {
      const result = response.data
      
      if (result.message) {
        return {
          success: true,
          file_url: result.message.file_url,
          file_name: result.message.file_name
        }
      } 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 || '上传文件失败' 
    }
  }
}

// 搜索记录（支持翻译搜索）- 使用后端search_widget API
// 对于标记了translated_pagetype的PageType，后端会自动处理翻译搜索
export const searchWidget = async (
  pagetype: string,
  txt: string,
  options?: {
    searchfield?: string
    page_length?: number
    start?: number
    filters?: any[] | Record<string, any>
    reference_pagetype?: string
    ignore_user_permissions?: boolean
  }
): Promise<{ success: boolean; data?: any[]; message?: string }> => {
  try {
    const params: Record<string, any> = {
      pagetype,
      txt: txt || '',
      page_length: options?.page_length || 20,
      start: options?.start || 0,
      as_dict: 1  // 返回字典格式，而不是数组格式
    }
    
    if (options?.searchfield) {
      params.searchfield = options.searchfield
    }
    
    if (options?.filters) {
      params.filters = typeof options.filters === 'string' 
        ? options.filters 
        : JSON.stringify(options.filters)
    }
    
    if (options?.reference_pagetype) {
      params.reference_pagetype = options.reference_pagetype
    }
    
    if (options?.ignore_user_permissions !== undefined) {
      params.ignore_user_permissions = options.ignore_user_permissions ? 1 : 0
    }
    
    const response = await axios.get('/api/action/jingrow.desk.search.search_widget', {
      params
    })
    
    return {
      success: true,
      data: response.data?.message || []
    }
  } catch (error: any) {
    return {
      success: false,
      message: error.response?.data?.message || error.message || '搜索失败'
    }
  }
}

