export const FACILITY_STATUS_LABELS = {
  source: { '0': '正常', '1': '异常' },
  plant: { '0': '正常', '1': '停产' },
  pumpStation: { '0': '正常', '1': '故障停运', '2': '检修中' },
  pipe: { '0': '正常', '1': '停用' },
  user: { '0': '正常', '1': '欠费', '2': '停用' }
}

export const FACILITY_TYPE_LABELS = {
  source: '水源地',
  plant: '水厂',
  pumpStation: '泵站',
  pipe: '管网',
  user: '用水户'
}

export const FACILITY_SECTION_TYPES = {
  pipeNetwork: 'pipe',
  waterPlant: 'plant',
  waterSource: 'source',
  waterUser: 'user',
  pumpStation: 'pumpStation'
}

export const FACILITY_SECTION_LABELS = {
  pipeNetwork: FACILITY_TYPE_LABELS.pipe,
  waterPlant: FACILITY_TYPE_LABELS.plant,
  waterSource: FACILITY_TYPE_LABELS.source,
  waterUser: FACILITY_TYPE_LABELS.user,
  pumpStation: FACILITY_TYPE_LABELS.pumpStation
}

export const FACILITY_STATUS_TAG_TYPES = {
  source: { '0': 'success', '1': 'danger' },
  plant: { '0': 'success', '1': 'danger' },
  pumpStation: { '0': 'success', '1': 'danger', '2': 'warning' },
  pipe: { '0': 'success', '1': 'danger' },
  user: { '0': 'success', '1': 'warning', '2': 'danger' }
}

const unknownStatus = { label: '未知', tagType: 'info' }
const FACILITY_TYPE_ORDER = ['source', 'plant', 'pumpStation', 'pipe', 'user']

export function buildPipeNetworkStatisticsQuery({ facilityTypes = [], status = '' } = {}) {
  const query = {}
  const types = Array.isArray(facilityTypes)
    ? facilityTypes.map(type => String(type).trim()).filter(Boolean)
    : []
  const normalizedStatus = String(status ?? '').trim()

  if (types.length) query.facilityTypes = types.join(',')
  if (normalizedStatus) query.status = normalizedStatus
  return query
}

export function getFacilityStatusOptions(facilityTypes = []) {
  const types = FACILITY_TYPE_ORDER.filter(type => facilityTypes.includes(type))
  const statusValues = new Set()

  types.forEach(type => {
    Object.keys(FACILITY_STATUS_LABELS[type] || {}).forEach(status => statusValues.add(status))
  })

  return [...statusValues].sort().map(status => {
    const labels = types
      .map(type => ({
        type,
        label: FACILITY_STATUS_LABELS[type]?.[status]
      }))
      .filter(item => item.label)

    const distinctLabels = [...new Set(labels.map(item => item.label))]
    const label = types.length === 1
      ? `${FACILITY_TYPE_LABELS[types[0]]}: ${distinctLabels[0]}`
      : distinctLabels.join(' / ')

    return { value: status, label }
  })
}

export function resolveFacilityStatusLabel(type, status) {
  const value = status === null || status === undefined ? '' : String(status)
  return FACILITY_STATUS_LABELS[type]?.[value] || unknownStatus.label
}

export function resolveFacilityStatusTagType(type, status) {
  const value = status === null || status === undefined ? '' : String(status)
  return FACILITY_STATUS_TAG_TYPES[type]?.[value] || unknownStatus.tagType
}
