import React, { useMemo, useRef } from "react";
import { Modal, Table } from "antd";
import { DEFAULT_SYSTEM_VARIABLES } from "@/constants";
import { useRequest } from "umi";
import { GetSystemVariable } from "@/api";
export default function VariableModal(props: {
  /**
   * 触发节点
   */
  trigger: JSX.Element;
  /**
   * 确认
   */
  onOk: (code: string) => void;
}) {
  const [open, setOpen] = React.useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = React.useState<React.Key[]>([]);
  const result = useRef<string>();

  const { run, data, loading } = useRequest(GetSystemVariable, {
    manual: true,
  });

  const dataSource = useMemo(() => {
    return [
      ...DEFAULT_SYSTEM_VARIABLES,
      ...(data?.result || [])
    ];
  }, [data]);

  const triggerDom = React.cloneElement(props.trigger, {
    ...props.trigger.props,
    onClick: () => {
      setSelectedRowKeys([]);
      result.current = '';
      run();
      setOpen(true);
    },
  });
  const handleSelected = (keys: React.Key[], rows: any[]) => {
    setSelectedRowKeys(keys);
    result.current = rows?.[0]?.name;
  };

  const handleOk = () => {
    props.onOk(result.current ? `<%${result.current}%>` : '');
    setOpen(false);
  };

  return (
    <>
      <Modal
        width={440}
        open={open}
        title="请选择"
        onCancel={() => setOpen(false)}
        onOk={handleOk}
        okButtonProps={{
          disabled: !result.current,
        }}
      >
        <Table
          rowKey={'id'}
          loading={loading}
          dataSource={dataSource}
          rowSelection={{
            type: "radio",
            selectedRowKeys,
            onChange: (keys, selectedRows) => {
              handleSelected(keys, selectedRows);
            },
          }}
          columns={[
            { title: "变量名", dataIndex: "name" },
            { title: "变量类型", dataIndex: "type" },
          ]}
        />
      </Modal>
      {triggerDom}
    </>
  );
}
