import type * as T from './type'
import http from '@/utils/http'

export type * from './type'
export * from './defect'

/** @desc 获取项目列表（分页） */
export const getProjectList = (params: T.ProjectQuery) => {
  return http.get<T.ProjectInfo[] | T.PageResult<T.ProjectInfo>>('/project/list', params)
}

/** @desc 获取项目详情 */
export const getProjectDetail = (projectId: string) => {
  return http.get<T.ProjectInfo>(`/project/detail/${projectId}`)
}

/** @desc 获取机组列表 */
export const getTurbineList = (params?: T.TurbineQuery) => {
  return http.get<T.TurbineInfo[]>('/turbine/list', params)
}

/** @desc 获取机组详情 */
export const getTurbineDetail = (turbineId: string) => {
  return http.get<T.TurbineInfo>(`/turbine/info/${turbineId}`)
}

/** @desc 获取部件列表 */
export const getPartList = (params?: T.PartQuery) => {
  return http.get<T.PartInfo[]>('/part/list', params)
}

/** @desc 获取部件详情 */
export const getPartDetail = (partId: string) => {
  return http.get<T.PartInfo>(`/part/detail/${partId}`)
}

/** @desc 获取项目树 */
export const getProjectTree = () => {
  return http.get<T.ProjectTreeNode[]>(`/industrial-image/project-tree`)
}

/** @desc 获取图像列表 */
export const getImageList = (params?: {
  imageTypes?: string[]
  keyword?: string
  partId?: string
  turbineId?: string
}) => {
  return http.get<{
    code: number
    data: Array<{
      imageId: string
      imageName: string
      audioList?: any[]
      cameraManufacturer?: string
      cameraModel?: string
      collectorName?: string
      focalDistance?: string
      gps?: string
      humidness?: number
      imageResolution?: string
      imageType?: string
      imageTypeLabel?: string
      partId?: string
      partName?: string
      shootingDistance?: number
      shootingMethod?: string
      shootingMethodLabel?: string
      shootingTime?: string
      temperature?: string
      weather?: string
      weatherLabel?: string
      windLevel?: number
      filePath?: string
      imagePath?: string
    }>
    msg: string
    status: number
    success: boolean
  }>('/image/list', params)
}

/** @desc 获取图像详情 */
export function getImageDetail(imageId: string) {
  return http.get<T.IndustrialImage>(`/industrial-image/image/${imageId}`)
}

/** @desc 搜索图像 */
export function searchImages(query: T.ImageQuery) {
  return http.get<T.IndustrialImage[]>(`/industrial-image/images/search`, query)
}

/** @desc 查询通用图片来源 */
export const getImageSources = () => {
  return http.get<Array<{
    code: number
    data: Array<{
      id: string
      name: string
      code: string
    }>
    msg: string
    status: number
  }>>('/common/list/common-image-source')
}

/** @desc 上传单张图片 */
export const uploadSingleImage = (imageSource: string, file: File, params?: {
  altitude?: string
  latitude?: string
  longitude?: string
  partId?: string
  uploadUser?: string
}) => {
  const formData = new FormData()
  formData.append('file', file)
  
  // 构建查询参数
  const queryParams = new URLSearchParams()
  if (params?.altitude) queryParams.append('altitude', params.altitude)
  if (params?.latitude) queryParams.append('latitude', params.latitude)
  if (params?.longitude) queryParams.append('longitude', params.longitude)
  if (params?.partId) queryParams.append('partId', params.partId)
  if (params?.uploadUser) queryParams.append('uploadUser', params.uploadUser)
  
  const url = `/common/upload-image/${imageSource}${queryParams.toString() ? '?' + queryParams.toString() : ''}`
  
  return http.post(url, formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

/** @desc 批量上传图片 */
export const batchUploadImages = (imageSource: string, files: File[], params?: {
  altitude?: string
  latitude?: string
  longitude?: string
  partId?: string
  uploadUser?: string
}) => {
  const formData = new FormData()
  
  // 添加文件
  files.forEach(file => {
    formData.append('files', file)
  })
  
  // 构建查询参数
  const queryParams = new URLSearchParams()
  if (params?.altitude) queryParams.append('altitude', params.altitude)
  if (params?.latitude) queryParams.append('latitude', params.latitude)
  if (params?.longitude) queryParams.append('longitude', params.longitude)
  if (params?.partId) queryParams.append('partId', params.partId)
  if (params?.uploadUser) queryParams.append('uploadUser', params.uploadUser)
  
  const url = `/common/batch-upload-image/${imageSource}${queryParams.toString() ? '?' + queryParams.toString() : ''}`
  
  return http.post(url, formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

/** @desc 单图自动标注缺陷 */
export const detectDefects = (params: {
  confThreshold: number
  defectTypeList: string[]
  imageId: string
  modelId: string
}) => {
  return http.post('/defect/detect', params, {
    headers: {
      'Content-Type': 'application/json'
    }
  })
}

/** @desc 图像导入接口（使用新的API规范） */
export const uploadImageToPartV2 = (
  imageSource: string,
  partId: string,
  files: File[],
  params: Partial<T.ImageUploadParams>
) => {
  const formData = new FormData()
  
  // 添加文件
  files.forEach(file => {
    formData.append('files', file)
  })
  
  // 添加其他参数
  if (params.collectorId) formData.append('collectorId', params.collectorId)
  if (params.collectorName) formData.append('collectorName', params.collectorName)
  if (params.humidness !== undefined) formData.append('humidness', params.humidness.toString())
  if (params.gps) formData.append('imageList[0].GPS', params.gps)
  if (params.xResolution) formData.append('imageList[0].XResolution', params.xResolution)
  if (params.yResolution) formData.append('imageList[0].YResolution', params.yResolution)
  if (params.altitude) formData.append('imageList[0].altitude', params.altitude)
  if (params.cameraManufacturer) formData.append('imageList[0].cameraManufacturer', params.cameraManufacturer)
  if (params.cameraModel) formData.append('imageList[0].cameraModel', params.cameraModel)
  if (params.focalDistance) formData.append('imageList[0].focalDistance', params.focalDistance)
  if (params.focalDistance35) formData.append('imageList[0].focalDistance35', params.focalDistance35)
  if (params.imageHeight) formData.append('imageList[0].imageHeight', params.imageHeight)
  if (params.imageId) formData.append('imageList[0].imageId', params.imageId)
  if (params.imageName) formData.append('imageList[0].imageName', params.imageName)
  if (params.imagePath) formData.append('imageList[0].imagePath', params.imagePath)
  if (params.imageResolution) formData.append('imageList[0].imageResolution', params.imageResolution)
  if (params.imageSize) formData.append('imageList[0].imageSize', params.imageSize)
  if (params.imageWidth) formData.append('imageList[0].imageWidth', params.imageWidth)
  if (params.latitude) formData.append('imageList[0].latitude', params.latitude)
  if (params.longitude) formData.append('imageList[0].longitude', params.longitude)
  if (params.resolutionUnits) formData.append('imageList[0].resolutionUnits', params.resolutionUnits)
  if (params.shootingTime) formData.append('imageList[0].shootingTime', params.shootingTime)
  if (params.shootingDistance !== undefined) formData.append('shootingDistance', params.shootingDistance.toString())
  if (params.shootingMethod) formData.append('shootingMethod', params.shootingMethod)
  if (params.shootingTimeBegin) formData.append('shootingTimeBegin', params.shootingTimeBegin)
  if (params.shootingTimeEnd) formData.append('shootingTimeEnd', params.shootingTimeEnd)
  if (params.temperatureMax !== undefined) formData.append('temperatureMax', params.temperatureMax.toString())
  if (params.temperatureMin !== undefined) formData.append('temperatureMin', params.temperatureMin.toString())
  if (params.weather) formData.append('weather', params.weather)
  if (params.windLevel !== undefined) formData.append('windLevel', params.windLevel.toString())
  
  return http.post(`/image/${imageSource}/upload/${partId}`, formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

/** @desc 图像导入接口（更新为使用真实接口） */
export const importImages = (files: FileList | File[], params: T.ImageImportParams) => {
  const fileArray = Array.from(files)
  
  // 使用批量上传接口
  return batchUploadImages(params.imageSource || 'default', fileArray, {
    partId: params.componentId,
    uploadUser: params.uploadUser
  }).then(response => {
    // 如果需要自动标注
    if (params.autoAnnotate && params.annotationTypes && params.annotationTypes.length > 0) {
      // 这里可以添加自动标注逻辑
      return response
    }
    return response
  })
}

/** @desc 自动标注接口（更新为使用真实接口） */
export const autoAnnotateImage = (params: T.AutoAnnotationParams) => {
  return detectDefects({
    confThreshold: params.confidenceThreshold || 0.5,
    defectTypeList: params.annotationTypes,
    imageId: params.imageId,
    modelId: params.params?.modelId || 'default'
  })
}

/** @desc 获取图像标注信息 */
export const getImageAnnotations = (imageId: string) => {
  return http.get<T.AnnotationResult>(`/industrial-image/annotations/${imageId}`)
}

/** @desc 删除标注 */
export const deleteAnnotation = (imageId: string, annotationId: string) => {
  return http.del(`/industrial-image/annotations/${imageId}/${annotationId}`)
}

/** @desc 确认标注 */
export const confirmAnnotation = (imageId: string, annotationId: string) => {
  return http.post(`/industrial-image/annotations/${imageId}/${annotationId}/confirm`)
}

/** @desc 上传图像（保留旧接口兼容性） */
export const uploadImage = (file: File, params: { projectId: string; componentId?: string }) => {
  return uploadSingleImage('default', file, {
    partId: params.componentId,
    uploadUser: 'current-user'
  })
}

/** @desc 删除图像 */
export const deleteImage = (imageId: string) => {
  return http.del(`/industrial-image/images/${imageId}`)
}

/** @desc 批量删除图像 */
export function batchDeleteImages(imageIds: string[]) {
  return http.del(`/industrial-image/images`, { ids: imageIds })
}

/** @desc 开始图像处理 */
export const processImage = (params: T.ImageProcessParams) => {
  return http.post<T.ImageProcessResult>(`/industrial-image/process`, params)
}

/** @desc 获取处理结果 */
export const getProcessResult = (processId: string) => {
  return http.get<T.ImageProcessResult>(`/industrial-image/process/${processId}`)
}

/** @desc 获取图像的所有处理结果 */
export function getImageProcessResults(imageId: string) {
  return http.get<T.ImageProcessResult[]>(`/industrial-image/image/${imageId}/results`)
}

/** @desc 取消图像处理 */
export function cancelImageProcess(processId: string) {
  return http.post(`/industrial-image/process/${processId}/cancel`)
}

/** @desc 重新处理图像 */
export function reprocessImage(params: T.ImageProcessParams) {
  return http.post<T.ImageProcessResult>(`/industrial-image/process/reprocess`, params)
}

/** @desc 批量处理 */
export const batchProcessImages = (imageIds: string[], processType: string) => {
  return http.post<T.ImageProcessResult[]>(`/industrial-image/batch-process`, {
    imageIds,
    processType
  })
}

/** @desc 导出处理结果 */
export function exportProcessResults(query: T.ImageQuery) {
  return http.get(`/industrial-image/export/results`, query, {
    responseType: 'blob'
  })
}

/** @desc 生成检测报告 */
export function generateReport(projectId: string) {
  return http.post(`/industrial-image/report/generate`, { projectId }, {
    responseType: 'blob'
  })
}

