import test from 'node:test'
import assert from 'node:assert/strict'
import {
  normalizeDeviceRow,
  buildMaintainOrderPayload,
  getDeviceOrderEndpoint,
  normalizeWorkOrderStatus,
  canDispatchDevice,
  preserveDevicePageOnError,
  normalizeDeviceGisPoints,
  normalizeAssigneeUser,
  buildAssigneeQuery,
  selectSingleAssignee,
  normalizeDispatchOrderResponse
} from '../src/utils/waterSupplyUiModel.js'

test('normalizes alarm and related work-order fields for device pages', () => {
  const row = normalizeDeviceRow({
    equipmentId: 'EQ-1',
    equipmentCode: 'P-001',
    equipmentName: '一号压力计',
    alarmStatus: 1,
    alertLevel: 2,
    latestOrderNo: 'WO202606101703482640',
    latestMaintainStatus: '处理中'
  })

  assert.equal(row.alarmStatusText, '报警')
  assert.equal(row.alarmLevelText, '二级报警')
  assert.equal(row.relatedOrderNo, 'WO202606101703482640')
  assert.equal(row.workOrderStatusText, '处理中')
})

test('keeps device operation, online, alarm, and work-order states distinct', () => {
  const row = normalizeDeviceRow({
    equipmentId: 'EQ-T6',
    equipmentCode: 'CN-GS-202609020001',
    equipmentName: 'T6压力监测点',
    currentStatus: 3,
    onlineStatus: 0,
    alarmStatus: 1,
    alertLevel: 1,
    abnormalReason: '供水压力超限',
    relatedWorkOrderNo: 'WO202609020001',
    relatedWorkOrderStatus: 4,
    relatedWorkOrderPerson: '张三'
  })

  assert.equal(row.currentStatusText, '维修')
  assert.equal(row.onlineStatusText, '离线')
  assert.equal(row.alarmStatusText, '报警')
  assert.equal(row.abnormalReasonText, '供水压力超限')
  assert.equal(row.relatedOrderNo, 'WO202609020001')
  assert.equal(row.workOrderStatusText, '处理中')
  assert.equal(row.relatedWorkOrderPerson, '张三')
})

test('builds a repair dispatch payload with the selected responsible user', () => {
  const payload = buildMaintainOrderPayload(
    { equipmentId: 'EQ-1', equipmentCode: 'P-001', equipmentName: '一号压力计' },
    { description: '压力低于阈值', receiveUserId: 18, orderLevel: 1 }
  )

  assert.deepEqual(payload, {
    equipmentId: 'EQ-1',
    equipmentCode: 'P-001',
    equipmentName: '一号压力计',
    maintainType: '故障维修',
    maintainContent: '压力低于阈值',
    orderLevel: 1,
    receiveUserId: 18
  })
})

test('uses the abnormal-device order endpoint for device repair dispatch', () => {
  assert.equal(getDeviceOrderEndpoint('dispatch'), '/waterSupply/device/abnormal/order')
  assert.equal(getDeviceOrderEndpoint('abnormal'), '/waterSupply/device/abnormal/order')
})

test('maps numeric and numeric-string work-order statuses and marks terminal states', () => {
  assert.deepEqual(normalizeWorkOrderStatus(4), { code: 4, text: '处理中', terminal: false })
  assert.deepEqual(normalizeWorkOrderStatus(8), { code: 8, text: '延期审核', terminal: false })
  assert.deepEqual(normalizeWorkOrderStatus('9'), { code: 9, text: '已延期', terminal: false })
  assert.deepEqual(normalizeWorkOrderStatus('6'), { code: 6, text: '已结案', terminal: true })
  assert.deepEqual(normalizeWorkOrderStatus('7'), { code: 7, text: '已驳回', terminal: true })
  assert.deepEqual(normalizeWorkOrderStatus('暂无工单'), { code: null, text: '暂无工单', terminal: false })
})

test('allows dispatch when the latest order is terminal, including numeric-string status', () => {
  assert.equal(canDispatchDevice({ relatedOrderNo: 'WO-6', relatedWorkOrderStatus: '6' }), true)
  assert.equal(canDispatchDevice({ relatedOrderNo: 'WO-7', relatedWorkOrderStatus: 7 }), true)
  assert.equal(canDispatchDevice({ relatedOrderNo: 'WO-4', relatedWorkOrderStatus: '4' }), false)
  assert.equal(canDispatchDevice({ relatedOrderNo: 'WO-8', relatedWorkOrderStatus: '8' }), false)
  assert.equal(canDispatchDevice({ relatedOrderNo: 'WO-9', relatedWorkOrderStatus: 9 }), false)
  assert.equal(canDispatchDevice({ relatedOrderNo: '-' }), true)
})

test('does not treat a maintenance record id as a unified work-order number', () => {
  const row = normalizeDeviceRow({
    equipmentId: 'EQ-RECENT-MAINTENANCE',
    latestMaintainId: 42,
    latestMaintainStatus: '已完成'
  })

  assert.equal(row.relatedOrderNo, '-')
  assert.equal(row.workOrderStatusText, '已完成')
  assert.equal(canDispatchDevice(row), true)
})

test('retains existing page rows and total when a reload fails', () => {
  const previous = { records: [{ equipmentId: 'EQ-1' }], total: 1 }
  assert.deepEqual(preserveDevicePageOnError(previous), {
    page: previous,
    error: '设备数据加载失败，请点击重试'
  })
})

test('normalizes GIS responses to point records without inventing coordinates', () => {
  assert.deepEqual(normalizeDeviceGisPoints({ data: [{ equipmentId: 'EQ-1', longitude: '110.1', latitude: '28.2' }] }), [
    { equipmentId: 'EQ-1', longitude: '110.1', latitude: '28.2', _longitude: 110.1, _latitude: 28.2 }
  ])
  assert.deepEqual(normalizeDeviceGisPoints({ data: [{ equipmentId: 'EQ-2' }] }), [])
})

test('normalizes eligible assignee display fields with safe fallbacks', () => {
  assert.deepEqual(normalizeAssigneeUser({
    userId: 18,
    userName: 'zhangsan',
    nickName: '张三',
    phonenumber: '',
    status: '0',
    delFlag: '0',
    dept: { deptName: '供水运行部' }
  }), {
    userId: 18,
    userName: 'zhangsan',
    nickName: '张三',
    deptName: '供水运行部',
    phone: '未登记手机号',
    statusText: '正常',
    eligible: true
  })
  assert.equal(normalizeAssigneeUser({ userId: 19, status: '1', delFlag: '0' }).eligible, false)
})

test('builds server-paged assignee queries using the matching user field', () => {
  assert.deepEqual(buildAssigneeQuery({ keyword: 'zhang', deptId: 7, pageNum: 2, pageSize: 20 }), {
    pageNum: 2,
    pageSize: 20,
    deptId: 7,
    status: '0',
    userName: 'zhang'
  })
  assert.equal(buildAssigneeQuery({ keyword: '张', pageNum: 1, pageSize: 10 }).nickName, '张')
  assert.equal(buildAssigneeQuery({ keyword: '1380013' }).phonenumber, '1380013')
})

test('keeps only the last clicked assignee for single selection', () => {
  assert.deepEqual(selectSingleAssignee([{ userId: 1 }, { userId: 2 }]), { userId: 2 })
  assert.equal(selectSingleAssignee([]), null)
})

test('accepts only a real dispatched order summary', () => {
  assert.equal(normalizeDispatchOrderResponse({ data: { orderId: 12, orderNo: 'WO-12', orderStatus: '2' } }).orderNo, 'WO-12')
  assert.equal(normalizeDispatchOrderResponse({ data: { orderId: 12, orderNo: 'WO-12', orderStatus: 1 } }), null)
  assert.equal(normalizeDispatchOrderResponse({ data: { orderId: 12, orderStatus: 2 } }), null)
})
