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

import {
  resolveApprovalTaskActionItems,
  resolveApprovalTaskKeyboardCommand,
  resolveApprovalTaskRow,
  resolveApprovalTaskSlaMeta
} from '../src/views/scripts/approvalTaskQueueViewModel.js'

function task(overrides = {}) {
  return {
    id: 'task-001',
    claimId: 'claim-001',
    nodeLabel: '直属领导审批',
    canAct: true,
    availableActions: ['approve', 'delegate', 'unknown_action'],
    riskLevel: 'high',
    openRiskCount: 2,
    evidenceCompleteness: 0.75,
    dueAt: '2026-07-16T12:00:00Z',
    escalationLevel: 1,
    nextEscalationAt: '2026-07-16T13:00:00Z',
    ...overrides
  }
}

test('动作列表只展示服务端授权且前端认识的动作', () => {
  assert.deepEqual(
    resolveApprovalTaskActionItems(task()).map((item) => item.action),
    ['approve', 'delegate']
  )
  assert.deepEqual(
    resolveApprovalTaskActionItems(task({
      canAct: false,
      availableActions: ['approve', 'return', 'transfer', 'sla_escalate'],
      readOnlyReason: '管理员只能管理任务'
    })).map((item) => item.action),
    ['transfer', 'sla_escalate']
  )
})

test('SLA 展示使用服务端截止时间和升级等级', () => {
  const nearDue = resolveApprovalTaskSlaMeta(task(), Date.parse('2026-07-16T11:00:00Z'))
  assert.equal(nearDue.label, '剩余 1.0h')
  assert.equal(nearDue.tone, 'warning')
  assert.equal(nearDue.escalationLabel, 'L1')
  assert.match(nearDue.title, /下次升级：2026-07-16T13:00:00Z/)

  const overdue = resolveApprovalTaskSlaMeta(task(), Date.parse('2026-07-16T14:00:00Z'))
  assert.equal(overdue.label, '超时 2.0h')
  assert.equal(overdue.overdue, true)
  assert.equal(overdue.tone, 'danger')
})

test('任务行组合风险、证据、单据和只读原因', () => {
  const row = resolveApprovalTaskRow({
    task: task({
      canAct: false,
      availableActions: [],
      readOnlyReason: '仅原审批人可操作'
    }),
    claim: {
      claim_no: 'BX-2026-001',
      employee_name: '张三',
      department_name: '销售部',
      amount: 1280.5
    }
  }, Date.parse('2026-07-16T11:00:00Z'))

  assert.equal(row.claimNo, 'BX-2026-001')
  assert.equal(row.applicant, '张三')
  assert.equal(row.riskLabel, '高风险')
  assert.equal(row.evidenceLabel, '75%')
  assert.equal(row.readOnlyReason, '仅原审批人可操作')
  assert.deepEqual(row.actions, [])
})

test('键盘模型支持 Enter、Space、J/K，并在输入控件聚焦时禁用', () => {
  const rowTarget = { tagName: 'TR', isContentEditable: false }
  assert.equal(resolveApprovalTaskKeyboardCommand({ key: 'Enter', target: rowTarget }), 'open')
  assert.equal(resolveApprovalTaskKeyboardCommand({ key: ' ', target: rowTarget }), 'toggle')
  assert.equal(resolveApprovalTaskKeyboardCommand({ key: 'j', target: rowTarget }), 'next')
  assert.equal(resolveApprovalTaskKeyboardCommand({ key: 'K', target: rowTarget }), 'previous')
  assert.equal(
    resolveApprovalTaskKeyboardCommand({ key: 'j', target: { tagName: 'INPUT' } }),
    ''
  )
})
