export function normalizeText(value) {
  return String(value ?? '').trim()
}

export function filterRows(rows, keyword) {
  const target = normalizeText(keyword).toLowerCase()
  if (!target) return rows
  return rows.filter((item) => {
    const merged = [
      item.title,
      item.subtitle,
      item.accountName,
      item.owner,
      item.sheetName,
      ...(item.tags || []),
    ]
      .join(' ')
      .toLowerCase()
    return merged.includes(target)
  })
}

export function attachSheetName(sheets = []) {
  return sheets.map((sheet) => ({
    ...sheet,
    rows: (sheet.rows || []).map((row) => ({ ...row, sheetName: sheet.name })),
  }))
}

export function flattenRows(sheets = []) {
  return attachSheetName(sheets).flatMap((sheet) => sheet.rows || [])
}

export function buildDuplicates(rows) {
  // 构建完整路径需要包含所有数据（文件和文件夹）
  const allItems = rows
  // 只检测文件类型，排除文件夹
  const fileRows = rows.filter(item => item.type !== 'folder')
  
  const map = new Map()

  fileRows.forEach((item) => {
    // 使用更智能的标题标准化：去除空格、标点符号，统一小写
    const key = normalizeTitleForComparison(item.title)
    if (!key) return
    if (!map.has(key)) {
      map.set(key, [])
    }
    map.get(key).push(item)
  })

  return [...map.entries()]
    .filter(([, list]) => list.length > 1)
    .map(([, list], index) => ({
      id: `duplicate-${index + 1}`,
      title: list[0].title,
      locations: list.map((item, idx) => {
        // 构建完整路径：网盘名称 / 父文件夹路径 / 资源库
        // 注意：传入 allItems 而不是 fileRows，因为需要查找文件夹
        const parentPath = buildParentPath(item, allItems)
        const location = `${item.sheetName}${parentPath} / ${item.accountName}`
        
        // 如果同一个位置有多个重复文件，添加序号区分
        const sameLocationCount = list.filter((other, otherIdx) => {
          if (otherIdx === idx) return false
          const otherParentPath = buildParentPath(other, allItems)
          const otherLocation = `${other.sheetName}${otherParentPath} / ${other.accountName}`
          return otherLocation === location
        }).length
        
        return sameLocationCount > 0 ? `${location} (副本${sameLocationCount + 1})` : location
      }),
    }))
}

// 标准化标题用于比较（去除空格、标点符号等）
function normalizeTitleForComparison(title) {
  return normalizeText(title)
    .toLowerCase()
    .replace(/[\s\-_.]+/g, '') // 去除所有空格、连字符、下划线、点号
    .replace(/[\(\)\[\]【】《》]/g, '') // 去除各种括号
}

// 构建父文件夹路径
function buildParentPath(item, allItems) {
  if (!item.parentId) return ''
  
  const pathParts = []
  let currentId = item.parentId
  const visited = new Set() // 防止循环引用
  
  // 向上查找所有父文件夹
  while (currentId && !visited.has(currentId)) {
    visited.add(currentId)
    const parent = allItems.find(i => i.id === currentId && i.type === 'folder')
    if (!parent) break
    pathParts.unshift(parent.title)
    currentId = parent.parentId
  }
  
  return pathParts.length ? ' / ' + pathParts.join(' / ') : ''
}

export function createLoginLog(device = '未知设备', ip = '127.0.0.1', options = {}) {
  const hashSeed = String(options.hashSeed || `${Date.now()}-${Math.random()}`)
  const hash = hashSeed
    .split('')
    .reduce((acc, char) => ((acc << 5) - acc + char.charCodeAt(0)) | 0, 0)
    .toString(16)
    .replace('-', '')
    .slice(0, 8)

  return {
    id: options.id ? `log-${options.id}` : `log-${Date.now()}`,
    time: options.time || new Date().toLocaleString('zh-CN', { hour12: false }),
    device,
    ip,
    hash,
    username: normalizeText(options.username) || '未知账号',
    result: normalizeText(options.result) || 'success',
    userId: options.userId ?? null,
    rawUserAgent: normalizeText(options.rawUserAgent) || device,
    failReason: normalizeText(options.failReason) || '',
  }
}

export function createRecord(record = {}, fallbackSheetName = '') {
  const normalizedTags = Array.isArray(record.tags)
    ? record.tags.map((item) => normalizeText(item)).filter(Boolean)
    : normalizeText(record.tags)
        .split(/[，,]/)
        .map((item) => item.trim())
        .filter(Boolean)

  return {
    id: record.id || `record-${Date.now()}`,
    title: normalizeText(record.title),
    subtitle: normalizeText(record.subtitle),
    accountName: normalizeText(record.accountName),
    owner: normalizeText(record.owner),
    updatedAt: normalizeText(record.updatedAt),
    status: normalizeText(record.status) || '正常',
    poster: normalizeText(record.poster),
    tags: normalizedTags,
    score: Number(record.score) || 0,
    sheetName: normalizeText(record.sheetName) || fallbackSheetName,
    parentId: record.parentId || null, // 父文件夹ID
    type: record.type || 'file', // 'folder' 或 'file'
    originalName: normalizeText(record.originalName),
    description: normalizeText(record.description),
    category: normalizeText(record.category),
    driveId: record.driveId ?? null,
    folderId: record.folderId ?? null,
    minioUrl: normalizeText(record.minioUrl),
    mimeType: normalizeText(record.mimeType),
    extension: normalizeText(record.extension),
    fileSize: Number(record.fileSize) || 0,
    createdAt: normalizeText(record.createdAt),
  }
}

export function mapMovieToRecord(movie = {}, fallbackSheetName = '') {
  return createRecord({
    id: movie.id,
    title: movie.title,
    subtitle: movie.subtitle || '',
    accountName: movie.resourceLibrary || '',
    owner: movie.maintainer || '',
    updatedAt: movie.updateTime || '',
    status: movie.status === 'deleted' ? '已删除' : '正常',
    poster: movie.posterUrl || '',
    tags: movie.tags,
    score: Number(movie.rating) || 0,
    sheetName: fallbackSheetName,
    parentId: movie.folderId || null,
    type: 'file',
    category: movie.category,
    description: movie.description || '',
  }, fallbackSheetName)
}

// 创建文件夹
export function createFolder(folder = {}, fallbackSheetName = '') {
  return {
    id: folder.id || `folder-${Date.now()}`,
    title: normalizeText(folder.title),
    parentId: folder.parentId || null,
    sheetName: normalizeText(folder.sheetName) || fallbackSheetName,
    type: 'folder',
    children: [], // 子项（文件夹或文件）
    createdAt: folder.createdAt || new Date().toLocaleString('zh-CN', { hour12: false }),
  }
}

// 构建树形结构
export function buildTree(items = []) {
  const map = new Map()
  const roots = []

  // 创建映射
  items.forEach((item) => {
    map.set(item.id, { ...item, children: [] })
  })

  // 构建树
  items.forEach((item) => {
    const node = map.get(item.id)
    if (item.parentId && map.has(item.parentId)) {
      map.get(item.parentId).children.push(node)
    } else {
      roots.push(node)
    }
  })

  return roots
}
