import type { TestTypeRecord, TestTypeStatus } from '@/stores/testTypes'
import { request, type ApiResponse } from './request'

export interface TestTypeListParams {
  pageNum: number
  pageSize: number
  testTypeId?: number
  testTypeName?: string
  beginCreateTime?: string
  endCreateTime?: string
  status?: string
}

interface TestTypeDto {
  testTypeId: number
  testTypeName: string | null
  status: string | null
  createBy: string | null
  createTime: string | null
  remark: string | null
}

interface TestTypeListResponse extends ApiResponse {
  total: number
  rows: TestTypeDto[]
}

interface TestTypeDetailResponse extends ApiResponse {
  data: TestTypeDto
}

export interface TestTypeListResult {
  total: number
  rows: TestTypeRecord[]
}

export interface TestTypePayload {
  testTypeName: string
  remark: string
}

const statusMap: Record<string, TestTypeStatus> = { '0': '启用', '1': '禁用' }

function mapTestType(item: TestTypeDto): TestTypeRecord {
  return {
    id: item.testTypeId,
    name: item.testTypeName || '-',
    createdAt: item.createTime || '',
    creator: item.createBy || '-',
    remark: item.remark || '',
    status: statusMap[item.status || ''] || '禁用',
  }
}

export async function getTestTypeList(params: TestTypeListParams): Promise<TestTypeListResult> {
  const searchParams = new URLSearchParams()
  Object.entries(params).forEach(([key, value]) => {
    if (value !== undefined && value !== '') searchParams.set(key, String(value))
  })

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

export async function getTestType(testTypeId: number): Promise<TestTypeRecord> {
  const result = await request<TestTypeDetailResponse>(`/system/testType/${testTypeId}`)
  return mapTestType(result.data)
}

export function createTestType(payload: TestTypePayload): Promise<ApiResponse> {
  return request<ApiResponse>('/system/testType', {
    method: 'POST',
    body: JSON.stringify(payload),
  })
}

export function updateTestType(testTypeId: number, payload: TestTypePayload): Promise<ApiResponse> {
  return request<ApiResponse>('/system/testType', {
    method: 'PUT',
    body: JSON.stringify({ testTypeId, ...payload }),
  })
}

export async function changeTestTypeStatus(testTypeId: number, status: TestTypeStatus): Promise<void> {
  await request<ApiResponse>('/system/testType/changeStatus', {
    method: 'PUT',
    body: JSON.stringify({
      testTypeId,
      status: status === '启用' ? '0' : '1',
    }),
  })
}

export async function deleteTestTypes(testTypeIds: number | number[]): Promise<void> {
  const ids = Array.isArray(testTypeIds) ? testTypeIds : [testTypeIds]
  await request<ApiResponse>(`/system/testType/${ids.join(',')}`, {
    method: 'DELETE',
  })
}
