import useHttp from "../axios/index.mjs";
const useDataSource = (dataSourceJson) => {
  var _a, _b;
  if (!dataSourceJson) {
    return;
  }
  const dataSource = JSON.parse(dataSourceJson.replace(/'/g, '"'));
  const globalDataHandle = dataSource.dataHandler ? createFn(dataSource.dataHandler.value) : (res) => res;
  const http = useHttp(globalDataHandle);
  const shouldFetch = ((_a = dataSource.shouldFetch) == null ? void 0 : _a.value) ? createFn(dataSource.shouldFetch.value) : () => true;
  const willFetch = ((_b = dataSource.willFetch) == null ? void 0 : _b.value) ? createFn(dataSource.willFetch.value) : (options) => options;
  const dataHandler = (res) => {
    var _a2;
    const data = ((_a2 = dataSource.dataHandler) == null ? void 0 : _a2.value) ? createFn(dataSource.dataHandler.value)(res) : res;
    return data;
  };
  const errorHandler = (error) => {
    return Promise.reject(error);
  };
  http.interceptors.request.use(willFetch, errorHandler);
  http.interceptors.response.use(dataHandler, errorHandler);
  return {
    load: createLoad(http, dataSource, shouldFetch)
  };
};
const createFn = (fnContent) => {
  return (...args) => {
    window.eval("var fn = " + fnContent);
    return fn.apply(void 0, args);
  };
};
const createLoad = (http, dataSource, shouldFetch) => (params) => {
  if (!shouldFetch()) {
    return;
  }
  if (dataSource.mockSwitch == "1") {
    let mockData = dataSource.mockData;
    return new Promise((resolve) => {
      const mockDataHandle = createFn(dataSource.mockDataHandlerValue);
      resolve(mockDataHandle(mockData));
    });
  }
  const {
    method,
    uri: url,
    params: defaultParams,
    timeout,
    headers,
    serviceAddr
  } = dataSource.options;
  const config = { method, url, headers, timeout };
  const data = params && JSON.stringify(params) != "{}" ? params : defaultParams;
  if (serviceAddr) {
    const serviceAddrValue = dataSource == null ? void 0 : dataSource.serviceAddr;
    const serviceAddrItem = serviceAddrValue == null ? void 0 : serviceAddrValue.find(
      (item) => item.name == serviceAddr
    );
    config.url = (serviceAddrItem == null ? void 0 : serviceAddrItem.url) ? serviceAddrItem.url + config.url : config.url;
  } else {
    config.url = config.url;
  }
  if (method.toLowerCase() === "get") {
    config.params = data;
  } else {
    config.data = data;
  }
  if (method.toLowerCase() === "upload") {
    config.headers = {
      "Content-Type": "multipart/form-data"
    };
    config.method = "post";
  }
  return http.request(config);
};
export {
  useDataSource
};
