const {
  statusRegisters
} = require('./registers.js')
const {
  MAX_USER_STATUS_COUNT,
  getUserStatusCount
} = require('./control-state.js')
const {
  formatStatusRegisters
} = require('./status-format.js')

const STATUS_SUMMARY_METRICS = [
  { key: 'speed', name: '估算速度', unit: 'RPM', decimals: 0 },
  { key: 'voltage', name: '母线电压', unit: 'V', decimals: 1 },
  { key: 'power', name: '估算功率', unit: 'W', decimals: 1 },
  { key: 'temperature', name: 'NTC 温度', unit: '℃', decimals: 0 }
]
const STATUS_GROUPS = [
  {
    key: 'system',
    title: '状态机 / 故障码',
    names: ['状态机', '故障码']
  },
  {
    key: 'dqVoltageCurrent',
    title: 'DQ 电压电流',
    names: ['UD', 'UQ', 'ID', 'IQ']
  },
  {
    key: 'phaseCurrent',
    title: '相电流',
    names: ['A 相电流', 'B 相电流', 'C 相电流', '相电流最大值', '相电流最小值']
  },
  {
    key: 'estimator',
    title: '估算器状态',
    names: ['估算速度', '估算反电动势']
  },
  {
    key: 'bus',
    title: '母线 / 温度',
    names: ['母线电压', '母线电流', '估算功率', 'NTC 温度']
  },
  {
    key: 'inputPwm',
    title: '输入 / PWM',
    names: ['模拟输入电压', '占空比', '频率']
  }
]

function getVisibleStatusRegisters(userStatusCount) {
  const count = getUserStatusCount(userStatusCount)

  return statusRegisters.filter((item) => (
    item.name.indexOf('用户状态字') !== 0 ||
    Number(item.name.replace('用户状态字 ', '')) <= count
  ))
}

function getStatusPageState(userStatusCount) {
  const registers = formatStatusRegisters(getVisibleStatusRegisters(userStatusCount))
  const registerMap = registers.reduce((result, item) => {
    result[item.name] = item
    return result
  }, {})

  return {
    maxUserStatusCount: MAX_USER_STATUS_COUNT,
    statusRegisterGroups: STATUS_GROUPS.map((group) => ({
      key: group.key,
      title: group.title,
      registers: group.names.map((name) => registerMap[name]).filter(Boolean)
    })).filter((group) => group.registers.length),
    statusRegisters: registers,
    userStatusRegisters: registers.filter((item) => item.name.indexOf('用户状态字') === 0)
  }
}

function getFormattedStatusMap() {
  const formattedRegisters = formatStatusRegisters(statusRegisters)

  return formattedRegisters.reduce((result, item) => {
    result[item.name] = item
    return result
  }, {})
}

function formatMetricText(item, unit, decimals) {
  if (!item || item.displayValue === undefined || item.displayValue === '--') return '--'

  const numberValue = Number(item.displayValue)
  const displayValue = Number.isFinite(numberValue)
    ? numberValue.toFixed(decimals)
    : String(item.displayValue)

  return `${displayValue}${unit}`
}

function getStatusSummaryState() {
  const registerMap = getFormattedStatusMap()
  const stateValue = registerMap['状态机'] && registerMap['状态机'].displayValue
  const faultValue = registerMap['故障码'] && registerMap['故障码'].displayValue
  const faultText = faultValue || '--'
  const isFault = faultText !== '--' && faultText !== '无故障'

  return {
    faultClass: isFault ? 'is-warning' : '',
    faultText,
    metrics: STATUS_SUMMARY_METRICS.map((config) => ({
      key: config.key,
      displayText: formatMetricText(registerMap[config.name], config.unit, config.decimals)
    })),
    stateText: stateValue || '--'
  }
}

module.exports = {
  getStatusPageState,
  getStatusSummaryState
}
