"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _hooks = require("@teamix/hooks");
var _utils = require("@teamix/utils");
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var _default = function _default(bindUrl, functions, formRef) {
  // 预处理 bindUrl 参数（主要兼容 SelectGroup 组件）
  var initializeBindUrl = function initializeBindUrl(options) {
    return options ? _objectSpread(_objectSpread({}, options), {}, {
      beforeStringify: function beforeStringify(values) {
        var _Object$entries;
        var beforeStringify = options.beforeStringify;
        var newValues = _objectSpread({}, values);
        (_Object$entries = Object.entries(values)) === null || _Object$entries === void 0 ? void 0 : _Object$entries.forEach(function (_ref) {
          var _form$query;
          var _ref2 = _slicedToArray(_ref, 2),
            key = _ref2[0],
            value = _ref2[1];
          var form = formRef.current;
          var field = (_form$query = form.query(key)) === null || _form$query === void 0 ? void 0 : _form$query.take();
          if ((field === null || field === void 0 ? void 0 : field.component[0]) === 'SelectGroup') {
            newValues[key] = value.map(function (_ref3) {
              var key = _ref3.key,
                value = _ref3.value;
              return key && value ? "".concat(key, "||").concat(value === null || value === void 0 ? void 0 : value.join('|')) : '';
            });
          }
        });
        return beforeStringify ? beforeStringify(newValues) : newValues;
      }
    }) : options;
  };
  // 通过 useUrlState 获取 url 上的参数和 url 配置方法
  var _ref4 = bindUrl ? (0, _hooks.useUrlState)(undefined, initializeBindUrl((0, _utils.isPlainObj)(bindUrl) ? bindUrl : {})) : [],
    _ref5 = _slicedToArray(_ref4, 2),
    urlState = _ref5[0],
    setUrlState = _ref5[1];
  // 输出配置url参数的函数
  var initializedFunctions = Object.entries(functions).reduce(function (prev, _ref6) {
    var _ref7 = _slicedToArray(_ref6, 2),
      key = _ref7[0],
      fun = _ref7[1];
    prev[key] = function (values) {
      fun === null || fun === void 0 ? void 0 : fun(values);
      setUrlState === null || setUrlState === void 0 ? void 0 : setUrlState(values);
    };
    return prev;
  }, {});
  // 使用 url 参数配置 QueryFilter 默认值（移除非表单值，兼容数组数据，兼容 SelectGroup 组件）
  var setValuesByUrlState = function setValuesByUrlState(form) {
    if (urlState) {
      var _Object$entries2;
      (_Object$entries2 = Object.entries(urlState)) === null || _Object$entries2 === void 0 ? void 0 : _Object$entries2.forEach(function (_ref8) {
        var _form$query2;
        var _ref9 = _slicedToArray(_ref8, 2),
          key = _ref9[0],
          value = _ref9[1];
        var field = (_form$query2 = form.query(key)) === null || _form$query2 === void 0 ? void 0 : _form$query2.take();
        if (field) {
          var newValue = value;
          if (field.displayName === 'ArrayField') {
            newValue = [].concat((0, _utils.isUsable)(newValue) ? newValue : []);
          }
          if (field.component[0] === 'SelectGroup') {
            newValue = newValue.map(function (item) {
              var _item$split = item === null || item === void 0 ? void 0 : item.split('||'),
                _item$split2 = _slicedToArray(_item$split, 2),
                key = _item$split2[0],
                value = _item$split2[1];
              return {
                key: key,
                value: value === null || value === void 0 ? void 0 : value.split('|')
              };
            });
          }
          form.setValuesIn(key, newValue);
        }
      });
    }
  };
  return _objectSpread({
    setValuesByUrlState: setValuesByUrlState
  }, initializedFunctions);
};
exports.default = _default;