import { http } from '@/api/request'

/** 下载流程 Excel 导入模板 */
export async function downloadTemplate(definitionId: number, filename?: string): Promise<void> {
  const blob = await http.get<Blob>(`/flow/import/template/${definitionId}`, {
    responseType: 'blob',
    timeout: 120000,
  })
  const url = window.URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = (filename || 'template') + '.xlsx'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  window.URL.revokeObjectURL(url)
}

/** 批量导入流程 */
export function importFlow(
  file: File,
  definitionId: number,
  mappings: Record<string, string>
): Promise<{
  total: number
  successCount: number
  updateCount: number
  instanceIds: number[]
}> {
  const formData = new FormData()
  formData.append('file', file)
  formData.append('definitionId', String(definitionId))
  formData.append('mappings', JSON.stringify(mappings))
  return http.post<{ total: number; successCount: number; updateCount: number; instanceIds: number[] }>(
    '/flow/import/execute',
    formData,
    { headers: { 'Content-Type': 'multipart/form-data' }, timeout: 120000 }
  )
}
