import React from 'react';
import Form from 'antd/es/form';

import { ElementType } from '../../StarElement/type';
import StarForm from '../../StarForm';
import { StarFormField } from '../../StarForm/type';
import { StarTableProps, TableFormMode } from '../interface';
import StarModal from '../../StarModal';

const TableForm: React.FC<StarTableProps & {
  show: boolean;
  entity: any;
  mode: TableFormMode;
  close: () => void;
  destroy?: () => void;
}> = (props) => {
  const { columns, show, mode, entity, close, destroy, onSaveClick, format } = props;

  const fields: StarFormField[] = [];
  columns.forEach((col) => {
    const label = typeof col.title === 'function' ? col.title({}) : col.title;
    if (col.form) {
      if (col.form === true) {
        fields.push({
          element: ElementType.Input,
          label,
          name: col.dataIndex?.toString(),
        });
      } else {
        fields.push({
          label,
          name: col.dataIndex?.toString(),
          ...col.form,
        });
      }
    }
  });

  const [form] = Form.useForm();

  let title = '';
  if (format) title = format({ id: mode });
  else {
    switch (mode) {
      case 'add':
        title = '增加';
        break;
      case 'edit':
        title = '编辑';
        break;
      default:
        title = '查看';
        break;
    }
  }
  return (
    <StarModal
      title={title}
      open={show}
      onOk={async () => {
        try {
          let values = await form.validateFields();
          values = { ...entity, ...values };
          onSaveClick && onSaveClick(values, mode);
          close();
        } catch (error) {
          console.error('form fields validate error! ', error);
        }
      }}
      onCancel={() => close()}
      afterClose={() => destroy && destroy()}
      okButtonProps={{ hidden: mode === 'view' }}
      width={800}
      destroyOnClose
    >
      <StarForm
        style={{ padding: '20px 40px' }}
        form={form}
        fields={fields}
        entity={entity}
        readonly={mode === 'view'}
      />
    </StarModal>
  );
};

export default TableForm;
