import React, { useEffect } from 'react';
import { Form, Button, Select, Input, Radio, Checkbox } from 'antd';
import Upload from '@/components/Upload';
import { useForm } from 'antd/lib/form/Form';

export const renderButtonGroup = props => {
  const { buttons, wrapper = false } = props;
  const bts = buttons.map(bt => {
    const { text, ...rest } = bt;
    return (
      <Button {...rest} key={text}>
        {text}
      </Button>
    );
  });
  if (wrapper) {
    return wrapper(bts);
  }
  return bts;
};

export const ITEM_TYPE = {
  INPUT: 'INPUT',
  SELECT: 'SELECT', // 下拉选择
  IMGSHOP: 'IMGSHOP', // 图片库
  SINGLE_RADIO: 'SINGLE_RADIO', // 单选radio
  CHECK_BOX: 'CHECK_BOX', // 多选框
};

const BaseFormItem = itemOption => {
  const { formType, options = [], ...rest } = itemOption;
  switch (formType) {
    case ITEM_TYPE.INPUT:
      // eslint-disable-next-line no-undef
      return <Input allowClear {...rest} />;
    case ITEM_TYPE.SELECT:
      return (
        <Select {...rest}>
          {options.map((o, i) => (
            <Select.Option key={`item_${i}`} {...o} />
          ))}
        </Select>
      );
    case ITEM_TYPE.IMGSHOP:
      return <Upload {...rest} />;
    case ITEM_TYPE.SINGLE_RADIO:
      // eslint-disable-next-line no-case-declarations
      return (
        <Radio.Group {...rest}>
          {options.map((o, i) => (
            <Radio key={`item_${i}`} {...o} />
          ))}
        </Radio.Group>
      );
    case ITEM_TYPE.CHECK_BOX:
      return (
        <Checkbox.Group {...rest}>
          {options.map((o, i) => (
            <Checkbox key={`item_${i}`} {...o} />
          ))}
        </Checkbox.Group>
      );
    default:
      return null;
  }
};

/**
 * 基本表单
 * @param {*} props
 *  items: 每个表单项
 *  buttons： 表单按钮
 */
const BaseForm = props => {
  const {
    items,
    buttons = [],
    buttonsWraper,
    getForm, // 用来获取表单实例
    formProps,
    children,
    ...restProps
  } = props;

  const [form] = useForm();

  useEffect(() => {
    // 执行回调让外部组件拿到表单实例
    // eslint-disable-next-line no-unused-expressions
    getForm && getForm(form);
  }, []);

  return (
    <Form size="small" form={form} {...formProps} {...restProps}>
      {items &&
        items.map(item => {
          const {
            label,
            dataIndex,
            initialValue = '',
            rules = [],
            formItemProps = {},
            ...rest
          } = item;
          return (
            <Form.Item
              label={label}
              name={dataIndex}
              key={`formItem_${dataIndex}`}
              rules={rules}
              initialValue={initialValue}
              {...formItemProps}
            >
              <BaseFormItem {...rest} />
            </Form.Item>
          );
        })}
      {renderButtonGroup({
        buttons,
        wrapper: buttonsWraper || (bts => <Form.Item>{bts}</Form.Item>),
      })}
      {children}
    </Form>
  );
};

export default BaseForm;
