import type { RequestClientConfig } from '@vben/request'

import { requestClient } from './request'

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

// 发送get请求
export function get<T>(
  uri: string,
  params?: Record<string, any>,
  config?: RequestClientConfig,
): Promise<T> {
  if (params) {
    config = config ? { ...config, params } : { params }
  }
  return requestClient.get(uri, config)
}

function getMultipartData(data: any) {
  if (!data) 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 === null || v === undefined) continue
    if (Array.isArray(v)) {
      for (const item of v) {
        form.append(k, item)
      }
    } else {
      form.append(k, v)
    }
  }
  return form
}

// 处理请求data（可能有文件）
function 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 (Array.isArray(v)) {
      for (const item of v) {
        if (item instanceof File) {
          hasFile = true
          break
        }
      }
      if (hasFile) {
        break
      }
    }
  }
  if (!hasFile) return data
  // 如果有文件
  return getMultipartData(data)
}

function processDataAndConfig(
  type: any,
  data: any,
  config?: RequestClientConfig,
) {
  data = processFormData(data)
  if (data) {
    if (data instanceof FormData) {
      // 文件上传
      type = 'multipart/form-data'
    }
    const headers = { 'Content-Type': type }
    config = config
      ? {
          ...config,
          headers,
        }
      : { headers }
  }
  return {
    data,
    config,
  }
}

// 发送delete请求
export function del<T>(url: string, data?: any): Promise<T> {
  return requestClient.delete(url, data)
}

// 发送put请求
export function put<T>(
  url: string,
  data?: any,
  config?: RequestClientConfig,
): Promise<T> {
  return requestClient.put(url, data, config)
}

// 发送post请求（JSON格式）
export function post<T>(
  url: string,
  data?: any,
  config?: RequestClientConfig,
): Promise<T> {
  const res = processDataAndConfig('application/json', data, config)
  return requestClient.post(url, res.data, res.config)
}

// 发送post请求（表单格式）
export function postForm<T>(
  url: string,
  data?: any,
  config?: RequestClientConfig,
): Promise<T> {
  const res = processDataAndConfig(
    'application/x-www-form-urlencoded',
    data,
    config,
  )
  return requestClient.post(url, res.data, res.config)
}

// 发送post请求（表单格式带文件）
export function postMultipart<T>(
  url: string,
  data?: any,
  config?: RequestClientConfig,
): Promise<T> {
  data = getMultipartData(data)
  if (data) {
    const headers = { 'Content-Type': 'multipart/form-data' }
    config = config
      ? {
          ...config,
          headers,
        }
      : { headers }
  }
  return requestClient.post(url, data, config)
}
