const ALLOWED_EXTENSIONS = [
  '.docx', '.pdf', '.txt', '.md',
  '.xlsx', '.pptx', '.doc', '.xls', '.ppt'
]

const MAX_FILE_SIZE = 50 * 1024 * 1024
const MAX_FILENAME_LENGTH = 200
const FORBIDDEN_CHARS = /[\\/:*?"<>|]/

function getExtension(filename) {
  const dotIndex = filename.lastIndexOf('.')
  return dotIndex === -1 ? '' : filename.slice(dotIndex).toLowerCase()
}

export function validateFile(file) {
  const errors = []
  const ext = getExtension(file.name)

  if (!ext || !ALLOWED_EXTENSIONS.includes(ext)) {
    errors.push(`不支持的文件类型: ${ext || '(无扩展名)'}`)
  }

  if (file.size > MAX_FILE_SIZE) {
    errors.push(`文件大小超出限制 (最大 ${formatFileSize(MAX_FILE_SIZE)})`)
  }

  if (file.name.length > MAX_FILENAME_LENGTH) {
    errors.push(`文件名过长 (${file.name.length}/${MAX_FILENAME_LENGTH} 字符)`)
  }

  if (FORBIDDEN_CHARS.test(file.name)) {
    errors.push('文件名包含非法字符: \\ / : * ? " < > |')
  }

  return {
    valid: errors.length === 0,
    errors,
    ext,
    size: file.size
  }
}

export function validateFiles(files) {
  const validFiles = []
  const invalidFiles = []

  for (const file of files) {
    const result = validateFile(file)
    if (result.valid) {
      validFiles.push(file)
    } else {
      invalidFiles.push({ file, errors: result.errors })
    }
  }

  return { validFiles, invalidFiles }
}

export function formatFileSize(bytes) {
  if (bytes === 0) return '0B'

  const units = ['B', 'KB', 'MB', 'GB']
  let unitIndex = 0
  let size = bytes

  while (size >= 1024 && unitIndex < units.length - 1) {
    size /= 1024
    unitIndex++
  }

  const decimalPlaces = unitIndex === 0 ? 0 : size % 1 === 0 ? 0 : 1
  return `${size.toFixed(decimalPlaces)}${units[unitIndex]}`
}

export function getFileTypeLabel(ext) {
  const extLower = ext.toLowerCase()

  if (['.docx', '.doc'].includes(extLower)) return 'Word文档'
  if (extLower === '.pdf') return 'PDF文档'
  if (['.xlsx', '.xls'].includes(extLower)) return 'Excel表格'
  if (['.pptx', '.ppt'].includes(extLower)) return 'PowerPoint演示'
  if (extLower === '.txt') return '文本文件'
  if (extLower === '.md') return 'Markdown文档'

  return '未知类型'
}

export function getFileIconName(ext) {
  const extLower = ext.toLowerCase()

  if (['.docx', '.doc'].includes(extLower)) return 'FileWordOutlined'
  if (extLower === '.pdf') return 'FilePdfOutlined'
  if (['.xlsx', '.xls'].includes(extLower)) return 'FileExcelOutlined'
  if (['.pptx', '.ppt'].includes(extLower)) return 'FilePptOutlined'
  if (['.txt', '.md'].includes(extLower)) return 'FileTextOutlined'

  return 'FileOutlined'
}

export default {
  ALLOWED_EXTENSIONS,
  MAX_FILE_SIZE,
  MAX_FILENAME_LENGTH,
  validateFile,
  validateFiles,
  formatFileSize,
  getFileTypeLabel,
  getFileIconName
}
