import { createAlova } from 'alova';
import VueHook from 'alova/vue';
import { xhrRequestAdapter } from '@alova/adapter-xhr';
import { getToken } from '@/request/tools';

import { notification } from 'ant-design-vue';

const request = createAlova({
  baseURL: '/manager/',
  statesHook: VueHook,
  requestAdapter: xhrRequestAdapter(),
  async beforeRequest(method) {
    if (!method.config.meta?.ignoreToken) method.config.headers.Authorization ??= getToken();
  },
  responded: {
    async onSuccess(response, method) {
      try {
        if (response.status >= 400) throw new Error(`${response.statusText}(${response.status})`);
        const result = await response.data;
        /* 接口修正 code */
        if (result.success !== false && result.code === 200) result.code = 0;
        const { error = false, warn = false, code = error || warn ? -1 : 0, msg: message = '未知错误', data } = result;
        if (code === 0) return data;
        throw new Error(`${message}(${code})`);
      } catch (e: any) {
        if (!method.meta?.ignoreException) {
          notification.error({
            message: method.url,
            description: e?.message,
            key: method.url,
          });
        }
        throw e;
      }
    },
  },
});

export default function upload(file: File, ignoreException = false) {
  const formData = new FormData();
  formData.append('file', file);
  return request.Post<{ url: string; name: string }>(`/file/upload`, formData, {
    meta: { ignoreException },
  });
}
