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 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 _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, useRef, forwardRef, useImperativeHandle } from 'react';
import { Form } from 'antd';
import { useMemoizedFn } from 'ahooks';
import classNames from 'classnames';
import JsonWrapperContext from "../dataSourceForm/provider/jsonWrapper/JsonWrapperContext";
import DataSourceProvider from "../provider/dataSource/DataSourceProvider";
import FormSettingProvider from "../dataSourceForm/provider/formSetting/FormSettingProvider";
// ===================== 工具函数 =====================

/**
 * @title 提取多语言文本
 * @description 兼容字符串、数字、多语言对象格式，返回可显示文本
 */
var getI18nText = function getI18nText(value) {
  if (value === null || value === undefined) {
    return '';
  }
  if (typeof value === 'string' || typeof value === 'number') {
    return "".concat(value);
  }
  if (_typeof(value) === 'object') {
    return value.original || value['zh-CN'] || value.en || value['zh-HK'] || value.ja || value.pt || '';
  }
  return '';
};

/**
 * @title 解析并规范化 xRecordSchema
 * @description 兼容字符串、数组、properties 和 fields 结构，统一成字段数组供渲染使用
 */
var normalizeRecordSchema = function normalizeRecordSchema(xRecordSchema) {
  var _rawSchema, _rawSchema2, _rawSchema3;
  if (!xRecordSchema) {
    return [];
  }
  var rawSchema = xRecordSchema;
  if (typeof xRecordSchema === 'string') {
    try {
      rawSchema = JSON.parse(xRecordSchema);
    } catch (error) {
      console.error('Failed to parse xRecordSchema:', error);
      return [];
    }
  }

  // 处理单个对象（非数组）的情况
  if (rawSchema && _typeof(rawSchema) === 'object' && !Array.isArray(rawSchema) && rawSchema.name) {
    rawSchema = [rawSchema];
  }

  /**
   * @title 规范化单个字段
   * @description 将各种格式的字段配置统一转换为标准格式
   */
  var normalizeSingleField = function normalizeSingleField(field, fallbackName) {
    var _uiSchema$xDataSour;
    var uiSchema = (field === null || field === void 0 ? void 0 : field.uiSchema) || {};
    var name = (field === null || field === void 0 ? void 0 : field.name) || fallbackName;
    if (!name) {
      return null;
    }

    // 确定组件类型
    var component = (uiSchema === null || uiSchema === void 0 ? void 0 : uiSchema['x-component']) || (field === null || field === void 0 ? void 0 : field.interface) || (field === null || field === void 0 ? void 0 : field.componentName) || (field === null || field === void 0 ? void 0 : field.component) || 'Input';

    // 合并组件属性
    var props = _objectSpread(_objectSpread({}, (uiSchema === null || uiSchema === void 0 ? void 0 : uiSchema['x-component-props']) || {}), (field === null || field === void 0 ? void 0 : field.props) || {});

    // 解析选项列表（优先使用 x-data-source.options，其次 enum，最后 options/props.options）
    var uiSchemaDataSourceOptions = (uiSchema === null || uiSchema === void 0 || (_uiSchema$xDataSour = uiSchema['x-data-source']) === null || _uiSchema$xDataSour === void 0 ? void 0 : _uiSchema$xDataSour.options) || [];
    var rawOptions = uiSchemaDataSourceOptions.length ? uiSchemaDataSourceOptions : (uiSchema === null || uiSchema === void 0 ? void 0 : uiSchema.enum) || (field === null || field === void 0 ? void 0 : field.options) || (props === null || props === void 0 ? void 0 : props.options) || [];
    var options = rawOptions.map(function (option) {
      if (typeof option === 'string' || typeof option === 'number') {
        return {
          label: option,
          value: option
        };
      }
      return _objectSpread(_objectSpread({}, option), {}, {
        label: getI18nText(option === null || option === void 0 ? void 0 : option.label) || (option === null || option === void 0 ? void 0 : option.value)
      });
    });

    // Select 类型字段：若字段 type 为 array 且未设置 mode，自动切换为多选
    if (component === 'Select' && (field === null || field === void 0 ? void 0 : field.type) === 'array' && !(props !== null && props !== void 0 && props.mode)) {
      props.mode = 'multiple';
    }
    return _objectSpread(_objectSpread({}, field), {}, {
      name: name,
      label: getI18nText(field === null || field === void 0 ? void 0 : field.label) || getI18nText(uiSchema === null || uiSchema === void 0 ? void 0 : uiSchema.title) || name,
      component: component,
      componentName: component,
      options: options,
      props: props,
      uiSchema: uiSchema
    });
  };
  if (Array.isArray(rawSchema)) {
    return rawSchema.map(function (item) {
      return normalizeSingleField(item);
    }).filter(Boolean);
  }
  if (Array.isArray((_rawSchema = rawSchema) === null || _rawSchema === void 0 ? void 0 : _rawSchema.fields)) {
    return rawSchema.fields.map(function (item) {
      return normalizeSingleField(item);
    }).filter(Boolean);
  }
  if (Array.isArray((_rawSchema2 = rawSchema) === null || _rawSchema2 === void 0 ? void 0 : _rawSchema2.children)) {
    return rawSchema.children.map(function (item) {
      return normalizeSingleField(item);
    }).filter(Boolean);
  }
  if ((_rawSchema3 = rawSchema) !== null && _rawSchema3 !== void 0 && _rawSchema3.properties && _typeof(rawSchema.properties) === 'object') {
    return Object.keys(rawSchema.properties).map(function (name) {
      return normalizeSingleField(rawSchema.properties[name], name);
    }).filter(Boolean);
  }
  return [];
};

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

/**
 * @title DataSourceSubForm 子表单组件
 * @description
 * 独立的子表单组件，专注于渲染一组表单字段。支持两种使用方式：
 * 1. 传入 children：使用低代码引擎渲染的子组件（优先）
 * 2. 传入 xRecordSchema：通过配置自动生成表单字段（fallback）
 *
 * 值结构: { field1: v1, field2: v2 }
 */
var DataSourceSubForm = /*#__PURE__*/forwardRef(function (props, ref) {
  var activeKey = props.activeKey,
    _props$value = props.value,
    value = _props$value === void 0 ? {} : _props$value,
    onChange = props.onChange,
    children = props.children,
    xRecordSchema = props.xRecordSchema,
    _props$renderMode = props.renderMode,
    renderMode = _props$renderMode === void 0 ? 'edit' : _props$renderMode,
    __designMode = props.__designMode,
    className = props.className,
    style = props.style;
  var _Form$useForm = Form.useForm(),
    _Form$useForm2 = _slicedToArray(_Form$useForm, 1),
    innerForm = _Form$useForm2[0];
  var activeKeyRef = useRef(activeKey);

  /** 确保 value 是对象 */
  var safeValue = useMemo(function () {
    if (value && _typeof(value) === 'object' && !Array.isArray(value)) {
      return value;
    }
    return {};
  }, [value]);
  useImperativeHandle(ref, function () {
    return {
      getFieldsValue: function getFieldsValue() {
        return innerForm.getFieldsValue();
      }
    };
  });

  /** 当外部 value 变化时，同步到内部 Form */
  useEffect(function () {
    if (activeKeyRef.current !== activeKey) {
      activeKeyRef.current = activeKey;
      innerForm.resetFields();
    }
    innerForm.setFieldsValue(safeValue);
  }, [safeValue, innerForm, activeKey]);

  /** 内部 Form 值变化 -> 通知外部 */
  var handleValuesChange = useMemoizedFn(function (_, allValues) {
    onChange === null || onChange === void 0 || onChange(_objectSpread(_objectSpread({}, safeValue), allValues));
  });

  /** 解析 xRecordSchema 为字段数组 */
  var fields = useMemo(function () {
    return normalizeRecordSchema(xRecordSchema);
  }, [xRecordSchema]);

  /**
   * @title 判断是否有有效的低代码子组件
   * @description 排除引擎注入的空容器占位符
   */
  var hasRealChildren = useMemo(function () {
    var childArray = React.Children.toArray(children);
    if (childArray.length === 0) return false;
    return childArray.some(function (child) {
      return /*#__PURE__*/React.isValidElement(child);
    });
  }, [children]);

  /**
   * @title 创建模拟数据源
   * @description 供 DataSourceProvider 消费，使子组件（如 Select）可访问字段元信息
   */
  var mockDataSource = useMemo(function () {
    if (!fields || fields.length === 0) return null;
    // 仅提供字段元信息供 DataSourceProvider 消费；其余必填字段以 as any 绕过类型检查
    return {
      fields: fields.map(function (field) {
        return {
          name: field.name,
          uiSchema: field.uiSchema,
          interface: field.interface
        };
      }),
      name: 'dataSourceSubForm',
      tableName: 'dataSourceSubForm'
    };
  }, [fields]);

  /**
   * @title 渲染表单核心内容
   * @description
   * - 有 children：渲染低代码引擎注入的子组件
   * - 无 children 但有 fields：用 renderFormItem 逐字段渲染 Antd 控件
   * - 两者均无：显示空状态提示
   */
  var renderFormContent = function renderFormContent() {
    if (!hasRealChildren && fields.length === 0) {
      return /*#__PURE__*/React.createElement("div", {
        className: "pisell-data-source-sub-form__empty"
      }, "No fields configured. Please configure xRecordSchema or add children components.");
    }
    var formContent = /*#__PURE__*/React.createElement(JsonWrapperContext.Provider, {
      value: {
        path: [],
        level: 0
      }
    }, /*#__PURE__*/React.createElement(Form, {
      form: innerForm,
      onValuesChange: handleValuesChange,
      component: false,
      layout: "vertical"
    }, children));

    // 提供完整上下文（mockDataSource 存在时包裹 DataSourceProvider）
    if (mockDataSource) {
      return /*#__PURE__*/React.createElement(FormSettingProvider, {
        renderMode: renderMode,
        groupInfoPosition: "top",
        size: "large"
      }, /*#__PURE__*/React.createElement(DataSourceProvider, {
        dataSource: mockDataSource,
        __designMode: __designMode
      }, formContent));
    }
    return /*#__PURE__*/React.createElement(FormSettingProvider, {
      renderMode: renderMode,
      groupInfoPosition: "top",
      size: "large"
    }, formContent);
  };
  return /*#__PURE__*/React.createElement("div", {
    className: classNames('pisell-data-source-sub-form', className),
    style: style
  }, renderFormContent());
});
export default DataSourceSubForm;