index.tsx 2.81 KB
import { BlockOutlined } from '@ant-design/icons';
import { useSetState } from 'ahooks';
import { Button } from 'antd';
import cls from 'classnames';
import React, { useCallback, useRef } from 'react';
import { QxAppSelector } from '../qx-app-selector';
import type { InputSelectProps } from '../qx-input-select';
import { QxInputSelect } from '../qx-input-select';

import './styles.less';

const prefix = 'qx-form-select';

/**
 * 选择数据源
 */
export const QxFormSelect: React.FC<FormSelectProps> = (props) => {
  const {
    className,
    options = [],
    onChange,
    value,
    loading,
    appId,
    request,
    disabled,
    placeholder,
    title
  } = props;

  const [state, setState] = useSetState<FormSelectState>({
    visible: false,
    modalVisible: false,
  });

  const inputSelectRef = useRef<any>();

  const handleChange = (val: any) => {
    if (!val?.code) return;
    function onOk() {
      if (val?.code) {
        onChange?.(val);
        setState({
          visible: false,
        });
      }
    }
    onOk();
  };

  const onOpenOther = useCallback(() => {
    inputSelectRef.current?.closeDropdown();
    setState({
      modalVisible: true,
    });
  }, []);

  return (
    <div className={cls(prefix, className)}>
      <QxInputSelect
        ref={inputSelectRef}
        value={value?.name}
        defaultValue={value?.name}
        placeholder={placeholder || '请选择数据源'}
        prefix={<BlockOutlined style={{ color: '#52c41a' }} />}
        options={options}
        onChange={handleChange}
        dropdownProps={{
          showSearch: true,
          loading,
          listHeight: 160,
          renderBottom: (
            <Button
              className={`${prefix}__dropdown-bottom`}
              type="link"
              onClick={onOpenOther}
            >
              其他应用
            </Button>
          ),
        }}
        disabled={disabled}
        popupOnBody={props?.popupOnBody}
      />

      {state.modalVisible ? (
        <QxAppSelector
          title={title || placeholder || '选择数据源'}
          item={{
            flag: 'SINGLE',
            currentId: '',
            appId: appId,
          }}
          onChange={handleChange}
          flag="join"
          showTableTypeTab={false}
          modalProps={{
            width: 550,
            destroyOnClose: true,
            open: state.modalVisible,
            onOk: () => setState({ modalVisible: false }),
            onCancel: () => setState({ modalVisible: false }),
          }}
          request={request}
        />
      ) : null}
    </div>
  );
};

interface FormSelectProps extends InputSelectProps {
  value?: any;
  loading?: boolean;
  appId?: string;
  request?: any;
  disabled?: boolean;
  popupOnBody?: boolean;
}
interface FormSelectState {
  visible: boolean;
  modalVisible: boolean;
}