import { apiRequest } from './api.js'

function buildEmployeesQuery(params = {}) {
  const search = new URLSearchParams()

  if (params.status && params.status !== '全部员工') {
    search.set('status', params.status)
  }

  if (params.keyword) {
    search.set('keyword', params.keyword)
  }

  const page = params.page
  const pageSize = params.pageSize || params.page_size

  if (page) {
    search.set('page', String(page))
  }

  if (pageSize) {
    search.set('page_size', String(pageSize))
  }

  return search
}

export function fetchEmployees(params = {}) {
  const query = buildEmployeesQuery(params).toString()
  return apiRequest(`/employees${query ? `?${query}` : ''}`)
}

function triggerBlobDownload(blob, filename) {
  const objectUrl = URL.createObjectURL(blob)
  const anchor = document.createElement('a')
  anchor.href = objectUrl
  anchor.download = filename
  anchor.rel = 'noopener'
  document.body.appendChild(anchor)
  anchor.click()
  anchor.remove()
  URL.revokeObjectURL(objectUrl)
}

export async function downloadEmployeeImportTemplate() {
  const blob = await apiRequest('/employees/import-template', {
    responseType: 'blob',
    contentType: null
  })
  triggerBlobDownload(blob, '员工导入模板.xlsx')
}

export async function exportEmployees(params = {}) {
  const query = buildEmployeesQuery(params).toString()
  const blob = await apiRequest(`/employees/export${query ? `?${query}` : ''}`, {
    responseType: 'blob',
    contentType: null
  })
  triggerBlobDownload(blob, '员工目录导出.xlsx')
}

export function importEmployees(file) {
  const formData = new FormData()
  formData.append('file', file)

  return apiRequest('/employees/import', {
    method: 'POST',
    body: formData,
    contentType: null
  })
}

export function fetchEmployeeMeta() {
  return apiRequest('/employees/meta')
}

export function fetchEmployeeDetail(employeeId) {
  return apiRequest(`/employees/${employeeId}`)
}

export function updateEmployee(employeeId, payload) {
  return apiRequest(`/employees/${employeeId}`, {
    method: 'PATCH',
    body: JSON.stringify(payload)
  })
}

export function disableEmployee(employeeId) {
  return apiRequest(`/employees/${employeeId}/disable`, {
    method: 'POST'
  })
}

export function enableEmployee(employeeId) {
  return apiRequest(`/employees/${employeeId}/enable`, {
    method: 'POST'
  })
}
