import "core-js/modules/es.array.iterator.js";
import "core-js/modules/web.dom-collections.iterator.js";
import "core-js/modules/es.array.reduce.js";
import React, { useContext, useImperativeHandle, useRef } from 'react';
import classNames from 'classnames';
import { ObjToMap, proFieldParsingText, useFieldFetchData } from '../wau-select-field';
import Checkbox from '../checkbox';
import ConfigProvider from '../config-provider';
import Space from '../space';
import Spin from '../spin';
import './style';
import { jsx as _jsx } from "react/jsx-runtime";
import { Fragment as _Fragment } from "react/jsx-runtime";
/**
 * 多选组件
 *
 * @param param0
 * @param ref
 */
const FieldCheckbox = ({
  layout = 'horizontal',
  renderFormItem,
  mode,
  render,
  ...rest
}, ref) => {
  const {
    getPrefixCls
  } = useContext(ConfigProvider.ConfigContext);
  const layoutClassName = getPrefixCls('pro-field-checkbox');
  const [loading, options, fetchData] = useFieldFetchData(rest);
  const checkBoxRef = useRef();
  useImperativeHandle(ref, () => ({
    ...(checkBoxRef.current || {}),
    fetchData: () => fetchData()
  }));
  if (loading) {
    return /*#__PURE__*/_jsx(Spin, {
      size: "small"
    });
  }
  if (mode === 'read') {
    const optionsValueEnum = options !== null && options !== void 0 && options.length ? options === null || options === void 0 ? void 0 : options.reduce((pre, cur) => {
      return {
        ...pre,
        [cur.value]: cur.label
      };
    }, {}) : undefined;
    const dom = proFieldParsingText(rest.text, ObjToMap(rest.valueEnum || optionsValueEnum));
    if (render) {
      return render(rest.text, {
        mode,
        ...rest.fieldProps
      }, /*#__PURE__*/_jsx(_Fragment, {
        children: dom
      })) || null;
    }
    return /*#__PURE__*/_jsx(Space, {
      children: dom
    });
  }
  if (mode === 'edit') {
    var _rest$fieldProps;
    const dom = /*#__PURE__*/_jsx(Checkbox.Group, {
      ...rest.fieldProps,
      className: classNames((_rest$fieldProps = rest.fieldProps) === null || _rest$fieldProps === void 0 ? void 0 : _rest$fieldProps.className, `${layoutClassName}-${layout}`),
      options: options === null || options === void 0 ? void 0 : options.map(option => {
        if (typeof option === 'string') {
          return {
            key: option,
            label: option,
            value: option
          };
        }
        return option;
      })
    });
    if (renderFormItem) {
      return renderFormItem(rest.text, {
        mode,
        ...rest.fieldProps
      }, dom) || null;
    }
    return dom;
  }
  return null;
};
export default /*#__PURE__*/React.forwardRef(FieldCheckbox);