import axios from 'axios'
import { get_session_api_headers } from './auth'

const jingrowServerUrl = import.meta.env.VITE_JINGROW_SERVER_URL || ''

// 删除记录的通用函数
export const deleteRecords = async (pagetype: string, names: string[]): Promise<{ success: boolean; message?: string }> => {
  try {
    const results = []
    const failed = []
    
    // 循环调用单个删除接口
    for (const name of names) {
      try {
        await axios.post(
          `${jingrowServerUrl}/api/action/jingrow.client.delete`,
          { 
            pagetype: pagetype,
            name: name 
          },
          {
            headers: get_session_api_headers(),
            withCredentials: true
          }
        )
        results.push(name)
      } catch (error: any) {
        failed.push(name)
      }
    }
    
    if (failed.length === 0) {
      return { success: true, message: `成功删除 ${results.length} 条记录` }
    } else if (results.length > 0) {
      return { success: false, message: `部分删除成功：${results.length} 条成功，${failed.length} 条失败` }
    } else {
      return { success: false, message: '删除失败' }
    }
  } catch (error: any) {
    return { success: false, message: 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,
      {
        headers: get_session_api_headers(),
        withCredentials: true
      }
    )

    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,
      {
        headers: get_session_api_headers(),
        withCredentials: true
      }
    )

    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}`,
      {
        headers: get_session_api_headers(),
        withCredentials: true
      }
    )
    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'])
        },
        headers: get_session_api_headers(),
        withCredentials: true
      }
    )
    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(
      `${jingrowServerUrl}/api/action/upload_file`,
      formData,
      {
        headers: {
          ...get_session_api_headers(),
          'Content-Type': 'multipart/form-data'
        },
        withCredentials: true
      }
    )
    
    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}`,
      {
        headers: get_session_api_headers(),
        withCredentials: true
      }
    )
    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.get(
      `${jingrowServerUrl}/api/action/jingrow.client.get_count`,
      {
        params: {
          pagetype: pagetype
        },
        headers: get_session_api_headers(),
        withCredentials: true
      }
    )
    
    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(
      `${jingrowServerUrl}/api/action/jingrow.core.pagetype.local_job.local_job.get_local_job_count`,
      {
        headers: get_session_api_headers(),
        withCredentials: true
      }
    )
    
    const count = response.data?.message || 0
    return { 
      success: true, 
      count: count,
      message: '获取Local Job总数成功'
    }
  } catch (error: any) {
    return { 
      success: false, 
      count: 0,
      message: 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
        },
        headers: get_session_api_headers(),
        withCredentials: true
      }
    )
    
    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 getFieldSelectOptions = async (pagetype: string, fieldname: string): Promise<string[]> => {
  try {
    const res = await axios.post(
      `${jingrowServerUrl}/api/action/jingrow.ai.utils.utils.get_field_select_options`,
      { pagetype, fieldname },
      { headers: get_session_api_headers(), withCredentials: true }
    )
    return res.data?.message?.options || []
  } catch (error: any) {
    return []
  }
}

// 下载图片到本地
export const downloadImageToLocal = async (
  imageUrl: string, 
  filename?: string
): Promise<{ success: boolean; local_path?: string; error?: string }> => {
  try {
    const response = await axios.post(
      `/jingrow/jingrow.utils.fs.download_image_to_local`,
      {
        image_url: imageUrl,
        filename: filename
      },
      {
        headers: get_session_api_headers(),
        withCredentials: true,
        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(
      `${jingrowServerUrl}/api/action/upload_file`,
      formData,
      {
        headers: {
          ...get_session_api_headers(),
          'Content-Type': 'multipart/form-data'
        },
        withCredentials: true,
        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 || '上传文件失败' 
    }
  }
}
