"use strict";

require("core-js/modules/es.array.iterator.js");
require("core-js/modules/web.dom-collections.iterator.js");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.FormListContext = void 0;
require("core-js/modules/es.array.flat.js");
require("core-js/modules/es.array.unscopables.flat.js");
var _react = _interopRequireWildcard(require("react"));
var _omit = _interopRequireDefault(require("omit.js"));
var _toArray = _interopRequireDefault(require("rc-util/lib/Children/toArray"));
var _icons = require("@wii/icons");
var _get = _interopRequireDefault(require("rc-util/lib/utils/get"));
var _utils = require("../../../utils");
var _button = _interopRequireDefault(require("../../../button"));
var _form = _interopRequireDefault(require("../../../form"));
var _tooltip = _interopRequireDefault(require("../../../tooltip"));
var _configProvider = _interopRequireDefault(require("../../../config-provider"));
var _jsxRuntime = require("react/jsx-runtime");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
/* eslint-disable @typescript-eslint/no-unused-vars */

const FormListContext = /*#__PURE__*/_react.default.createContext({});

// type ChildrenFunction = (
//   fields: FormListFieldData[],
//   operation: FormListOperation,
//   meta: {
//     errors: React.ReactNode[];
//   },
// ) => React.ReactNode;
exports.FormListContext = FormListContext;
/** Antd 自带的toArray 不这次方法，所以需要自己搞一个 */
const listToArray = children => {
  if (Array.isArray(children)) {
    return children;
  }
  if (typeof children === 'function') {
    return [children];
  }
  return (0, _toArray.default)(children);
};
const ProFormListItem = props => {
  var _formInstance$getFiel;
  const {
    creatorButtonProps,
    deleteIconProps,
    copyIconProps,
    itemContainerRender,
    itemRender,
    prefixCls,
    creatorRecord,
    action,
    children,
    actionRender,
    fields,
    meta,
    field,
    index,
    formInstance,
    ...rest
  } = props;
  const listContext = (0, _react.useContext)(FormListContext);
  const childrenArray = listToArray(children).map(childrenItem => {
    if (typeof childrenItem === 'function') {
      return childrenItem === null || childrenItem === void 0 ? void 0 : childrenItem(field, index, action);
    }
    return childrenItem;
  }).map((childrenItem, childIndex) => {
    if ( /*#__PURE__*/_react.default.isValidElement(childrenItem)) {
      return /*#__PURE__*/_react.default.cloneElement(childrenItem, {
        // eslint-disable-next-line react/no-array-index-key
        key: childIndex,
        ...(childrenItem === null || childrenItem === void 0 ? void 0 : childrenItem.props)
      });
    }
    return childrenItem;
  });
  const copyIcon = (0, _react.useMemo)(() => {
    /** 复制按钮的配置 */
    if (!copyIconProps) return null;
    const {
      Icon = _icons.CopyOutlined,
      tooltipText
    } = copyIconProps;
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(_tooltip.default, {
      title: tooltipText,
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(Icon, {
        className: `${prefixCls}-action-icon`,
        onClick: () => {
          action.add(formInstance === null || formInstance === void 0 ? void 0 : formInstance.getFieldValue([listContext.listName, rest.name, field.name].filter(item => item !== undefined).flat(1)));
        }
      })
    }, "copy");
  }, [action, copyIconProps, field.name, formInstance, listContext.listName, prefixCls, rest.name]);
  const deleteIcon = (0, _react.useMemo)(() => {
    if (!deleteIconProps) return null;
    const {
      Icon = _icons.DeleteOutlined,
      tooltipText
    } = deleteIconProps;
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(_tooltip.default, {
      title: tooltipText,
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(Icon, {
        className: `${prefixCls}-action-icon`,
        onClick: () => action.remove(field.name)
      })
    }, "delete");
  }, [action, deleteIconProps, field.name, prefixCls]);
  const defaultActionDom = (0, _react.useMemo)(() => [copyIcon, deleteIcon].filter(Boolean), [copyIcon, deleteIcon]);
  const actions = (actionRender === null || actionRender === void 0 ? void 0 : actionRender(field, action, defaultActionDom)) || defaultActionDom;
  const dom = actions.length > 0 ? /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
    className: `${prefixCls}-action`,
    children: actions
  }) : null;
  const options = {
    field,
    index,
    record: formInstance === null || formInstance === void 0 ? void 0 : (_formInstance$getFiel = formInstance.getFieldValue) === null || _formInstance$getFiel === void 0 ? void 0 : _formInstance$getFiel.call(formInstance, [listContext.listName, rest.name, field.name].filter(item => item !== undefined).flat(1)),
    fields,
    operation: action,
    meta
  };
  const itemContainer = (itemContainerRender === null || itemContainerRender === void 0 ? void 0 : itemContainerRender(childrenArray, options)) || childrenArray;
  const contentDom = (itemRender === null || itemRender === void 0 ? void 0 : itemRender({
    listDom: /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      className: `${prefixCls}-container`,
      children: itemContainer
    }),
    action: dom
  }, options)) || /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
    className: `${prefixCls}-item`,
    style: {
      display: 'flex',
      alignItems: 'flex-end'
    },
    children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      className: `${prefixCls}-container`,
      children: itemContainer
    }), dom]
  });
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(FormListContext.Provider, {
    value: {
      ...field,
      listName: [listContext.listName, rest.originName, field.name].filter(item => item !== undefined).flat(1)
    },
    children: contentDom
  }, field.name);
};
const ProFormListContainer = props => {
  const {
    creatorButtonProps,
    prefixCls,
    children,
    creatorRecord,
    action,
    fields
  } = props;
  const creatorButton = (0, _react.useMemo)(() => {
    if (creatorButtonProps === false) return null;
    const {
      position = 'bottom',
      creatorButtonText = '添加一行数据'
    } = creatorButtonProps || {};
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(_button.default, {
      className: `${prefixCls}-creator-button-${position}`,
      type: "dashed",
      block: true,
      icon: /*#__PURE__*/(0, _jsxRuntime.jsx)(_icons.PlusOutlined, {}),
      ...(0, _omit.default)(creatorButtonProps || {}, ['position', 'creatorButtonText']),
      onClick: () => {
        let index;
        // 如果是顶部，加到第一个，如果不是，为空就是最后一个
        if (position === 'top') index = 0;
        action.add((0, _utils.runFunction)(creatorRecord), index);
      },
      children: creatorButtonText
    });
  }, [action, creatorButtonProps, creatorRecord, prefixCls]);
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
    style: {
      width: 'max-content',
      maxWidth: '100%'
    },
    children: [creatorButtonProps !== false && (creatorButtonProps === null || creatorButtonProps === void 0 ? void 0 : creatorButtonProps.position) === 'top' && creatorButton, fields.map((field, index) => /*#__PURE__*/(0, _jsxRuntime.jsx)(ProFormListItem, {
      ...props,
      field: field,
      index: index,
      children: children
    }, field.key)), creatorButtonProps !== false && (creatorButtonProps === null || creatorButtonProps === void 0 ? void 0 : creatorButtonProps.position) !== 'top' && creatorButton]
  });
};
const ProFormList = ({
  actionRender,
  creatorButtonProps,
  label,
  tooltip,
  creatorRecord,
  itemRender,
  rules,
  itemContainerRender,
  copyIconProps = {
    Icon: _icons.CopyOutlined,
    tooltipText: '复制此行'
  },
  children,
  deleteIconProps = {
    Icon: _icons.DeleteOutlined,
    tooltipText: '删除此行'
  },
  actionRef,
  ...rest
}) => {
  const actionRefs = (0, _react.useRef)();
  const context = (0, _react.useContext)(_configProvider.default.ConfigContext);
  const listContext = (0, _react.useContext)(FormListContext);
  const baseClassName = context.getPrefixCls('pro-form-list');
  // 处理 list 的嵌套
  const name = (0, _react.useMemo)(() => {
    if (listContext.name === undefined) {
      return [rest.name].flat(1);
    }
    return [listContext.name, rest.name].flat(1);
  }, [listContext.name, rest.name]);

  // eslint-disable-next-line react-hooks/exhaustive-deps
  (0, _react.useImperativeHandle)(actionRef, () => actionRefs.current, [actionRefs.current]);
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_form.default.Item, {
    label: label,
    tooltip: tooltip,
    rules: rules,
    shouldUpdate: (prevValues, nextValues) => {
      return (0, _get.default)(prevValues, name) !== (0, _get.default)(nextValues, name);
    },
    children: formInstance => {
      return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        className: baseClassName,
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_form.default.List, {
          rules: rules,
          ...rest,
          name: name,
          children: (fields, action, meta) => {
            // 将 action 暴露给外部
            actionRefs.current = action;
            return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
              children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(ProFormListContainer, {
                name: name,
                originName: rest.name,
                copyIconProps: copyIconProps,
                deleteIconProps: deleteIconProps,
                formInstance: formInstance,
                prefixCls: baseClassName,
                meta: meta,
                fields: fields,
                itemContainerRender: itemContainerRender,
                itemRender: itemRender,
                creatorButtonProps: creatorButtonProps,
                creatorRecord: creatorRecord,
                actionRender: actionRender,
                action: action,
                children: children
              }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_form.default.ErrorList, {
                errors: meta.errors
              })]
            });
          }
        })
      });
    }
  });
};
var _default = ProFormList;
exports.default = _default;