TotalAmountSal.tsx 9.73 KB
import React, { useState, useEffect } from "react";
import { Table, Input, InputNumber, Popconfirm, Form, Typography, Space, Divider, Modal } from "antd";
import { SalaryMapHeader } from "@/pages/performance/CompensateGroupConfig/entity";

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

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

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

const TotalAmount = ({
  laddersType,
  value,
  onChange,
  readOnly,
  visible,
  type,
  setladderVisible,
  salaryCode,
  isPercent,
  calType,
}: Props) => {
  const EditableCell: React.FC<EditableCellProps> = ({
    editing,
    dataIndex,
    title,
    inputType,
    record,
    index,
    children,
    ...restProps
  }) => {
    let precision = 0;
    if (dataIndex == "upper" && isPercent == 2) {
      precision = 2;
    }
    const inputNode = inputType === "number" ? <InputNumber precision={precision} /> : <Input />;

    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item name={dataIndex} style={{ margin: 0 }}>
            {inputNode}
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };
  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({
      upper: "",
      money: "",
      ...record,
    });
    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(),
      money: 0,
    };

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

  const checkRange = async (tempData:any, index:number) => {
    const res = [...tempData.map((i:any) => ({ ...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) => {
    console.log(record);
    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: "区间",
      editable: true,
      children: [
        {
          title: "阶梯值下限(≥)",
          dataIndex: "lower",
          width: "25%",
          render: (value: number) => {
            if (isPercent == 2) {
              return value + "%";
            } else if (isPercent == 1) {
              return value;
            } else if (isPercent == 0 && laddersType == 2) {
              return value + "%";
            } else {
              return value;
            }
          },
        },
        {
          title: "阶梯值上限(<)",
          dataIndex: "upper",
          width: "25%",
          editable: true,
          render: (value: number) => {
            if (value) {
              if (isPercent == 2) {
                return value + "%";
              } else if (isPercent == 1) {
                return value;
              } else if (isPercent == 0 && laddersType == 2) {
                return value + "%";
              } else {
                return value;
              }
            } else {
              return "";
            }
          },
        },
      ],
    },
    {
      title: "金额 (元)",
      dataIndex: "money",
      width: "20%",
      editable: true,
      render: (text: number) => (typeof text === "number" ? `${text}` : "--"),
    },
    {
      title: "封顶金额 (元)",
      dataIndex: "capMoney",
      width: "20%",
      editable: true,
      render: (text: number) => (typeof text === "number" ? `${text}` : "--"),
    },
    {
      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 calTypeColumns = () => {
    const _columns = getColumns();
    if (calType == 5) {
      return _columns;
    } else {
      return _columns.filter((item) => item.dataIndex !== "capMoney");
    }
  };
  const mergedColumns = calTypeColumns().map((col) => {
    if (!col.editable) {
      return col;
    }
    if (col.children) {
      return {
        ...col,
        children: [
          {
            ...col.children[0],
          },
          {
            ...col.children[1],
            onCell: (record: Item) => ({
              record,
              inputType: "number",
              dataIndex: col.children[1].dataIndex,
              title: col.children[1].title,
              editing: isEditing(record),
            }),
          },
        ],
      };
    }
    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>
          <div>金额可为负数,负数为负激励</div>
        </Modal>
      ) : (
        <>
          <Form form={form} component={false}>
            <Table
              components={{
                body: {
                  cell: EditableCell,
                },
              }}
              bordered
              dataSource={value}
              columns={mergedColumns}
              rowClassName="editable-row"
              pagination={{
                onChange: cancel,
              }}
            />
          </Form>
          <div>金额可为负数,负数为负激励</div>
        </>
      )}
    </>
  );
};

export default TotalAmount;