import assert from 'node:assert/strict'
import {
  buildMonitoringQuery,
  buildTrendQuery,
  formatMonitoringDateTime
} from '../src/utils/waterSupplyMonitoringQuery.js'
import {
  normalizeMonitoringRecord,
  readMonitoringExportError
} from '../src/utils/waterSupplyModel.js'

const query = {
  pageNum: 2,
  pageSize: 20,
  equipmentName: '测试流量点',
  equipmentCode: '',
  equipmentLocation: '测试大道',
  timeRange: [new Date(2026, 8, 1, 8, 30, 5), '2026-09-01 12:00:00'],
  flowMin: '20',
  flowMax: 40
}

assert.deepEqual(buildMonitoringQuery(query, 'flowMin', 'flowMax'), {
  pageNum: 2,
  pageSize: 20,
  equipmentName: '测试流量点',
  equipmentLocation: '测试大道',
  startTime: '2026-09-01 08:30:05',
  endTime: '2026-09-01 12:00:00',
  flowMin: 20,
  flowMax: 40
})

assert.deepEqual(buildMonitoringQuery({}, 'pressureMin', 'pressureMax'), {
  pageNum: 1,
  pageSize: 10
})
assert.deepEqual(buildMonitoringQuery({ powerMin: 'not-number' }, 'powerMin', 'powerMax'), {
  pageNum: 1,
  pageSize: 10
})
assert.deepEqual(buildTrendQuery(['2026-09-01 08:00:00']), {
  startTime: '2026-09-01 08:00:00'
})
assert.deepEqual(buildTrendQuery(), {})
assert.equal(formatMonitoringDateTime(new Date(2026, 8, 1, 8, 30, 5)), '2026-09-01 08:30:05')
assert.equal(formatMonitoringDateTime('  '), undefined)

const trendPoint = normalizeMonitoringRecord({
  equipmentId: 'water-flow-device',
  equipmentName: '供水流量监测点',
  time: '2026-09-01 12:30:00',
  value: '25.5'
}, 'flow', '流量监测')

assert.equal(trendPoint.updateTime, '2026-09-01 12:30:00')
assert.equal(trendPoint.value, 25.5)

const exportError = await readMonitoringExportError(
  new Blob(['{"code":500,"msg":"导出数据过多"}'], {type: 'application/json'})
)
const validExport = await readMonitoringExportError(
  new Blob(['xlsx'], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'})
)

assert.equal(exportError, '导出数据过多')
assert.equal(validExport, null)

console.log('waterSupplyMonitoring tests passed')
