import React, { useState, useEffect } from "react";
import { Table, Input, InputNumber, Popconfirm, Form, Typography, Space, Divider, Modal, Radio } 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;
  rankType?: 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,
  rankType,
}: Props) => {
  const EditableCell: React.FC<EditableCellProps> = ({
    editing,
    dataIndex,
    title,
    inputType,
    record,
    index,
    children,
    ...restProps
  }) => {
    let precision = 0;
    if (dataIndex == "upper" && isPercent == 2) {
      precision = 2;
    }
    let max = 0;
    if ((dataIndex == "upper" || dataIndex == "lower") && isPercent == 2) {
      max = 100;
    } else {
      max = 999999999999;
    }
    const inputNode = inputType === "number" ? <InputNumber precision={precision} max={max} /> : <Input />;
    const rankOrderType = (
      <Radio.Group>
        <Radio value={1}>正数</Radio>
        <Radio value={2}>倒数</Radio>
      </Radio.Group>
    );

    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item name={dataIndex} style={{ margin: 0 }}>
            {dataIndex == "rankOrderType" ? rankOrderType : 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 }) => {
    console.log(record);
    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];
    if (rankType == 2) {
      newObj.lower = lastData.upper;
    } else if (rankType == 1) {
      newObj.lower = lastData.upper + 1;
    } else {
      newObj.lower = lastData.upper + 1;
    }
    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) {
        if (rankType == 2) {
          res[i + 1].lower = item.upper;
        } else if (rankType == 1) {
          res[i + 1].lower = item.upper + 1;
        }
      }
    }

    return res;
  };

  const _add = 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 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 = [...res];

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

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

        onChange && onChange([...addRow.map((i) => ({ ...i }))]);
        setEditingKey("");
      } else {
        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 = rankType == 1 ? 1 : 0;
      }
    });
    onChange && onChange([...res]);
  };
  const columns = [
    {
      title: "区间",
      editable: true,
      children: [
        {
          title: `初始排名${rankType == 1 ? "(≥)" : "(>)"}`,
          editable: true,
          dataIndex: "lower",
          width: "15%",
          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: `结束排名${rankType == 1 ? "(≤)" : "(≤)"}`,
          dataIndex: "upper",
          width: "15%",
          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: "10%",
      editable: true,
      render: (text: number) => (typeof text === "number" ? `${text}` : "--"),
    },
    {
      title: "封顶金额 (元)",
      dataIndex: "capMoney",
      width: "20%",
      editable: true,
      render: (text: number) => (typeof text === "number" ? `${text}` : "--"),
    },
    {
      title: "排名顺序类型",
      dataIndex: "rankOrderType",
      width: "20%",
      editable: true,
      render: (rankOrderType: number) => (rankOrderType === 2 ? "倒数排序" : "正数排序"),
    },
    {
      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={() => _add(record.key, record)} style={{ marginRight: 8 }}>
              保存并新增排名区间
            </Typography.Link>
            <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)}>
              编辑
            </Typography.Link>
            {index !== 0 && (
              <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],
            onCell: (record: Item) => {
              return {
                record,
                inputType: "number",
                dataIndex: col.children[0].dataIndex,
                title: col.children[0].title,
                editing: isEditing(record),
              };
            },
          },
          {
            ...col.children[1],
            onCell: (record: Item) => {
              console.log("recordrecord", record);
              return {
                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;
