EditTable.tsx 4.42 KB
import React, { useState, useEffect } from "react";
import { Table, Input, InputNumber, Popconfirm, Form, Typography } from "antd";
import { useStore } from "../index";

interface Item {
  key: string;
  shopId: number;
  shopName: string;
  amount: number;
  ratio: number;
  rewardBelong: number;
}

interface EditableCellProps extends React.HTMLAttributes<HTMLElement> {
  editing: boolean;
  dataIndex: string;
  title: any;
  inputType: "number" | "text";
  record: Item;
  index: number;
  children: React.ReactNode;
}

const EditableCell: React.FC<EditableCellProps> = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}) => {
  const inputNode = inputType === "number" ? <InputNumber /> : <Input />;

  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{ margin: 0 }}
          rules={[
            {
              required: true,
              message: `请输入 ${title}!`,
            },
          ]}
        >
          {inputNode}
        </Form.Item>
      ) : (
        children
      )}
    </td>
  );
};

interface Props {
  tableDataSource: any[];
  // 扣款金额
  amount: number;
  value?: any[];
  onChange?: () => void;
}
const EditableTable = ({ tableDataSource, amount, onChange, value }: Props) => {
  const { readOnly } = useStore();
  const [form] = Form.useForm();
  const [data, setData] = useState(tableDataSource || []);
  const [editingKey, setEditingKey] = useState("");

  const isEditing = (record: Item) => record.key === editingKey;

  const edit = (record: Partial<Item> & { key: React.Key }) => {
    form.setFieldsValue({ ratio: "", ...record });
    setEditingKey(record.key);
  };

  const cancel = () => {
    setEditingKey("");
  };

  useEffect(() => {
    setData([...tableDataSource]);
  }, [tableDataSource]);
  const save = async (key: React.Key) => {
    try {
      const row = (await form.validateFields()) as Item;
      const { ratio } = row;
      const money = (amount * ratio) / 100;

      const newData = [...data];
      const index = newData.findIndex((item) => key === item.key);
      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, {
          ...item,
          ...row,
          amount: money,
        });
        setData(newData);
        setEditingKey("");
      } else {
        newData.push(row);
        setData(newData);
        setEditingKey("");
      }
      onChange && onChange(newData);
    } catch (errInfo) {
      console.log("Validate Failed:", errInfo);
    }
  };

  const columns = [
    {
      title: "商家",
      dataIndex: "dealerName",
      width: "30%",
    },
    {
      title: "分摊金额",
      dataIndex: "amount",
      width: "25%",
    },
    {
      title: "分摊比例(%)",
      dataIndex: "ratio",
      width: "20%",
      editable: true,
    },
    {
      title: "操作",
      dataIndex: "operation",
      width: "25%",
      render: (_: any, record: Item) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <Typography.Link
              onClick={() => save(record.key)}
              style={{ marginRight: 8 }}
            >
              保存
            </Typography.Link>
            <Popconfirm title="确定取消?" onConfirm={cancel}>
              <a>取消</a>
            </Popconfirm>
          </span>
        ) : (
          <Typography.Link
            disabled={editingKey !== ""}
            onClick={() => edit(record)}
          >
            编辑
          </Typography.Link>
        );
      },
    },
  ];

  const getColumns = () => {
    if (readOnly) {
      columns.pop();
    }
    return columns;
  };
  const mergedColumns = getColumns().map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record: Item) => ({
        record,
        inputType: "number",
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });

  return (
    <Form form={form} component={false}>
      <Table
        components={{
          body: {
            cell: EditableCell,
          },
        }}
        rowKey={(_, record) => `id_${record.key}`}
        bordered
        dataSource={data}
        columns={mergedColumns}
        rowClassName="editable-row"
        pagination={{
          onChange: cancel,
        }}
      />
    </Form>
  );
};

export default EditableTable;