import * as React from 'react';
import { cloneElement } from 'react';
import { FastForm } from 'components/ui';
import { FormTypes } from '../types';

function FormItem(props: FormTypes.FormItem.FormItemProps) {
  const {
    layout,
    values,
    config,
    dict,
    children,
  } = props;
  const {
    key,
    type,
    label,
    rule,
    labelLayout,
    contentLayout,
    helperText,
    placeholder,
    style,
  } = config;
  let validateTrigger = 'onChange';
  let valuePropName = 'value';

  switch (type) {
    case 'uploadimage':
    case 'multuploadimage':
      validateTrigger = 'onChange';
      valuePropName = 'defaultFiles';
      break;
    default:
      validateTrigger = 'onChange';
      valuePropName = 'value';
      break;
  }

  const ChildComp = cloneElement(
    children,
    {
      config: {
        ...config,
        placeholder: placeholder || `请填写${label}`,
      },
      style,
      values,
      validateTrigger,
      valuePropName,
      dict,
    },
  );

  return (
    <FastForm.Item
      name={key}
      label={label}
      colon={!!(label?.trim())}
      rules={rule}
      help={helperText}
      validateTrigger={validateTrigger}
      valuePropName={valuePropName}
      labelCol={layout === 'inline' ? {} : { span: labelLayout }}
      wrapperCol={layout === 'inline' ? {} : { span: contentLayout }}
    >
      {ChildComp}
    </FastForm.Item>
  );
}

export default FormItem;
