function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
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(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
import React, { useEffect, useMemo, useState, useRef } from 'react';
import { withMode } from "../../dataSourceForm/utils";
import ReadPretty from "./ReadPretty";
import Tabs from "../Tabs/Tabs";
import DataSourceSubForm from "../../dataSourceSubForm";

// ===================== 主组件 =====================

/**
 * @title RecordListWrapper 编辑器
 * @description
 *   上部为插槽区域（topSlot），通过 cloneElement 注入 options/value/onChange，默认展示 Tabs 导航。
 *   下部委托给 DataSourceSubForm 渲染当前 activeKey 对应的子表单。
 *   切换 tab 时通过 key={activeKey} 强制重新挂载 DataSourceSubForm，实现值自动同步。
 *
 *   值结构: { [optionValue]: { field1: v1, field2: v2 } }
 */
var RecordListWrapperBase = function RecordListWrapperBase(props) {
  var value = props.value,
    _onChange = props.onChange,
    _props$options = props.options,
    options = _props$options === void 0 ? [] : _props$options,
    children = props.children,
    xRecordSchema = props.xRecordSchema,
    topSlot = props.topSlot,
    slot = props.slot,
    renderMode = props.renderMode,
    __designMode = props.__designMode,
    defaultValue = props.defaultValue;
  var isMounted = useRef(false);
  var dataSourceSubFormRef = useRef(null);

  /** value 是 Map: { optionValue: { field1: v1 } } */
  var safeValue = useMemo(function () {
    if (value && _typeof(value) === 'object' && !Array.isArray(value)) {
      return value;
    }
    return {};
  }, [value]);

  /**
   * 当前选中的 option key
   * 优先级：defaultActiveKey > options[0].value
   */
  var _useState = useState(function () {
      var _options$;
      if (defaultValue != null) return String(defaultValue);
      return String(((_options$ = options[0]) === null || _options$ === void 0 ? void 0 : _options$.value) || '');
    }),
    _useState2 = _slicedToArray(_useState, 2),
    activeKey = _useState2[0],
    setActiveKey = _useState2[1];

  /** defaultValue 变化时同步更新 activeKey */
  useEffect(function () {
    if (defaultValue != null) {
      setActiveKey(String(defaultValue));
    }
  }, [defaultValue]);

  /** options 变化时校正 activeKey（仅在无 defaultValue 且当前 key 不合法时回退） */
  useEffect(function () {
    if (options.length && !options.find(function (o) {
      return String(o.value) === activeKey;
    })) {
      var _options$2;
      setActiveKey(defaultValue != null ? String(defaultValue) : String(((_options$2 = options[0]) === null || _options$2 === void 0 ? void 0 : _options$2.value) || ''));
    }
  }, [options]);

  /**
   * 初始化所有 option 的值：
   * 以字段 schema 中的 uiSchema.default 作为每个 option 的默认值模板，
   * 已有值（safeValue）优先覆盖，确保已填写的数据不丢失。
   * 仅执行一次（由 isMounted 守卫），避免重复触发 onChange。
   */
  useEffect(function () {
    if (isMounted.current) {
      return;
    }
    if ((options === null || options === void 0 ? void 0 : options.length) > 0 && dataSourceSubFormRef.current) {
      var _dataSourceSubFormRef, _dataSourceSubFormRef2, _dataSourceSubFormRef3;
      var defaultValues = (_dataSourceSubFormRef = (_dataSourceSubFormRef2 = (_dataSourceSubFormRef3 = dataSourceSubFormRef.current).getFieldsValue) === null || _dataSourceSubFormRef2 === void 0 ? void 0 : _dataSourceSubFormRef2.call(_dataSourceSubFormRef3)) !== null && _dataSourceSubFormRef !== void 0 ? _dataSourceSubFormRef : {};
      var completeValue = options.reduce(function (acc, option) {
        if (option.value === null || option.value === undefined) return acc;
        acc[String(option.value)] = _objectSpread(_objectSpread({}, defaultValues), safeValue[String(option.value)] || {});
        return acc;
      }, {});
      _onChange === null || _onChange === void 0 || _onChange(completeValue);
      isMounted.current = true;
    }
  }, [options, safeValue]);

  // ---- 上部: 插槽区域 ----
  var renderTopSlot = function renderTopSlot() {
    var slotElement = topSlot || slot;
    if (slotElement && /*#__PURE__*/React.isValidElement(slotElement)) {
      // cloneElement 注入 options / value(activeKey) / onChange(setActiveKey)
      return /*#__PURE__*/React.cloneElement(slotElement, {
        options: options,
        value: activeKey,
        onChange: setActiveKey
      });
    }

    // TabOption.label 为必填，RecordListWrapperOption.label 可选，fallback 到 value
    var tabOptions = options.map(function (o) {
      var _o$label;
      return _objectSpread(_objectSpread({}, o), {}, {
        label: (_o$label = o.label) !== null && _o$label !== void 0 ? _o$label : String(o.value)
      });
    });
    if (!options.length) {
      return /*#__PURE__*/React.createElement("div", {
        style: {
          color: '#999',
          fontSize: 16
        }
      }, "\u6682\u65E0\u9009\u9879\uFF0C\u8BF7\u914D\u7F6E\u6570\u636E\u6E90\u3002");
    }
    return /*#__PURE__*/React.createElement(Tabs, {
      options: tabOptions,
      value: activeKey,
      onChange: function onChange(key) {
        return setActiveKey(String(key));
      },
      disabled: renderMode === 'disabled'
    });
  };

  // ---- 下部: 委托给 DataSourceSubForm ----
  var renderBottom = function renderBottom() {
    return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(DataSourceSubForm, {
      activeKey: activeKey,
      value: safeValue[activeKey],
      onChange: function onChange(recordValue) {
        return _onChange === null || _onChange === void 0 ? void 0 : _onChange(_objectSpread(_objectSpread({}, safeValue || {}), {}, _defineProperty({}, activeKey, recordValue || {})));
      },
      xRecordSchema: xRecordSchema,
      renderMode: renderMode,
      __designMode: __designMode
    }, children), /*#__PURE__*/React.createElement("div", {
      style: {
        width: '100%',
        height: 0,
        visibility: 'hidden',
        overflow: 'hidden'
      }
    }, /*#__PURE__*/React.createElement(DataSourceSubForm, {
      key: "record-list-wrapper-default-value-form",
      ref: dataSourceSubFormRef,
      xRecordSchema: xRecordSchema,
      renderMode: renderMode,
      __designMode: __designMode
    }, children)));
  };
  return /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("div", {
    style: {
      marginBottom: 12
    }
  }, renderTopSlot()), renderBottom());
};
var RecordListWrapperWithMode = withMode(RecordListWrapperBase, ReadPretty);
export default RecordListWrapperWithMode;