import React, { useRef } from 'react';
import { Select } from 'antd';
import { onBlurFn } from '../onBlurFn';
import { ApolloSelectProps } from '../editInterface';
import { antiAssign } from '../../../../utils/utils';
import styles from './styles.less';

export const ApolloSelect = (props: ApolloSelectProps) => {
    const { options = [], onChange, isMultiple, origin, maxPopHeight } = props;
    const selfProps = antiAssign(props, ['columnConfig', 'onChange', 'isMultiple', 'options', 'maxPopHeight']);
    const isOpen: any = useRef();

    if (isMultiple) {
        selfProps.mode = 'multiple';
    }
    const changeValue = (value: any, option: any) => {
        if (typeof onChange === 'function') {
            if (typeof onBlurFn === 'function' && !isOpen.current) {
                onBlurFn({ ...props, value });
            }
            onChange(value, option);
        }
    };
    const singleBlurFn = (e: boolean) => {
        isOpen.current = e;
    };
    const multipleBlurFn = (e: boolean) => {
        isOpen.current = e;
        if (typeof onBlurFn === 'function' && !e) {
            onBlurFn(props);
        }
    };

    return origin === 'editForm' ? (
        <Select
            className={styles.select}
            {...selfProps}
            onChange={changeValue}
            onDropdownVisibleChange={selfProps.mode === 'multiple' ? multipleBlurFn : singleBlurFn}
            dropdownStyle={{
                maxHeight: maxPopHeight,
            }}
        >
            {options.map((item) => {
                return (
                    <Select.Option key={item.id} value={item.id}>
                        {item.name}
                    </Select.Option>
                );
            })}
        </Select>
    ) : (
        <Select
            className={styles.select}
            {...selfProps}
            onChange={changeValue}
            dropdownStyle={{
                maxHeight: maxPopHeight,
            }}
        >
            {options.map((item) => {
                return (
                    <Select.Option key={item.id} value={item.id}>
                        {item.name}
                    </Select.Option>
                );
            })}
        </Select>
    );
};
