import type { MonitoringStatus, TestRecord, TestStatus } from '@/stores/tests'
import { request, type ApiResponse } from './request'

export type TestStatusCode = 'WAITING' | 'RUNNING' | 'PAUSED' | 'RUNNING_ABNORMAL' | 'COMPLETION_PENDING' | 'COMPLETED' | 'TERMINATED'
export type MonitoringStatusCode = 'NOT_MONITORED' | 'WAITING_DEVICE_START' | 'MONITORING' | 'BACKFILLING' | 'MONITORING_ENDED' | 'CANCELLED'

export interface TestListParams {
  pageNum: number
  pageSize: number
  testName?: string
  testTypeId?: number
  batteryNo?: string
  status?: string
  beginCreateTime?: string
  endCreateTime?: string
}

export interface TestPlanStepPayload {
  planStepId?: number
  cycleNo: number
  stepNo: number
  stepType: string
  stepName: string
  parameters: Record<string, unknown>
  sortOrder: number
}

export interface TestBatteryPayload {
  relationId?: number
  groupId: number
  batteryNo: string
  collectorId: number | null
  binding: { bindingId?: number; channelId: number; expectedBarcode: string | null; claimStatus?: string }
  fields: Array<{ fieldId?: number; fieldName: string; fieldValue: string }>
}

export interface TestThresholdPayload {
  thresholdId?: number
  metricCode: string
  minValue: number | null
  maxValue: number | null
  unit: 'A' | 'V' | 'Ah' | 'Wh' | '℃'
  severity: string
}

export interface TestConfigurationPayload {
  testId?: number
  testName: string
  principalId: number
  testTypeId: number
  testPurpose: string
  monitorTimeoutMinutes: number
  remark: string | null
  batteries: TestBatteryPayload[]
  planSteps: TestPlanStepPayload[]
  thresholds: TestThresholdPayload[]
}

export interface TestConfigurationDetail extends TestConfigurationPayload {
  testId: number
  creatorId: number
  creatorName: string | null
  principalName: string | null
  testTypeName: string | null
  testStatus: TestStatusCode
  monitoringStatus: MonitoringStatusCode
}

export interface TestConfigurationOptions {
  users: Array<{ userId: number; userName: string; nickName: string | null }>
  testTypes: Array<{ testTypeId: number; testTypeName: string }>
  batteries: Array<{ relationId: number; groupId: number; groupName: string; batteryNo: string }>
  channels: Array<{ channelId: number; cabinetId: number; cabinetCode: string; cabinetName: string; adapterCode: string; devtype: number; devid: number; subdevid: number; chlid: number; displayNo: string | null }>
  collectors: Array<{ collectorId: number; collectorCode: string; collectorName: string }>
}

interface TestDto {
  testId: number
  testName: string | null
  testTypeName: string | null
  principalName: string | null
  testPurpose: string | null
  testStatus: TestStatusCode | null
  monitoringStatus: MonitoringStatusCode | null
  createTime: string | null
  startedAtUtc: string | null
  endedAtUtc: string | null
  remark: string | null
  batteryCount: number | null
}

interface TestListResponse extends ApiResponse { total: number; rows: TestDto[] }
interface TestDetailResponse extends ApiResponse { data: TestConfigurationDetail }
interface TestOptionsResponse extends ApiResponse { data: TestConfigurationOptions }
export interface TestListResult { total: number; rows: TestRecord[] }

const statusMap: Record<TestStatusCode, TestStatus> = {
  WAITING: '待测试', RUNNING: '检测中', PAUSED: '暂停', RUNNING_ABNORMAL: '检测中（异常）',
  COMPLETION_PENDING: '完成确认中', COMPLETED: '检测完成', TERMINATED: '已终止',
}
const monitoringStatusMap: Record<MonitoringStatusCode, MonitoringStatus> = {
  NOT_MONITORED: '未监测', WAITING_DEVICE_START: '等待设备启动', MONITORING: '监测中',
  BACKFILLING: '补采中', MONITORING_ENDED: '监测结束', CANCELLED: '已取消',
}
const legacyStatusMap: Record<string, TestStatusCode> = {
  '0': 'WAITING', '1': 'RUNNING', '2': 'RUNNING_ABNORMAL', '3': 'COMPLETED',
}

function mapTest(item: TestDto): TestRecord {
  const status = item.testStatus ? statusMap[item.testStatus] : '未知'
  const monitoringStatus = item.monitoringStatus ? monitoringStatusMap[item.monitoringStatus] : '未知'
  return {
    id: item.testId, name: item.testName || '-', type: item.testTypeName || '-', batteryNo: '-', batteryGroup: '-',
    batteryCount: Number(item.batteryCount) || 0, createdAt: item.createTime || '-', startedAt: item.startedAtUtc || '-',
    endedAt: item.endedAtUtc || '-', purpose: item.testPurpose || '-', owner: item.principalName || '-',
    remark: item.remark || '-', status, monitoringStatus, editable: item.monitoringStatus === 'NOT_MONITORED',
  }
}

export async function getTestList(params: TestListParams): Promise<TestListResult> {
  const searchParams = new URLSearchParams()
  Object.entries(params).forEach(([key, value]) => {
    if (value === undefined || value === '') return
    if (key === 'status') searchParams.set('testStatus', legacyStatusMap[String(value)] || String(value))
    else searchParams.set(key, String(value))
  })
  const result = await request<TestListResponse>(`/system/test/list?${searchParams.toString()}`)
  return { total: Number(result.total) || 0, rows: (result.rows || []).map(mapTest) }
}

export async function getTestConfigurationOptions(): Promise<TestConfigurationOptions> {
  return (await request<TestOptionsResponse>('/system/test/options')).data
}

export async function getTestDetail(testId: number): Promise<TestConfigurationDetail> {
  return (await request<TestDetailResponse>(`/system/test/${testId}`)).data
}

export async function createTest(payload: TestConfigurationPayload): Promise<TestConfigurationDetail> {
  return (await request<TestDetailResponse>('/system/test', { method: 'POST', body: JSON.stringify(payload) })).data
}

export async function updateTest(payload: TestConfigurationPayload & { testId: number }): Promise<TestConfigurationDetail> {
  return (await request<TestDetailResponse>('/system/test', { method: 'PUT', body: JSON.stringify(payload) })).data
}
