import assert from 'node:assert/strict'
import test from 'node:test'

import {
  applyArchiveListFilters,
  buildArchiveMonthFilterOptions,
  buildDepartmentFilterOptions,
  buildTypeFilterOptions,
  countClaimRisks,
  extractArchiveMonth,
  formatArchiveMonthLabel,
  formatArchiveRiskCountLabel,
  hasActiveArchiveListFilters,
  resolveArchiveRiskTone
} from '../src/utils/archiveCenterListFilters.js'

const sampleRows = [
  {
    id: 'EXP-001',
    typeCode: 'travel',
    type: '差旅费',
    archiveTypeCode: 'reimbursement',
    archiveType: '报销',
    department: '研发部',
    archiveMonth: '2026-05',
    archiveMonthLabel: '2026年05月',
    archiveTab: '报销归档',
    hasRisk: true,
    riskTone: 'high',
    risk: '2条',
    riskCount: 2
  },
  {
    id: 'EXP-002',
    typeCode: 'entertainment',
    type: '业务招待费',
    archiveTypeCode: 'reimbursement',
    archiveType: '报销',
    department: '销售部',
    archiveMonth: '2026-04',
    archiveMonthLabel: '2026年04月',
    archiveTab: '报销归档',
    hasRisk: false,
    riskTone: 'none',
    risk: '0条',
    riskCount: 0
  }
]

test('countClaimRisks counts flag points and summary fallback', () => {
  assert.equal(
    countClaimRisks([
      { severity: 'high', points: ['酒店超标', '缺少水单'] },
      { severity: 'info', message: '提示信息' }
    ], '无'),
    2
  )
  assert.equal(countClaimRisks([], '发票抬头不一致'), 1)
  assert.equal(formatArchiveRiskCountLabel(3), '3条')
})

test('countClaimRisks ignores approval opinions and completed flow logs', () => {
  assert.equal(
    countClaimRisks([
      { source: 'manual_approval', severity: 'info', message: '同意' },
      { source: 'finance_approval', severity: 'info', message: '周晓彤 已完成财务审核，进入归档入账。' }
    ], '无'),
    0
  )
  assert.equal(countClaimRisks([], '同意'), 0)
  assert.equal(countClaimRisks([], '周晓彤 已完成财务审核，进入归档入账。'), 0)
})

test('extractArchiveMonth parses iso timestamps', () => {
  assert.equal(extractArchiveMonth('2026-05-20T08:00:00.000Z'), '2026-05')
})

test('applyArchiveListFilters supports department and archive month', () => {
  const filtered = applyArchiveListFilters(sampleRows, {
    department: '销售部',
    archiveMonth: '2026-04'
  })

  assert.equal(filtered.length, 1)
  assert.equal(filtered[0].id, 'EXP-002')
})

test('applyArchiveListFilters supports the unified reimbursement archive tab', () => {
  const reimbursementRows = applyArchiveListFilters(sampleRows, {
    tab: '报销归档'
  })
  const oldTravelRows = applyArchiveListFilters(sampleRows, {
    tab: '差旅报销'
  })

  assert.equal(reimbursementRows.length, 2)
  assert.equal(oldTravelRows.length, 0)
})

test('build filter options are derived from archive types', () => {
  const typeLabels = buildTypeFilterOptions(sampleRows).map((item) => item.label)
  const typeValues = buildTypeFilterOptions(sampleRows).map((item) => item.value)
  const departmentLabels = buildDepartmentFilterOptions(sampleRows).map((item) => item.label)
  const monthOptions = buildArchiveMonthFilterOptions(sampleRows)

  assert.equal(typeLabels[0], '全部归档类型')
  assert.deepEqual(typeValues, ['all', 'reimbursement'])
  assert.deepEqual(typeLabels, ['全部归档类型', '报销'])
  assert.equal(departmentLabels[0], '全部部门')
  assert.ok(departmentLabels.includes('研发部'))
  assert.ok(departmentLabels.includes('销售部'))
  assert.equal(formatArchiveMonthLabel('2026-05'), '2026年05月')
  assert.equal(monthOptions[0].label, '全部月份')
  assert.ok(monthOptions.some((item) => item.value === '2026-05'))
})

test('hasActiveArchiveListFilters detects active criteria', () => {
  assert.equal(hasActiveArchiveListFilters({ risk: 'high' }), true)
  assert.equal(hasActiveArchiveListFilters({ risk: 'all', type: 'all' }), false)
})

test('list risk tone hides budget governance risk from applicant for consistency with detail', () => {
  // 申请单列表里，预算治理类风险（对申请人不可见）不应计入申请人看到的风险等级，
  // 避免出现“列表显示中风险、详情却看不到”的不一致。
  const applicationRequest = {
    id: 'AP-202606200001',
    documentTypeCode: 'application',
    typeCode: 'travel_application',
    employeeId: 'EMP-001',
    employeeName: '张三'
  }
  const submitter = { id: 'EMP-001', name: '张三', employeeId: 'EMP-001' }

  const riskFlags = [
    {
      source: 'budget_control',
      severity: 'high',
      message: '预算可用余额不足。',
      business_stage: 'expense_application',
      risk_domain: 'budget',
      visibility_scope: 'budget_manager',
      actionability: 'budget_governance'
    }
  ]
  const viewerForSubmitter = { request: applicationRequest, currentUser: submitter }

  // 申请人：列表不应显示该预算风险 → tone 为 low、count 为 0
  assert.equal(resolveArchiveRiskTone(riskFlags, '', viewerForSubmitter), 'low')
  assert.equal(countClaimRisks(riskFlags, '', viewerForSubmitter), 0)
  // 不传 viewerOptions 时保持向后兼容（原样统计）
  assert.equal(resolveArchiveRiskTone(riskFlags, ''), 'high')
})
