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

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

interface TestDto {
  testId: number
  testName: string | null
  testTypeName: string | null
  leaderName: string | null
  purpose: string | null
  status: string | null
  createTime: string | null
  remark: string | null
  batteryCount: number | null
}

interface TestListResponse extends ApiResponse {
  total: number
  rows: TestDto[]
}

export interface TestListResult {
  total: number
  rows: TestRecord[]
}

const statusMap: Record<string, TestStatus> = {
  '0': '待测试',
  '1': '检测中',
  '2': '检测中（异常）',
  '3': '检测完成',
}

function mapTest(item: TestDto): TestRecord {
  return {
    id: item.testId,
    name: item.testName || '-',
    type: item.testTypeName || '-',
    batteryNo: '-',
    batteryGroup: '-',
    batteryCount: Number(item.batteryCount) || 0,
    createdAt: item.createTime || '-',
    startedAt: '-',
    endedAt: '-',
    purpose: item.purpose || '-',
    owner: item.leaderName || '-',
    remark: item.remark || '-',
    status: statusMap[item.status || ''] || '待测试',
  }
}

export async function getTestList(params: TestListParams): Promise<TestListResult> {
  const searchParams = new URLSearchParams()
  Object.entries(params).forEach(([key, value]) => {
    if (value === undefined || value === '') return
    const queryKey = key === 'beginCreateTime' || key === 'endCreateTime'
      ? `params[${key}]`
      : key
    searchParams.set(queryKey, String(value))
  })

  const result = await request<TestListResponse>(`/system/test/list?${searchParams.toString()}`)
  return {
    total: Number(result.total) || 0,
    rows: (result.rows || []).map(mapTest),
  }
}
