import { http } from './http'
import type { RequestConfig } from './only-last'

export type PageResponse<T> = {
  current: number
  size: number
  totalPage: number
  totalRows: number
  rows: T[]
}

// 发送get请求
export async function get<T>(
  uri: string,
  params?: Record<string, any>,
  config?: RequestConfig,
): Promise<T> {
  if (params) {
    config = config ? { ...config, params } : { params }
  }
  return (await http.get<any>(uri, config)).data['data'] as T
}

// 发送delete请求
export async function remove<T>(
  uri: string,
  params?: Record<string, any>,
  config?: RequestConfig,
): Promise<T> {
  if (params) {
    config = config ? { ...config, params } : { params }
  }
  return (await http.delete<any>(uri, config)).data['data'] as T
}

// 处理请求data（可能有文件）
const processFormData = (data: any): any => {
  if (!data) return data
  const vs = Object.values(data)
  let hasFile = false
  for (const v of vs) {
    if (v instanceof File) {
      hasFile = true
      break
    }
  }
  if (!hasFile) return data

  // 如果有文件
  const form = new FormData()
  const ks = Object.keys(data)
  for (const k_ of ks) {
    const k = k_ as string
    const v = data[k]
    if (v) {
      form.append(k, v)
    }
  }
  return form
}

// 发送post请求（JSON格式）
export async function post<T>(url: string, data?: any, config?: RequestConfig): Promise<T> {
  return (await http.post(url, data, config)).data['data'] as T
}

// 发送put请求（JSON格式）
export async function put<T>(url: string, data?: any, config?: RequestConfig): Promise<T> {
  return (await http.put(url, data, config)).data['data'] as T
}

// 发送post请求（表单格式）
export async function postForm<T>(url: string, data?: any, config?: RequestConfig): Promise<T> {
  data = processFormData(data)
  if (data) {
    let type = 'application/x-www-form-urlencoded'
    if (data instanceof FormData) {
      // 文件上传
      type = 'multipart/form-data'
    }
    const headers = { 'Content-Type': type }
    config = config
      ? {
          ...config,
          headers,
        }
      : { headers }
  }
  return (await http.post(url, data, config)).data['data'] as T
}
