import config from '../../../config/index.js'

/**
 * 使用原生 fetch 发送 multipart/form-data，不设置 Content-Type，由浏览器自动带 boundary，
 * 确保后端从 ctx.request.files 接收文件
 */
async function uploadOosImgWithFormData(formData) {
  const apiUrl = (config.apiUrl || '').replace(/\/$/, '')
  const url = `${apiUrl}/sys_file/upload_oos_img`
  const headers = {}
  if (window.framework && typeof window.framework.getToken === 'function') {
    const token = window.framework.getToken()
    if (token) headers['Authorization'] = token
  }
  const response = await fetch(url, { method: 'POST', headers, body: formData })
  const data = await response.json().catch(() => ({}))
  return data
}

class FileServe {
  async upload_oos_img(row) {
    if (row instanceof FormData) {
      return uploadOosImgWithFormData(row)
    }
    let res = await window.framework.http.postFormData('/sys_file/upload_oos_img', row)
    return res
  }

  async upload_Img(row) {
    let res =  await window.framework.http.postFormData("/file/upload_Img", row);
    return res;
  }
}

const fileServe = new FileServe();
export default fileServe;
