import { useCallback, useEffect, useMemo, useState } from "react";
import { A5TableType } from "@/types";
import { Radio, Table } from "antd";
import { forwardRef, useImperativeHandle } from "react";

type Props = {
  data: A5TableType[];
  type: "部门" | "阶段";
  valAc: string;
  ref: any;
};

function A2Tab2AddTable({ data, type, valAc }: Props, ref: any) {
  const [value, setValue] = useState("");

  useEffect(() => {
    if (valAc) setValue(valAc);
  }, [valAc]);

  const kongGeFu = useCallback((level: 1 | 2 | 3 | 4) => {
    let arr = "";
    if (level === 2) return <>&emsp;{arr}</>;
    else if (level === 3) return <>&emsp;&emsp;{arr}</>;
    else if (level === 4) return <>&emsp;&emsp;&emsp;{arr}</>;
    else return <></>;
  }, []);

  const A2Tab2AddTableResFu = useCallback(() => {
    return value;
  }, [value]);

  // 可以让父组件调用子组件的方法
  useImperativeHandle(ref, () => ({
    A2Tab2AddTableResFu,
  }));

  const columns = useMemo(() => {
    return [
      {
        width: 150,
        title: "单选",
        render: (item: A5TableType) => {
          if (item.children) return null;
          else
            return (
              <Radio
                value={item.id}
                checked={item.id === value}
                onChange={(e) => setValue(e.target.value)}
              ></Radio>
            );
        },
      },
      {
        title: `${type}名称`,
        render: (item: A5TableType) => (
          <span>
            {kongGeFu(item.level)}
            {item.name}
          </span>
        ),
      },
    ];
  }, [kongGeFu, type, value]);

  return (
    <>
      {data.length ? (
        <Table
          size="small"
          dataSource={data}
          columns={columns}
          rowKey="id"
          pagination={false}
          expandable={{ defaultExpandAllRows: true }}
        />
      ) : null}
    </>
  );
}

export default forwardRef(A2Tab2AddTable);
