import { FC, Key, useEffect, useState } from "react";
import { Form, Modal, ModalProps, Tree } from "antd";
import { getSelectedNodes } from "@/utils";
import style from "./index.module.scss";

export interface AddIndexModalProps extends Omit<ModalProps, "onOk"> {
  checkedKeys: Key[];
  onCancel?: () => void;
  onOk?: (keys: Key[], items: any) => void;
}

const treeData: any[] = [
  {
    name: "0-0",
    id: "0-0",
    children: [
      {
        name: "0-0-0",
        id: "0-0-0",
        children: [
          { id: "0-0-0-0", level: 1, name: "指标名称1" },
          { id: "0-0-0-1", level: 1, name: "指标名称2" },
          { id: "0-0-0-2", level: 1, name: "指标名称3" },
        ],
      },
    ],
  },
];

export const AddIndexModal: FC<AddIndexModalProps> = ({
  open,
  checkedKeys,
  onOk,
  onCancel,
  ...rest
}) => {
  const [form] = Form.useForm<any>();
  const [_checkedKeys, setCheckedKeys] = useState<Key[]>([]);

  const handleCancel = () => {
    form.resetFields();
    onCancel?.();
  };

  const handleConfirm = () => {
    form.submit();
  };

  const handleSubmit = async (values: any) => {
    onOk?.(values.checkedKeys, getSelectedNodes(values.checkedKeys, treeData));
    handleCancel();
  };

  useEffect(() => {
    if (open) {
      setCheckedKeys(checkedKeys);
    }
  }, [open, checkedKeys]);

  return (
    <Modal
      className={style.modal}
      title="新增指标"
      okText="提交"
      cancelText="取消"
      open={open}
      width={640}
      okButtonProps={{
        disabled: false,
      }}
      onOk={handleConfirm}
      onCancel={handleCancel}
      {...rest}
    >
      <Form
        labelCol={{ span: 4, offset: 2 }}
        form={form}
        onFinish={handleSubmit}
      >
        <Form.Item
          label="采用指标"
          name="checkedKeys"
          required
          rules={[{ required: true, message: "请选择指标" }]}
        >
          <Tree
            checkable
            defaultExpandAll
            fieldNames={{
              key: "id",
              title: "name",
            }}
            checkedKeys={_checkedKeys}
            treeData={treeData}
            onCheck={(checkedKeys) => {
              setCheckedKeys(checkedKeys as Key[]);
              form.setFieldsValue({
                checkedKeys,
              });
            }}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
};
