import { v4 as uuidv4 } from 'uuid'
import mime from 'mime'
import { createCustomOSSUploader } from '@bty/uploader'
import { createFileUploadRecord } from '@apis/mindnote/next-agent-chat'
import { getOssSignatureUrl, getSTSToken } from '@apis/mindnote/oss'

export const ACCEPT_FILE_TYPE_LIST = [
  '.png',
  '.jpg',
  '.jpeg',
  '.gif',
  '.bmp',
  '.webp',
]

function getMimeByAcceptList(filename: string): string | undefined {
  const ext = `.${(filename.split('.').pop() || '').toLowerCase()}`
  if (!ext) return undefined
  const map: Record<string, string> = {
    '.png': 'image/png',
    '.jpg': 'image/jpeg',
    '.jpeg': 'image/jpeg',
    '.gif': 'image/gif',
    '.bmp': 'image/bmp',
    '.webp': 'image/webp',
  }
  if (ACCEPT_FILE_TYPE_LIST.includes(ext)) {
    return map[ext]
  }
  return undefined
}

export interface RcFile extends File {
  uid: string;
}


export interface MessageFile {
  uid?: string
  name: string
  type: string
  path?: string
  url?: string
  upload_file_id?: string
  byte_size?: number
  progress?: number
  uploadStatus?: 'pending' | 'success' | 'error'
}

interface UploadFile extends MessageFile {
  uid?: string
}
interface UploadResult {
  name: string,
  type: string,
  byte_size: number,
  url: string,
  upload_file_id: string
}
export const customUpload = async (params: {
  file: File
  onProgress?: (args: {
    progress: number
    file: RcFile
    uploadStatus: 'success' | 'error' | 'pending'
  }) => void,
  onFail?: (message?: any) => void
}): Promise<UploadResult | null> => {
  const { file, onProgress,onFail } = params
  const ossUploader = createCustomOSSUploader(getSTSToken)
  try {
    // 构建文件路径，参考 util.ts 中的格式
    const timestamp = new Date().valueOf()
    const uuid = uuidv4()
    const filePath = `super_agent/user_upload_file/${uuid}/_${timestamp}_${file.name}`
    // 上传文件到 OSS
    await ossUploader.multipartUpload({
      filePath,
      file,
      options: {
        headers: (() => {
          const contentType = getMimeByAcceptList(file.name)
          return {
            'Content-Type': contentType,
            'Content-Disposition': 'inline',
          } as Record<string, string>
        })(),
        progress(
          progress: number,
          ossFile: { file: RcFile },
          { status }: { status: number } = { status: 0 },
        ) {
          const uploadStatus =
            progress >= 1 ? (status === 200 ? 'success' : 'error') : 'pending'

          if (uploadStatus !== 'pending') {
            setTimeout(() => {
              onProgress?.({
                progress,
                file: ossFile?.file || file,
                uploadStatus,
              })
            }, 500)
          } else {
            onProgress?.({
              progress,
              file: ossFile?.file || file,
              uploadStatus,
            })
          }
        },
      },
    })

    const signatureUrl = await getOssSignatureUrl(filePath)

    // 获取文件类型
    const file_type =
      file.type || mime.getType(file.name) || 'application/octet-stream'

    // 只分割最后一个点，例如 'a.b.c' -> ['a.b', 'c']
    const lastDotIndex = file.name.lastIndexOf('.')
    const splitName =
      lastDotIndex !== -1
        ? [
            file.name.substring(0, lastDotIndex),
            file.name.substring(lastDotIndex + 1),
          ]
        : [file.name]
    const name = `${splitName[0]}-${Math.random().toString(36).substring(2, 5)}${splitName.length > 1 ? `.${splitName[1]}` : ''}`
    const res = await createFileUploadRecord({
      file_url: filePath || '',
      file_type: file.type || 'application/octet-stream',
      file_name: name,
      file_byte_size: file.size || 0,
      conversation_id: uuid,
    })

    // 构造返回的文件对象
    const result: UploadFile = {
      name,
      type: file_type,
      byte_size: file.size,
      url: signatureUrl,
      upload_file_id: res.file_upload_record_id,
    }
    return result as UploadResult
  } catch (error) {
    console.error('文件上传失败:', error)
    onFail && onFail(error)
    return null
  }
}
