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 Radio from '../radio';
import Spin from '../spin';
import ConfigProvider from '../config-provider';
import { ObjToMap, proFieldParsingText, useFieldFetchData } from '../wau-select-field';
import './style';
import { jsx as _jsx } from "react/jsx-runtime";
import { Fragment as _Fragment } from "react/jsx-runtime";
/**
 * 单选组件
 *
 * @param param0
 * @param ref
 */
const FieldRadio = ({
  radioType,
  renderFormItem,
  mode,
  render,
  ...rest
}, ref) => {
  const {
    getPrefixCls
  } = useContext(ConfigProvider.ConfigContext);
  const layoutClassName = getPrefixCls('pro-field-radio');
  const [loading, options, fetchData] = useFieldFetchData(rest);
  const radioRef = useRef();
  useImperativeHandle(ref, () => ({
    ...(radioRef.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 = /*#__PURE__*/_jsx(_Fragment, {
      children: proFieldParsingText(rest.text, ObjToMap(rest.valueEnum || optionsValueEnum))
    });
    if (render) {
      return render(rest.text, {
        mode,
        ...rest.fieldProps
      }, dom) || null;
    }
    return dom;
  }
  if (mode === 'edit') {
    var _rest$fieldProps;
    const RadioComponents = radioType === 'button' ? Radio.Button : Radio;
    const dom = /*#__PURE__*/_jsx(Radio.Group, {
      ref: radioRef,
      ...rest.fieldProps,
      className: classNames((_rest$fieldProps = rest.fieldProps) === null || _rest$fieldProps === void 0 ? void 0 : _rest$fieldProps.className, `${layoutClassName}-${rest.fieldProps.layout || 'horizontal'}`),
      options: undefined,
      children: options === null || options === void 0 ? void 0 : options.map(option => {
        if (typeof option === 'string') {
          return {
            label: option,
            value: option
          };
        }
        return option;
      }).map(item => /*#__PURE__*/_jsx(RadioComponents, {
        ...item,
        children: item.label
      }, item.value))
    });
    if (renderFormItem) {
      return renderFormItem(rest.text, {
        mode,
        ...rest.fieldProps
      }, dom) || null;
    }
    return dom;
  }
  return null;
};
export default /*#__PURE__*/React.forwardRef(FieldRadio);