import type {
  ParamsType,
  ProFormTreeSelectProps,
} from '@ant-design/pro-components';
import { ProFormTreeSelect } from '@ant-design/pro-components';
import { TreeSelectProps } from 'antd';
import React, {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useState,
} from 'react';
import '../index.less';

interface IProFormBizTreeSelectProps extends ProFormTreeSelectProps {
  params?: ParamsType;
  fetchOptions: (params?: ParamsType) => Promise<TreeSelectProps['treeData']>;
}

export interface ProFormBizTreeSelectHandles {
  reload: () => Promise<void>;
}

const ProFormBizTreeSelect = forwardRef<
  ProFormBizTreeSelectHandles,
  IProFormBizTreeSelectProps
>(({ params, fetchOptions, ...rest }, ref) => {
  const [options, setOptions] = useState<TreeSelectProps['treeData']>();

  const init = async (params?: ParamsType) => {
    const data = await fetchOptions(params);
    setOptions(data);
  };

  useEffect(() => {
    if (params) {
      init(params).then();
    }
  }, [params]);

  useImperativeHandle(ref, () => ({
    reload: async () => {
      await init(params);
    },
  }));

  return (
    <ProFormTreeSelect
      {...rest}
      fieldProps={{
        ...rest.fieldProps,
        treeData: options,
      }}
    />
  );
});

export default ProFormBizTreeSelect;
