const alarmLevelLabels = {
  1: '一级报警',
  2: '二级报警',
  3: '三级报警',
  4: '四级报警'
}

const workOrderStatusLabels = {
  1: '待派单',
  2: '待接单',
  3: '已接单',
  4: '处理中',
  5: '待验收',
  6: '已结案',
  7: '已驳回',
  8: '已取消'
}

export function normalizeDeviceRow(row = {}) {
  const alarmStatus = Number(row.alarmStatus ?? row.status ?? 0)
  const alarmLevel = Number(row.alertLevel ?? row.alarmLevel ?? 0)
  const relatedOrderNo = row.latestOrderNo ?? row.orderNo ?? row.latestMaintainId ?? '-'
  const rawOrderStatus = row.latestMaintainStatus ?? row.orderStatus ?? row.statusText

  return {
    ...row,
    deviceStatusText: alarmStatus === 1 ? '报警' : '正常',
    alarmLevelText: alarmLevelLabels[alarmLevel] ?? (alarmLevel ? `${alarmLevel}级报警` : '未分级'),
    relatedOrderNo,
    workOrderStatusText: typeof rawOrderStatus === 'number'
      ? (workOrderStatusLabels[rawOrderStatus] ?? '未知')
      : (rawOrderStatus || '暂无工单')
  }
}

export function buildMaintainOrderPayload(device = {}, form = {}) {
  const payload = {
    equipmentId: device.equipmentId ?? device.id,
    equipmentCode: device.equipmentCode,
    equipmentName: device.equipmentName,
    maintainType: '故障维修',
    maintainContent: form.description?.trim() || '异常设备维修派单'
  }

  if (form.receiveUserId != null && form.receiveUserId !== '') {
    payload.receiveUserId = Number(form.receiveUserId)
  }
  return payload
}

export function getDeviceOrderEndpoint(view) {
  return view === 'dispatch' ? '/waterSupply/device/abnormal/order' : null
}
