CondLaddersTable.tsx 8.14 KB
import React, { useState, useEffect } from "react";
import { Table, Input, InputNumber, Popconfirm, Form, Typography, Button, message, Space, Divider, Modal } from "antd";
import { cloneDeep } from "lodash";

interface Item {
  key: string;
  lower: number;
  upper: number;
  scorePercent: number;
}

interface Props {
  value?: any[];
  onChange?: Function;
  readOnly?: boolean;
  visible?: boolean;
  type?: number; //2 查看得分阶梯
  setladderVisible?: Function;
}

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 precision={dataIndex === "upper" ? 2 : 0} min={0} /> : <Input />;

  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{ margin: 0 }}
          rules={
            [
              // {
              //   required: dataIndex !== "upper",
              //   message: `请输入${title}!`,
              // },
              // {
              //   pattern: dataIndex == "upper" ? /^[1-9]\d*$/ : undefined,
              //   message: "请输入大于0的正整数",
              // },
            ]
          }
        >
          {inputNode}
        </Form.Item>
      ) : (
        children
      )}
    </td>
  );
};

const LadderTable = ({ value, onChange, readOnly, visible, type, setladderVisible }: Props) => {
  const [form] = Form.useForm();
  // 添加阶梯
  const [disable, setDisable] = useState(false);
  const [editingKey, setEditingKey] = useState("");
  const isEditing = (record: Item) => record.key === editingKey;

  const edit = (record: Partial<Item> & { key: React.Key }, index: number) => {
    form.setFieldsValue({
      scorePercent: "",
      address: "",
      ...record,
      upper: record.upper == 65536 ? "" : record.upper,
    });
    // console.log(record);
    record.key = index.toString();
    setEditingKey(record.key);
  };

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

  // 添加阶梯
  const onAdd = (values: any[], index: number) => {
    const preTableData: any[] = [...values.map((i) => ({ ...i }))];

    // 编辑不是最后一行,不需要增加阶梯
    if (index !== preTableData.length - 1) {
      return preTableData;
    }

    // 如果最后一行没有输入最大值,不需要增加阶梯
    if (index === preTableData.length - 1) {
      const endData = preTableData[index];
      if (!endData.upper) {
        return preTableData;
      }
    }
    const newObj: { lower?: number; key?: number } = {};
    const lastData = preTableData[preTableData.length - 1];
    newObj.lower = lastData.upper;
    newObj.key = Number(lastData.key) + 1;

    const pa = {
      ...newObj,
      key: newObj.key?.toString(),
      scorePercent: 0,
    };

    preTableData.push(pa);
    return preTableData;
  };

  const checkRange = async (tempData, index) => {
    const res = [...tempData.map((i) => ({ ...i }))];
    const _tempData = res.concat();

    for (let i = 0; i < _tempData.length; i++) {
      const item = res[i];
      if (item.upper && item.lower && item.lower >= item.upper) {
        item.upper = item.lower + 1;
      }
      if (i >= index && i < res.length - 1) {
        res[i + 1].lower = item.upper;
      }
    }

    return res;
  };

  const save = async (key: React.Key, record: Item) => {
    try {
      const row = (await form.validateFields()) as Item;
      let newData = [...value.map((i) => ({ ...i }))];
      const index = newData.findIndex((item) => key === item.key);

      const tempData = [...newData].map((i) => (i.key == key ? { ...record, ...row } : { ...i }));

      const res = await checkRange([...tempData], index);

      const addRow = onAdd([...res], index);

      if (index > -1) {
        const item = addRow[index];

        addRow.splice(index, 1, {
          ...row,
          ...item,
        });

        onChange && onChange([...addRow.map((i) => ({ ...i }))]);
        setEditingKey("");
      } else {
        addRow.push(row);
        onChange && onChange([...addRow.map((i) => ({ ...i }))]);

        setEditingKey("");
      }
    } catch (errInfo) {
      console.log("Validate Failed:", errInfo);
    }
  };

  // 删除阶梯区间

  const _onDelete = (record: Item, index: number) => {
    const tmpData = [...(value || [])];
    const res = tmpData.filter((item) => item.key !== record.key);
    if (index > 0 && index <= res.length - 1) {
      res[index].lower = res[index - 1].upper;
    }

    //校准区间
    res.forEach((item, ind) => {
      if (ind === 0) {
        res[0].lower = 0;
      }
    });
    onChange && onChange([...res]);
  };
  const columns = [
    {
      title: "区间下限(≥)",
      dataIndex: "lower",
      width: "20%",
      render: (value: number) => value + "%",
    },
    {
      title: "区间上限(<)",
      dataIndex: "upper",
      width: "20%",
      editable: true,
      render: (value: number) => (value && value !== 65536 ? value + "%" : ""),
    },
    {
      title: "绩效分折算比例",
      dataIndex: "scorePercent",
      width: "15%",
      editable: true,
      render: (value: number) => value + "%",
    },
    {
      title: "操作",
      width: "40%",
      dataIndex: "operation",
      render: (_: any, record: Item, index: number) => {
        const editable = isEditing(record);
        return editable ? (
          <Space split={<Divider type="vertical" />}>
            <Typography.Link onClick={() => save(record.key, record)} style={{ marginRight: 8 }}>
              保存
            </Typography.Link>
            <Popconfirm title="确定取消?" onConfirm={cancel}>
              <a>取消</a>
            </Popconfirm>
          </Space>
        ) : (
          <Space split={<Divider type="vertical" />}>
            <Typography.Link disabled={editingKey !== "" || readOnly} onClick={() => edit(record, index)}>
              编辑
            </Typography.Link>
            {index !== 0 && index !== value?.length - 1 && (
              <Typography.Link
                disabled={editingKey !== "" || readOnly || value?.length === 1}
                onClick={() => _onDelete(record, index)}
              >
                删除
              </Typography.Link>
            )}
          </Space>
        );
      },
    },
  ];
  const getColumns = () => {
    const _columns = columns;
    if (readOnly) {
      _columns.pop();
    }
    return _columns;
  };
  // const mergedColumns = columns.map((col) => {
  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 (
    <>
      {type === 2 ? (
        <Modal
          title="查看阶梯"
          visible={visible}
          maskClosable={false}
          footer={null}
          width={700}
          onCancel={() => setladderVisible(false)}
        >
          <Form form={form} component={false}>
            <Table
              components={{
                body: {
                  cell: EditableCell,
                },
              }}
              bordered
              dataSource={value}
              columns={mergedColumns}
              rowClassName="editable-row"
              pagination={{
                onChange: cancel,
              }}
            />
          </Form>
        </Modal>
      ) : (
        <Form form={form} component={false}>
          <Table
            components={{
              body: {
                cell: EditableCell,
              },
            }}
            bordered
            dataSource={value}
            columns={mergedColumns}
            rowClassName="editable-row"
            pagination={{
              onChange: cancel,
            }}
          />
        </Form>
      )}
    </>
  );
};

export default LadderTable;