import { Upload_URL } from "../../app.config";
import { upload as _upload } from "../wx/network";

import { token } from "../logic";

const Instance = (function createUploadRequest(option: IRequestCreateConfig) {
  const { baseURL } = option;

  return <R, T>(config: IUploadConfig<R, T>) => {
    let { url, data, params, header, meta, transform = (params: any) => params, ..._config } = config;

    url ??= `/upload`;
    header ??= {};


    header['Authorization'] = meta?.ignoreToken ? '' : option.token?.() ?? '';

    // header['patientId'] = wx.getStorageSync('patientId') ?? '';
    // header['doctorId'] = wx.getStorageSync('doctorId') ?? '';

    return _upload({
      url: /https?\:\/\//.test(url) ? url : `${baseURL}${url}`,
      header, formData: data, filePath: params.file, name: params.name, ..._config,
    }, (response => {
      const data = JSON.parse(response);
      if (data.code === 200 && data.success !== false)
        return transform({ data: data.data, header: {} });
      throw { errMsg: data.msg || `app:${data.code}`, errno: `060402${data.code}` }
    }));
  }
})({
  baseURL: Upload_URL,
  token: token
})

export function upload<R, T>(config: IUploadConfig<R, T>) {
  return Instance<R, T>(config)
}


