import { FC, Key, useState } from "react";
import { Form, Modal, ModalProps, Tree } from "antd";
import style from "./index.module.scss";
import { getAssIndexTreeApi } from "@/api";
import { AssIndexTreeItemType, ASS_INDEX_TYPE } from "@/types";
import { useParams } from "react-router-dom";
import { DageLoading } from "@dage/pc-components";

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

export const AddIndexModal: FC<AddIndexModalProps> = ({
  open,
  onOk,
  onCancel,
  ...rest
}) => {
  const params = useParams();
  const [form] = Form.useForm<any>();
  const [_checkedKeys, setCheckedKeys] = useState<Key[]>([]);
  const [treeData, setTreeData] = useState<AssIndexTreeItemType[]>([]);
  const [loading, setLoading] = useState(false);

  const getAssIndexTree = async () => {
    try {
      setLoading(true);
      const data = await getAssIndexTreeApi(params.type as ASS_INDEX_TYPE);
      setTreeData(data);
    } finally {
      setLoading(false);
    }
  };

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

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

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

  const handleAfterOpenChange = (open: boolean) => {
    if (open && !treeData.length) getAssIndexTree();
  };

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

      {loading && <DageLoading />}
    </Modal>
  );
};
