import { UploadApiResult } from './model/uploadModel';
import { defHttp } from '/@/utils/http/axios';
import { UploadFileParams } from '/#/axios';
import { useGlobSetting } from '/@/hooks/setting';
import { AxiosProgressEvent } from 'axios';

const { uploadUrl = '' } = useGlobSetting();

/**
 * @description: Upload interface
 */
export function uploadApi(
  params: UploadFileParams,
  onUploadProgress: (progressEvent: AxiosProgressEvent) => void,
  keepFileName = true,
) {
  return defHttp
    .uploadFile<UploadApiResult>(
      {
        url: uploadUrl,
        onUploadProgress,
        params: { keepFileName },
      },
      params,
    )
    .then((res) => {
      let url = (res.data as any).result;
      if (uploadUrl.startsWith('http')) {
        const uploadServerUrl = new URL(uploadUrl);
        url = `${uploadServerUrl.protocol}//${uploadServerUrl.host}${url}`;
      }
      res.data = {
        ...res.data,
        url,
      } as UploadApiResult;
      return res;
    });
}
