import { ref } from 'vue'
import { closeWarningException, getWarningExceptions, type WarningExceptionRecord } from '@/api/tests'
import { formatBusinessTime } from '@/utils/businessTime'

export type ExceptionStatus = '待处理' | '已处理'

export interface ExceptionRecord {
  id: number
  testId: number
  testName: string
  testTime: string
  source: string
  exceptionItem: string
  abnormalValue: string
  normalValue: string
  generatedAt: string
  processor: string
  handledAt: string
  status: ExceptionStatus
  handleRemark: string
}

const records = ref<ExceptionRecord[]>([])

function mapRecord(item: WarningExceptionRecord): ExceptionRecord {
  const offline = item.exceptionType === 'DEVICE_OFFLINE'
  let normalValue = '-'
  try { const rule = JSON.parse(item.ruleSnapshot || '{}'); normalValue = rule.maxValue != null ? `≤ ${rule.maxValue} ${item.unit}` : rule.minValue != null ? `≥ ${rule.minValue} ${item.unit}` : '-' } catch { /* 快照不可解析时仍展示异常事实 */ }
  const sourceLabel = ({ CABINET: '检测柜', CABINET_CHANNEL: '检测柜通道', COLLECTOR: '采集器' } as Record<string, string>)[item.sourceType] || item.sourceType
  return {
    id: item.exceptionId, testId: item.testId, testName: item.testName || `测试 #${item.testId}`,
    testTime: formatBusinessTime(item.firstOccurredAtUtc),
    source: `${sourceLabel}${item.sourceIdentity ? ` · ${item.sourceIdentity}` : ''}`,
    exceptionItem: offline ? '设备离线' : item.metricCode,
    abnormalValue: offline ? '离线' : item.abnormalValue == null ? '-' : `${item.abnormalValue} ${item.unit}`,
    normalValue: offline ? '在线' : normalValue,
    generatedAt: formatBusinessTime(item.lastOccurredAtUtc), processor: item.handledByName || '',
    handledAt: formatBusinessTime(item.handledAtUtc), status: item.exceptionStatus === 'OPEN' ? '待处理' : '已处理',
    handleRemark: item.handlingNote || '',
  }
}

export function useExceptions() {
  async function loadFromServer() {
    try { records.value = (await getWarningExceptions()).map(mapRecord); return true } catch { records.value = []; return false }
  }
  async function handleServerRecord(id: number, handleRemark: string) {
    const saved = await closeWarningException(id, handleRemark)
    const index = records.value.findIndex(item => item.id === id)
    if (index >= 0) records.value[index] = mapRecord(saved)
    return true
  }

  return { records, handleServerRecord, loadFromServer }
}
