import {
  isActionableRiskFlag,
  isRiskSummaryWithRisk,
  normalizeRiskFlagTone
} from './riskFlags.js'
import { canViewRiskForContext } from './riskVisibility.js'

export const ARCHIVE_FILTER_ALL = 'all'

// 按当前查看者可见性过滤风险 flag，确保列表与详情页对同一用户展示一致的风险口径。
// viewerOptions 为空时（如未提供用户上下文）原样返回，保持向后兼容。
function filterRiskFlagsForViewer(riskFlags, viewerOptions) {
  const flags = Array.isArray(riskFlags) ? riskFlags : []
  if (!viewerOptions || !viewerOptions.request) {
    return flags
  }
  return flags.filter((flag) => {
    if (!isActionableRiskFlag(flag)) {
      return false
    }
    if (flag && typeof flag === 'object') {
      return canViewRiskForContext(flag, viewerOptions)
    }
    return true
  })
}

export function countClaimRisks(riskFlags, riskSummary, viewerOptions) {
  let count = 0

  const visibleFlags = filterRiskFlagsForViewer(riskFlags, viewerOptions)
  for (const flag of visibleFlags) {
    if (!isActionableRiskFlag(flag)) {
      continue
    }

    if (!flag || typeof flag !== 'object') {
      count += 1
      continue
    }

    const points = Array.isArray(flag.points)
      ? flag.points.map((point) => String(point || '').trim()).filter(Boolean)
      : []

    if (points.length) {
      count += points.length
      continue
    }

    const message = String(
      flag.message || flag.reason || flag.summary || flag.label || flag.description || flag.title || ''
    ).trim()

    if (message) {
      count += 1
    }
  }

  if (!count && isRiskSummaryWithRisk(riskSummary)) {
    return 1
  }

  return count
}

export function resolveArchiveRiskTone(riskFlags, riskSummary, viewerOptions) {
  let tone = 'low'

  const visibleFlags = filterRiskFlagsForViewer(riskFlags, viewerOptions)
  for (const flag of visibleFlags) {
    if (!isActionableRiskFlag(flag)) {
      continue
    }

    const flagTone = normalizeRiskFlagTone(flag)
    if (flagTone === 'high') {
      return 'high'
    }
    if (flagTone === 'medium') {
      tone = 'medium'
    }
  }

  if (tone === 'low' && isRiskSummaryWithRisk(riskSummary)) {
    return 'medium'
  }

  return tone
}

export function formatArchiveRiskCountLabel(riskCount) {
  const count = Math.max(0, Number(riskCount) || 0)
  return `${count}条`
}

export function extractArchiveMonth(...values) {
  for (const value of values) {
    const text = String(value || '').trim()
    if (!text) {
      continue
    }

    const parsedDate = new Date(text)
    if (!Number.isNaN(parsedDate.getTime())) {
      const year = parsedDate.getFullYear()
      const month = String(parsedDate.getMonth() + 1).padStart(2, '0')
      return `${year}-${month}`
    }

    const matched = text.match(/(\d{4})-(\d{2})/)
    if (matched) {
      return `${matched[1]}-${matched[2]}`
    }
  }

  return ''
}

export function formatArchiveMonthLabel(monthKey) {
  const normalized = String(monthKey || '').trim()
  const matched = normalized.match(/^(\d{4})-(\d{2})$/)
  if (!matched) {
    return normalized || '未知月份'
  }

  return `${matched[1]}年${matched[2]}月`
}

export function buildTypeFilterOptions(rows) {
  const typeMap = new Map()

  for (const row of rows) {
    const value = String(row?.archiveTypeCode || row?.typeCode || 'other').trim() || 'other'
    if (!typeMap.has(value)) {
      typeMap.set(value, String(row?.archiveType || row?.type || row?.typeLabel || value).trim() || value)
    }
  }

  return [
    { value: ARCHIVE_FILTER_ALL, label: '全部归档类型' },
    ...Array.from(typeMap.entries())
      .sort((left, right) => left[1].localeCompare(right[1], 'zh-CN'))
      .map(([value, label]) => ({ value, label }))
  ]
}

export function buildDepartmentFilterOptions(rows) {
  const departments = new Set()

  for (const row of rows) {
    const department = String(row?.department || row?.dept || '').trim()
    if (department) {
      departments.add(department)
    }
  }

  return [
    { value: ARCHIVE_FILTER_ALL, label: '全部部门' },
    ...Array.from(departments)
      .sort((left, right) => left.localeCompare(right, 'zh-CN'))
      .map((value) => ({ value, label: value }))
  ]
}

export function buildArchiveMonthFilterOptions(rows) {
  const months = new Set()

  for (const row of rows) {
    const month = String(row?.archiveMonth || '').trim()
    if (month) {
      months.add(month)
    }
  }

  return [
    { value: ARCHIVE_FILTER_ALL, label: '全部月份' },
    ...Array.from(months)
      .sort((left, right) => right.localeCompare(left))
      .map((value) => ({ value, label: formatArchiveMonthLabel(value) }))
  ]
}

export function applyArchiveListFilters(rows, filters) {
  let filteredRows = Array.isArray(rows) ? [...rows] : []

  if (filters.tab && filters.tab !== '全部归档') {
    filteredRows = filteredRows.filter((row) => row.archiveTab === filters.tab)
  }

  if (filters.risk === 'has') {
    filteredRows = filteredRows.filter((row) => row.hasRisk)
  } else if (filters.risk === 'none') {
    filteredRows = filteredRows.filter((row) => !row.hasRisk)
  } else if (filters.risk && filters.risk !== ARCHIVE_FILTER_ALL) {
    filteredRows = filteredRows.filter((row) => row.hasRisk && row.riskTone === filters.risk)
  }

  if (filters.type && filters.type !== ARCHIVE_FILTER_ALL) {
    filteredRows = filteredRows.filter((row) => String(row.archiveTypeCode || row.typeCode || '').trim() === filters.type)
  }

  if (filters.department && filters.department !== ARCHIVE_FILTER_ALL) {
    filteredRows = filteredRows.filter((row) => String(row.department || '').trim() === filters.department)
  }

  if (filters.archiveMonth && filters.archiveMonth !== ARCHIVE_FILTER_ALL) {
    filteredRows = filteredRows.filter((row) => String(row.archiveMonth || '').trim() === filters.archiveMonth)
  }

  const keyword = String(filters.keyword || '').trim().toLowerCase()
  if (keyword) {
    filteredRows = filteredRows.filter((row) => (
      String(row.id || '').toLowerCase().includes(keyword)
      || String(row.applicant || '').toLowerCase().includes(keyword)
      || String(row.department || '').toLowerCase().includes(keyword)
      || String(row.archiveType || '').toLowerCase().includes(keyword)
      || String(row.type || '').toLowerCase().includes(keyword)
      || String(row.amount || '').toLowerCase().includes(keyword)
      || String(row.risk || '').toLowerCase().includes(keyword)
      || String(row.riskCount ?? '').includes(keyword)
      || String(row.archiveMonthLabel || '').toLowerCase().includes(keyword)
    ))
  }

  return filteredRows
}

export function hasActiveArchiveListFilters(filters) {
  return Boolean(
    (filters.tab && filters.tab !== '全部归档')
    || (filters.risk && filters.risk !== ARCHIVE_FILTER_ALL)
    || (filters.type && filters.type !== ARCHIVE_FILTER_ALL)
    || (filters.department && filters.department !== ARCHIVE_FILTER_ALL)
    || (filters.archiveMonth && filters.archiveMonth !== ARCHIVE_FILTER_ALL)
    || String(filters.keyword || '').trim()
  )
}
