import React from "react";
import { DrawerForm } from "@ant-design/pro-components";
import { Form } from "antd";
import XTable from "../XTable";

export default function Curd(props) {
  const {
    rowKey,
    columns,
    request,
    formProps,
    renderFormItems,
    transform,
    convertValue,
    ...leftProps
  } = props;

  const [form] = Form.useForm();
  const listRef = React.useRef();
  const rowRef = React.useRef();
  const [open, setOpen] = React.useState(false);

  const onAdd = () => {
    rowRef.current = undefined;
    form.resetFields();
    setOpen(true);
  };

  const onEdit = (row) => {
    rowRef.current = row;

    const formData = convertValue ? convertValue(row) : row;
    form.resetFields();
    form.setFieldsValue(formData);

    setOpen(true);
  };

  const onDelete = (row) => {
    rowRef.current = row;

    if (request.remove) {
      request
        .remove(row[rowKey])
        .then(() => {
          listRef.current.reload();
        })
        .catch(() => {
          //
        });
    }
  };

  const onFinish = async (values) => {
    const id = rowRef.current?.[rowKey];
    const data = transform ? transform(id, values) : values;
    if (rowRef.current && request.update) {
      // await request.update(id, data);
    } else if (request.save) {
      // await request.save(data);
    }
    listRef.current.reload();

    return true;
  };

  return (
    <div>
      <XTable
        ref={listRef}
        rowKey={rowKey}
        columns={columns}
        request={request.list}
        onAdd={onAdd}
        onDelete={onDelete}
        onEdit={onEdit}
        {...leftProps}
      />

      <DrawerForm
        submitTimeout={3000}
        open={open}
        form={form}
        drawerProps={{ destroyOnClose: true }}
        onOpenChange={setOpen}
        onFinish={onFinish}
        {...formProps}
      >
        {renderFormItems && renderFormItems(rowRef.current, listRef, setOpen)}
      </DrawerForm>
    </div>
  );
}
