import type { UploadFile } from 'ant-design-vue'
/**
 * 金额转 usd
 * @param num 需要转换的数字
 * @param precision 小数点精度
 * @returns
 */
export const toUSD = (num: number | string, precision: number = 2): string => {
  return parseFloat(num + '').toFixed(precision) + ' USD'
}

export const enumsMap = (code: string, enums: Array<{ value: string; text: string }>): string => {
  return enums.find((item) => item.value === code)?.text || ''
}

/**
 * 判断页面类型
 * 用于区分 新增编辑详情
 * @param type
 * @returns
 */
export const isPage = (type: string) => {
  return window.location.pathname.split('/').pop() === type
}

export const deepClone = (target: {}) => {
  return JSON.parse(JSON.stringify(target))
}

/**
 * 合并对象 使用前者的key 使用后者的value
 * @param obj1
 * @param obj2
 */
export const mergeObj = (obj1: {}, obj2: {}) => {
  for (const key in obj1) {
    if (obj2[key]) {
      obj1[key] = obj2[key]
    }
  }
  return obj1
}

/**
 * 下载文件
 * @returns
 */
export const downloadFile = async (url: string, name: string) => {
  try {
    const response = await fetch(url)
    if (!response.ok) {
      throw new Error('下载失败')
    }
    const blob = await response.blob()
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = name
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  } catch (error) {
    console.error(error)
  }
}

/**
 * 使用a链接下载文件,使用promise封装
 */
export const downloadFileByA = (url: string, name: string) => {
  try {
    const link = document.createElement('a')
    link.href = url
    link.download = name
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  } catch (error) {
    console.log(error)
  }
}

/**
 * 获取URL参数并合并为对象（支持重复参数数组化）
 * @param {string} [url=location.href] - 目标URL（默认当前页）
 * @returns {Object} 参数对象
 */
export const getUrlParamsObj = (url = window.location.href) => {
  const params = new URLSearchParams(new URL(url).search)
  const result: any = {}
  for (const [key, value] of params) {
    const decodedKey = decodeURIComponent(key)
    const decodedValue = decodeURIComponent(value)

    if (result.hasOwnProperty(decodedKey)) {
      result[decodedKey] = [].concat(result[decodedKey], decodedValue)
    } else {
      result[decodedKey] = decodedValue
    }
  }

  return result
}
/**
 * 是否为空对象
 */
export function isEmptyObject(obj: any): boolean {
  return (
    obj && // 检查非空
    typeof obj === 'object' && // 确认是对象类型
    !Array.isArray(obj) && // 排除数组
    Object.keys(obj).length === 0 // 检查属性数量
  )
}
