import { Modal, Spin, Tree } from "antd";
import React, { useState } from "react";
import { GetRoleTree } from "@/api/node";
import { ModalProps } from "./props";
import { useRequest } from "umi";

/**
 * 角色弹窗
 * @returns
 */
export default function RoleModal(props: ModalProps) {
  const [open, setOpen] = useState(props.defaultOpen ?? false);
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  const [selectedRows, setSelectedRows] = useState<any[]>([]);

  const { data, loading } = useRequest(GetRoleTree);

  const handleCancel = () => {
    props.onClose?.();
    setOpen(false);
  };

  const handleOk = () => {
    props.onChange?.(selectedRows);
    setOpen(false);
  };

  const handleSelect = (selectedKeys: React.Key[], e: any) => {
    setSelectedKeys(selectedKeys);
    setSelectedRows(e.selectedNodes)
  };

  return (
    <Modal
      title="请选择角色"
      width={440}
      open={open}
      onCancel={handleCancel}
      onOk={handleOk}
    >
      <Spin spinning={loading}>
        <div className="p-12px max-h-[300px] overflow-y-auto">
          <Tree
            treeData={data?.result || []}
            selectedKeys={selectedKeys}
            onSelect={handleSelect}
            showLine
          />
        </div>
      </Spin>
    </Modal>
  );
}
