var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/components/dataSourceComponents/provider/variables/VariablesProvider.tsx
var VariablesProvider_exports = {};
__export(VariablesProvider_exports, {
  default: () => VariablesProvider_default
});
module.exports = __toCommonJS(VariablesProvider_exports);
var import_react = __toESM(require("react"));
var import_utils = require("@pisell/utils");
var import_ahooks = require("ahooks");
var import_useEngineContext = __toESM(require("../../../../hooks/useEngineContext"));
var import_VariablesContext = __toESM(require("./VariablesContext"));
var import_utils2 = require("../../dataSourceForm/utils");
var import_utils3 = require("../../../../utils");
var import_utils4 = require("./utils");
var defaultCustomizer = (objValue, srcValue) => {
  if ((0, import_utils.isArr)(srcValue)) {
    return srcValue;
  }
};
var VARIABLE_PATTERN = /{{([^}]+)}}/g;
var VariablesProvider = (props) => {
  var _a, _b, _c, _d;
  const { children, variables, config } = props;
  const context = (0, import_useEngineContext.default)();
  const disabledHistoryListener = config ?? ((_c = (_b = (_a = context == null ? void 0 : context.engine) == null ? void 0 : _a.props) == null ? void 0 : _b.variablesConfig) == null ? void 0 : _c.disabledHistoryListener);
  const { getApp } = ((_d = context == null ? void 0 : context.appHelper) == null ? void 0 : _d.utils) || {};
  const initialQuery = (0, import_react.useMemo)(() => {
    var _a2, _b2, _c2;
    if (disabledHistoryListener) {
      return {};
    }
    const currentLocation = (_c2 = (_b2 = (_a2 = getApp == null ? void 0 : getApp()) == null ? void 0 : _a2.history) == null ? void 0 : _b2.instance) == null ? void 0 : _c2.location;
    if (currentLocation == null ? void 0 : currentLocation.search) {
      const searchParams = new URLSearchParams(currentLocation.search);
      const query = {};
      searchParams.forEach((value2, key) => {
        query[key] = value2;
      });
      return query;
    }
    return {};
  }, [disabledHistoryListener]);
  const variablesRef = (0, import_react.useRef)(
    disabledHistoryListener ? variables || {} : (0, import_utils3.mergeWith)(
      variables,
      {
        global: {
          value: {
            query: initialQuery
          },
          query: initialQuery
        }
      },
      defaultCustomizer
    )
  );
  const listenersRef = (0, import_react.useRef)(/* @__PURE__ */ new Set());
  const setQueryVariable = (0, import_ahooks.useMemoizedFn)((search) => {
    if (disabledHistoryListener) {
      return;
    }
    const searchParams = new URLSearchParams(search);
    const query = {};
    searchParams.forEach((value2, key) => {
      query[key] = value2;
    });
    registerVariable({
      global: query
    });
  });
  (0, import_react.useEffect)(() => {
    var _a2, _b2, _c2;
    if (disabledHistoryListener) {
      return;
    }
    const unlisten = (_c2 = (_b2 = (_a2 = getApp == null ? void 0 : getApp()) == null ? void 0 : _a2.history) == null ? void 0 : _b2.instance) == null ? void 0 : _c2.listen((location) => {
      setQueryVariable(location.search);
    });
    return () => {
      unlisten == null ? void 0 : unlisten();
    };
  }, [disabledHistoryListener]);
  const registerVariable = (0, import_ahooks.useMemoizedFn)((value2) => {
    variablesRef.current = (0, import_utils3.mergeWith)(
      variablesRef.current,
      value2,
      defaultCustomizer
    );
    listenersRef.current.forEach(
      (listener) => listener(variablesRef.current, value2)
    );
    console.log("注册变量", value2, "全部变量", variablesRef.current);
  });
  const subscribeVariables = (0, import_ahooks.useMemoizedFn)(
    (listener) => {
      listenersRef.current.add(listener);
      return () => {
        listenersRef.current.delete(listener);
      };
    }
  );
  const registerValueVariable = (0, import_ahooks.useMemoizedFn)(
    (componentId, value2) => {
      const variable = (0, import_utils4.genComponentValueVariable)(componentId, value2);
      registerVariable == null ? void 0 : registerVariable(variable);
    }
  );
  const registerFunctionVariable = (0, import_ahooks.useMemoizedFn)(
    (componentId, value2) => {
      const variable = (0, import_utils4.genComponentFunctionVariable)(componentId, value2);
      registerVariable == null ? void 0 : registerVariable(variable);
    }
  );
  const parseVariable = (0, import_ahooks.useMemoizedFn)(
    (str, localVariables = {}) => {
      var _a2;
      if (!(0, import_utils.isString)(str)) {
        return str;
      }
      if (((_a2 = str.match(VARIABLE_PATTERN)) == null ? void 0 : _a2[0]) === str) {
        const key = (0, import_utils4.getVariableKey)(str);
        if (!key) return str;
        const localValue = (0, import_utils2.getNestedValue)(localVariables, key);
        if (!(0, import_utils.isUndefined)(localValue)) {
          return localValue;
        }
        const globalValue = (0, import_utils2.getNestedValue)(variablesRef.current, key);
        return (0, import_utils.isUndefined)(globalValue) ? str : globalValue;
      }
      return str.replace(VARIABLE_PATTERN, (match, key) => {
        const localValue = (0, import_utils2.getNestedValue)(localVariables, key);
        if (!(0, import_utils.isUndefined)(localValue)) {
          return localValue;
        }
        const globalValue = (0, import_utils2.getNestedValue)(variablesRef.current, key);
        return (0, import_utils.isUndefined)(globalValue) ? match : globalValue;
      });
    }
  );
  const value = (0, import_react.useMemo)(
    () => ({
      variables: variablesRef.current,
      registerVariable,
      parseVariable,
      registerValueVariable,
      registerFunctionVariable,
      subscribeVariables
    }),
    [
      registerVariable,
      parseVariable,
      registerValueVariable,
      registerFunctionVariable,
      subscribeVariables
    ]
  );
  return /* @__PURE__ */ import_react.default.createElement(import_VariablesContext.default.Provider, { value }, children);
};
var VariablesProvider_default = VariablesProvider;
