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

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

const terminalWorkOrderStatuses = new Set([6, 7])

const deviceCurrentStatusLabels = {
  1: '在用',
  2: '闲置',
  3: '维修',
  4: '报废',
  5: '待入库'
}

const onlineStatusLabels = {
  1: '在线',
  0: '离线'
}

export function normalizeDeviceRow(row = {}) {
  const alarmStatus = Number(row.alarmStatus)
  const currentStatus = Number(row.currentStatus)
  const onlineStatus = Number(row.onlineStatus)
  const alarmLevel = Number(row.alertLevel ?? row.alarmLevel ?? 0)
  const relatedOrderNo = row.relatedWorkOrderNo
    ?? row.latestOrderNo
    ?? row.orderNo
    ?? '-'
  const rawOrderStatus = row.relatedWorkOrderStatus
    ?? row.latestMaintainStatus
    ?? row.orderStatus
    ?? row.statusText
  const currentStatusText = deviceCurrentStatusLabels[currentStatus]
    ?? (currentStatus ? `状态${currentStatus}` : '未知')
  const onlineStatusText = onlineStatusLabels[onlineStatus]
    ?? (Number.isFinite(onlineStatus) && onlineStatus !== 0 ? '在线' : '离线')
  const alarmStatusText = alarmStatus === 1 ? '报警' : '正常'

  const workOrderStatus = normalizeWorkOrderStatus(rawOrderStatus)
  return {
    ...row,
    deviceStatusText: currentStatusText,
    currentStatusText,
    onlineStatusText,
    alarmStatusText,
    abnormalReasonText: row.abnormalReason
      || (alarmStatus === 1 ? '设备报警' : currentStatus === 3 ? '设备维修中' : '-'),
    alarmLevelText: alarmLevelLabels[alarmLevel] ?? (alarmLevel ? `${alarmLevel}级报警` : '未分级'),
    relatedOrderNo,
    relatedWorkOrderPerson: row.relatedWorkOrderPerson ?? '-',
    workOrderStatusCode: workOrderStatus.code,
    workOrderTerminal: workOrderStatus.terminal,
    workOrderStatusText: workOrderStatus.text
  }
}

export function normalizeWorkOrderStatus(value) {
  if (value === null || value === undefined || value === '') {
    return { code: null, text: '暂无工单', terminal: false }
  }
  const numeric = typeof value === 'number' || /^\s*\d+\s*$/.test(String(value))
  if (numeric) {
    const code = Number(value)
    return {
      code: Number.isFinite(code) ? code : null,
      text: workOrderStatusLabels[code] ?? '未知',
      terminal: terminalWorkOrderStatuses.has(code)
    }
  }
  const text = String(value)
  const code = Object.entries(workOrderStatusLabels).find(([, label]) => label === text)?.[0]
  return { code: code ? Number(code) : null, text: text || '暂无工单', terminal: code ? terminalWorkOrderStatuses.has(Number(code)) : false }
}

export function canDispatchDevice(row = {}) {
  const orderNo = row.relatedOrderNo ?? row.latestOrderNo ?? row.orderNo
  if (!orderNo || orderNo === '-') return true
  return normalizeWorkOrderStatus(row.relatedWorkOrderStatus ?? row.latestMaintainStatus ?? row.orderStatus).terminal
}

export function preserveDevicePageOnError(page) {
  return { page, error: '设备数据加载失败，请点击重试' }
}

export function normalizeDeviceGisPoints(response) {
  const data = response?.data ?? response
  const points = Array.isArray(data) ? data : (data?.records || data?.rows || data?.points || [])
  return points.map(point => ({
    ...point,
    _longitude: Number(point.longitude ?? point.lng),
    _latitude: Number(point.latitude ?? point.lat)
  })).filter(point => Number.isFinite(point._longitude) && Number.isFinite(point._latitude))
}

export function normalizeAssigneeUser(user = {}) {
  const status = String(user.status ?? '0')
  const delFlag = String(user.delFlag ?? '0')
  const deptName = user.dept?.deptName ?? user.deptName ?? '-'
  const phone = user.phonenumber ?? user.phoneNumber ?? user.phone
  return {
    userId: user.userId ?? user.id,
    userName: user.userName ?? '',
    nickName: user.nickName ?? '',
    deptName,
    phone: phone || '未登记手机号',
    statusText: status === '0' && delFlag === '0' ? '正常' : '停用',
    eligible: status === '0' && delFlag === '0'
  }
}

export function buildAssigneeQuery({ deptId, keyword = '', pageNum = 1, pageSize = 10 } = {}) {
  const normalizedKeyword = String(keyword ?? '').trim()
  const searchField = normalizedKeyword
    ? (/^\+?[\d\s-]+$/.test(normalizedKeyword)
        ? 'phonenumber'
        : /[\u3400-\u9fff]/u.test(normalizedKeyword) ? 'nickName' : 'userName')
    : null
  return {
    pageNum: Number(pageNum) > 0 ? Number(pageNum) : 1,
    pageSize: Number(pageSize) > 0 ? Number(pageSize) : 10,
    ...(deptId == null || deptId === '' ? {} : { deptId }),
    status: '0',
    ...(searchField ? { [searchField]: normalizedKeyword } : {})
  }
}

export function selectSingleAssignee(selection = []) {
  return Array.isArray(selection) && selection.length ? selection[selection.length - 1] : null
}

export function normalizeDispatchOrderResponse(response) {
  const candidates = [response?.data?.data, response?.data, response]
  const summary = candidates.find(value => value && typeof value === 'object' && !Array.isArray(value)
    && value.orderId != null && String(value.orderNo ?? '').trim())
  if (!summary || Number(summary.orderStatus) !== 2) return null
  return {
    ...summary,
    orderId: summary.orderId,
    orderNo: String(summary.orderNo).trim(),
    orderStatus: Number(summary.orderStatus)
  }
}

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

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

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

function normalizeThresholdValue(value) {
  if (value === '' || value === null || value === undefined) {
    return undefined
  }
  const parsed = Number(value)
  return Number.isFinite(parsed) ? parsed : value
}

function normalizeThresholdPeriod(form = {}) {
  const periodStart = form.periodStart?.trim() || undefined
  const periodEnd = form.periodEnd?.trim() || undefined
  return { periodStart, periodEnd }
}

function removeUndefined(payload) {
  return Object.fromEntries(
    Object.entries(payload).filter(([, value]) => value !== undefined)
  )
}

export function buildThresholdSavePayload(form = {}) {
  const deviceCodes = Array.from(new Set((form.deviceCodes || [])
    .map(code => code?.trim())
    .filter(Boolean)))
  const { periodStart, periodEnd } = normalizeThresholdPeriod(form)

  return removeUndefined({
    deviceCodes,
    warningType: form.warningType?.trim() || undefined,
    warningCode: form.warningCode?.trim() || undefined,
    minValue: normalizeThresholdValue(form.minValue),
    maxValue: normalizeThresholdValue(form.maxValue),
    periodStart,
    periodEnd,
    remark: form.remark?.trim() || undefined
  })
}

export function buildThresholdUpdatePayload(form = {}) {
  const { periodStart, periodEnd } = normalizeThresholdPeriod(form)

  return removeUndefined({
    id: form.id,
    deviceCode: form.deviceCode?.trim() || undefined,
    warningType: form.warningType?.trim() || undefined,
    warningCode: form.warningCode?.trim() || undefined,
    minValue: normalizeThresholdValue(form.minValue),
    maxValue: normalizeThresholdValue(form.maxValue),
    periodStart,
    periodEnd,
    remark: form.remark?.trim() || undefined
  })
}

export function buildThresholdQuery(query = {}) {
  return removeUndefined({
    pageNum: query.pageNum || 1,
    pageSize: query.pageSize || 10,
    deviceCode: query.deviceCode?.trim() || undefined,
    warningType: query.warningType?.trim() || undefined,
    keyword: query.keyword?.trim() || undefined
  })
}
