import "core-js/modules/es.array.flat.js";
import "core-js/modules/es.array.unscopables.flat.js";
/* eslint-disable @typescript-eslint/no-unused-vars */

import React, { useContext, useImperativeHandle, useRef, useMemo } from 'react';
import omit from 'omit.js';
import toArray from 'rc-util/lib/Children/toArray';
import { DeleteOutlined, PlusOutlined, CopyOutlined } from '@wii/icons';
import get from 'rc-util/lib/utils/get';
import { runFunction } from '../../../utils';
import Button from '../../../button';
import Form from '../../../form';
import Tooltip from '../../../tooltip';
import ConfigProvider from '../../../config-provider';
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
import { Fragment as _Fragment } from "react/jsx-runtime";
const FormListContext = /*#__PURE__*/React.createContext({});

// type ChildrenFunction = (
//   fields: FormListFieldData[],
//   operation: FormListOperation,
//   meta: {
//     errors: React.ReactNode[];
//   },
// ) => React.ReactNode;
/** Antd 自带的toArray 不这次方法，所以需要自己搞一个 */
const listToArray = children => {
  if (Array.isArray(children)) {
    return children;
  }
  if (typeof children === 'function') {
    return [children];
  }
  return toArray(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 = 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.isValidElement(childrenItem)) {
      return /*#__PURE__*/React.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 = useMemo(() => {
    /** 复制按钮的配置 */
    if (!copyIconProps) return null;
    const {
      Icon = CopyOutlined,
      tooltipText
    } = copyIconProps;
    return /*#__PURE__*/_jsx(Tooltip, {
      title: tooltipText,
      children: /*#__PURE__*/_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 = useMemo(() => {
    if (!deleteIconProps) return null;
    const {
      Icon = DeleteOutlined,
      tooltipText
    } = deleteIconProps;
    return /*#__PURE__*/_jsx(Tooltip, {
      title: tooltipText,
      children: /*#__PURE__*/_jsx(Icon, {
        className: `${prefixCls}-action-icon`,
        onClick: () => action.remove(field.name)
      })
    }, "delete");
  }, [action, deleteIconProps, field.name, prefixCls]);
  const defaultActionDom = 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__*/_jsx("div", {
    className: `${prefixCls}-action`,
    children: actions
  }) : null;
  const options = {
    field,
    index,
    record: formInstance === null || formInstance === 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__*/_jsx("div", {
      className: `${prefixCls}-container`,
      children: itemContainer
    }),
    action: dom
  }, options)) || /*#__PURE__*/_jsxs("div", {
    className: `${prefixCls}-item`,
    style: {
      display: 'flex',
      alignItems: 'flex-end'
    },
    children: [/*#__PURE__*/_jsx("div", {
      className: `${prefixCls}-container`,
      children: itemContainer
    }), dom]
  });
  return /*#__PURE__*/_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 = useMemo(() => {
    if (creatorButtonProps === false) return null;
    const {
      position = 'bottom',
      creatorButtonText = '添加一行数据'
    } = creatorButtonProps || {};
    return /*#__PURE__*/_jsx(Button, {
      className: `${prefixCls}-creator-button-${position}`,
      type: "dashed",
      block: true,
      icon: /*#__PURE__*/_jsx(PlusOutlined, {}),
      ...omit(creatorButtonProps || {}, ['position', 'creatorButtonText']),
      onClick: () => {
        let index;
        // 如果是顶部，加到第一个，如果不是，为空就是最后一个
        if (position === 'top') index = 0;
        action.add(runFunction(creatorRecord), index);
      },
      children: creatorButtonText
    });
  }, [action, creatorButtonProps, creatorRecord, prefixCls]);
  return /*#__PURE__*/_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__*/_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: CopyOutlined,
    tooltipText: '复制此行'
  },
  children,
  deleteIconProps = {
    Icon: DeleteOutlined,
    tooltipText: '删除此行'
  },
  actionRef,
  ...rest
}) => {
  const actionRefs = useRef();
  const context = useContext(ConfigProvider.ConfigContext);
  const listContext = useContext(FormListContext);
  const baseClassName = context.getPrefixCls('pro-form-list');
  // 处理 list 的嵌套
  const name = 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
  useImperativeHandle(actionRef, () => actionRefs.current, [actionRefs.current]);
  return /*#__PURE__*/_jsx(Form.Item, {
    label: label,
    tooltip: tooltip,
    rules: rules,
    shouldUpdate: (prevValues, nextValues) => {
      return get(prevValues, name) !== get(nextValues, name);
    },
    children: formInstance => {
      return /*#__PURE__*/_jsx("div", {
        className: baseClassName,
        children: /*#__PURE__*/_jsx(Form.List, {
          rules: rules,
          ...rest,
          name: name,
          children: (fields, action, meta) => {
            // 将 action 暴露给外部
            actionRefs.current = action;
            return /*#__PURE__*/_jsxs(_Fragment, {
              children: [/*#__PURE__*/_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__*/_jsx(Form.ErrorList, {
                errors: meta.errors
              })]
            });
          }
        })
      });
    }
  });
};
export { FormListContext };
export default ProFormList;