/**
 * 资产管理 API
 */
import { request } from './request'
import type {
  Asset,
  PaginationParams,
  PaginationResponse,
  DynamicField
} from '@/types'

/** 资产列表参数 */
export interface AssetListParams extends PaginationParams {
  keyword?: string
  device_type_id?: number
  organization_id?: number
  status?: string
  purchase_date_start?: string
  purchase_date_end?: string
}

/** 创建资产参数 */
export interface AssetCreateParams {
  assetName: string
  deviceTypeId: number
  brandId?: number
  model?: string
  serialNumber?: string
  supplierId?: number
  purchaseDate?: string
  purchasePrice?: number
  warrantyPeriod?: number
  organizationId: number
  location?: string
  dynamicAttributes: Record<string, any>
}

/** 更新资产参数 */
export type AssetUpdateParams = Partial<AssetCreateParams>

/**
 * 获取资产列表
 */
export const getAssetList = (params: AssetListParams) => {
  return request.get<PaginationResponse<Asset>>('/assets', { params })
}

/**
 * 获取资产详情
 */
export const getAssetById = (id: number) => {
  return request.get<Asset>(`/assets/${id}`)
}

/**
 * 根据编码查询资产
 */
export const getAssetByCode = (code: string) => {
  return request.get<Asset>(`/assets/scan/${code}`)
}

/**
 * 创建资产
 */
export const createAsset = (data: AssetCreateParams) => {
  return request.post<Asset>('/assets', data)
}

/**
 * 更新资产
 */
export const updateAsset = (id: number, data: AssetUpdateParams) => {
  return request.put(`/assets/${id}`, data)
}

/**
 * 删除资产
 */
export const deleteAsset = (id: number) => {
  return request.delete(`/assets/${id}`)
}

/**
 * 批量导入资产
 */
export const importAssets = (file: File, onProgress?: (percent: number) => void) => {
  return request.upload('/assets/import', file, onProgress)
}

/**
 * 批量导出资产
 */
export const exportAssets = (params: AssetListParams) => {
  return request.download('/assets/export', `资产列表_${Date.now()}.xlsx`)
}

/**
 * 获取设备类型的动态字段
 */
export const getDeviceTypeFields = (typeId: number) => {
  return request.get<DynamicField[]>(`/device-types/${typeId}/fields`)
}
