import React, { useRef } from 'react';
import { message } from 'antd';
import Search from '../../extra/associationSearch';
import { ApolloSearchProps } from '../editInterface';
import { antiAssign } from '../../../../utils/utils';
import { onBlurFn } from '../onBlurFn';
import s from './index.less';

export const ApolloSearch = (props: ApolloSearchProps) => {
    const { onChange, maxCount, isMultiple, request, maxPopHeight } = props;
    const selfProps = antiAssign(props, [
        'columnConfig',
        'onChange',
        'isMultiple',
        'options',
        'request',
        'maxCount',
        'maxPopHeight',
    ]);
    const isOpen: any = useRef();
    if (isMultiple) {
        selfProps.mode = 'multiple';
    }
    const changeValue = (value: any) => {
        if (isMultiple && maxCount && maxCount < value.length) {
            message.warn(`最多选择${maxCount}个`);
            return;
        }
        if (typeof onChange === 'function') {
            if (typeof onBlurFn === 'function' && !isOpen.current) {
                onBlurFn({ ...props, value });
            }
            onChange(value, value);
        }
    };

    const singleBlurFn = (e: boolean) => {
        isOpen.current = e;
    };
    const multipleBlurFn = (e: boolean) => {
        isOpen.current = e;
        if (typeof onBlurFn === 'function' && !e) {
            onBlurFn(props);
        }
    };

    const extra: any = {};
    // 表格中限制下拉类组件弹框高度
    if (maxPopHeight) {
        extra.dropdownClassName = s.searchDropdown;
        extra.dropdownStyle = {
            maxHeight: maxPopHeight,
        };
    }

    return (
        <Search
            className={s.search}
            request={request}
            fieldNames={{ value: 'fieldValueValue', label: 'fieldValueName' }}
            {...selfProps}
            onDropdownVisibleChange={selfProps.mode === 'multiple' ? multipleBlurFn : singleBlurFn}
            onChange={changeValue}
            initDataType="onfocus"
            {...extra}
        />
    );
};
