AddOrUpdate.tsx 6.08 KB
import { postProductCollectBillAddOrModify } from '@/services';
import { useModel } from '@@/exports';
import {
  ActionType,
  EditableProTable,
  ModalForm,
  ProCard,
  ProColumns,
  ProForm,
  ProFormDependency,
  ProFormField,
  ProFormSwitch,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { Button, Form, message } from 'antd';
import React, { useEffect, useRef, useState } from 'react';

export default ({ record, onfinish }) => {
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [controlled, setControlled] = useState<boolean>(false);
  const [processedRecord, setProcessedRecord] = useState(record);
  const formRef = useRef(null);
  const editorFormRef = useRef(null);
  const { getProducts } = useModel('enum');
  const actionRef = useRef<ActionType>();
  useEffect(() => {
    if (record?.details) {
      const updateddetails = record.details.map((item) => ({
        ...item,
        key: item.key || `key-${Math.random().toString(36).substr(2, 9)}`, // 动态生成唯一 key
      }));
      setProcessedRecord({
        ...record,
        details: updateddetails,
      });
    }
  }, [record]);

  const columns: ProColumns[] = [
    {
      title: '商品',
      dataIndex: 'productId',
      valueType: 'select',
      request: async () => {
        const res = await getProducts();
        return res.map((item) => ({
          ...item,
          label: item.name,
          value: item.id,
          productUnitName: item.baseUnitName,
          productUnitPrice: item.unitPrice,
        }));
      },
      fieldProps: (_, { rowIndex }) => ({
        onSelect: (value, option) => {
          const currentTableData = editorFormRef.current?.getRowsData?.();
          if (currentTableData) {
            const updatedData = [...currentTableData];
            updatedData[rowIndex] = {
              ...updatedData[rowIndex],
              productUnitName: option.productUnitName,
              productUnitPrice: option.productUnitPrice,
            };
            formRef.current?.setFieldsValue({
              details: updatedData,
            });
          }
        },
      }),
    },
    {
      title: '单位',
      dataIndex: 'productUnitName',
      valueType: 'text',
      editable: false,
    },
    {
      title: '单价',
      dataIndex: 'productUnitPrice',
      valueType: 'digit',
      editable: false,
    },
    {
      title: '数量',
      dataIndex: 'number',
      valueType: 'digit',
    },
    {
      title: '备注',
      dataIndex: 'notes',
      valueType: 'textarea',
    },
    {
      title: '操作',
      valueType: 'option',
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.key);
          }}
        >
          编辑
        </a>,
        <a
          key="delete"
          onClick={() => {
            const tableDataSource = formRef.current?.getFieldValue('details');
            formRef.current?.setFieldsValue({
              table: tableDataSource.filter((item) => item.key !== record.key),
            });
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  const [form] = Form.useForm();
  return (
    <ModalForm
      formRef={formRef}
      initialValues={processedRecord}
      validateTrigger="onBlur"
      title="新建表单"
      trigger={
        record?.id ? (
          <Button type="link">修改</Button>
        ) : (
          <Button type="primary">新建</Button>
        )
      }
      form={form}
      autoFocusFirstInput
      width={1500}
      modalProps={{
        destroyOnClose: true,
        onCancel: () => console.log('run'),
      }}
      submitTimeout={2000}
      onFinish={async (values) => {
        const res = await postProductCollectBillAddOrModify({
          data: {
            ...record,
            ...values,
          },
        });
        if (res) {
          message.success(res.message);
          onfinish();
        }
        return true;
      }}
    >
      <EditableProTable
        rowKey="key"
        scroll={{
          x: 960,
        }}
        editableFormRef={editorFormRef}
        headerTitle="可编辑表格"
        maxLength={5}
        name="details"
        controlled={controlled}
        recordCreatorProps={{
          position: 'bottom',
          record: () => ({
            key: `key-${Math.random().toString(36).substr(2, 9)}`,
          }),
        }}
        actionRef={actionRef}
        toolBarRender={() => [
          <ProFormSwitch
            key="render"
            fieldProps={{
              style: {
                marginBlockEnd: 0,
              },
              checked: controlled,
              onChange: (value) => {
                setControlled(value);
              },
            }}
            checkedChildren="数据更新通知 Form"
            unCheckedChildren="保存后通知 Form"
            noStyle
          />,
          <Button
            key="rows"
            onClick={() => {
              const rows = editorFormRef.current?.getRowsData?.();
              console.log(rows);
            }}
          >
            获取 table 的数据
          </Button>,
        ]}
        columns={columns}
        editable={{
          type: 'multiple',
          editableKeys,
          onChange: setEditableRowKeys,
          actionRender: (row, config, defaultDom) => {
            return [defaultDom.save, defaultDom.delete, defaultDom.cancel];
          },
        }}
      />
      <ProForm.Item>
        <ProCard title="表格数据" headerBordered collapsible defaultCollapsed>
          <ProFormDependency name={['details']}>
            {({ details }) => (
              <ProFormField
                ignoreFormItem
                fieldProps={{
                  style: {
                    width: '100%',
                  },
                }}
                mode="read"
                valueType="jsonCode"
                text={JSON.stringify(details)}
              />
            )}
          </ProFormDependency>
        </ProCard>
      </ProForm.Item>
      <ProFormTextArea name="auditRemarks" label="备注" />
    </ModalForm>
  );
};