import React, { useEffect, useState } from 'react';
import { Select } from 'antd';
import { ApolloSelectProps } from '../editInterface';
import { antiAssign } from '@/apollo-table/utils/utils';
import styles from './styles.less';

const ApolloSelect = (props: ApolloSelectProps) => {
    const { options = [], onChange, emitTrigger, onEmitChange, isMultiple } = props;
    const selfProps = antiAssign(props, ['value', 'onChange', 'emitTrigger', 'onEmitChange', 'isMultiple', 'options']);
    const [value, setValue] = useState(props.value);
    const [option, setOption] = useState(undefined);
    useEffect(() => {
        setValue(props.value);
        setOption(undefined);
    }, [props.value]);
    const changeValue = (value, option) => {
        setValue(value);
        setOption(option);
        if (typeof onChange === 'function') {
            onChange(value, option);
        }
        if (!emitTrigger || emitTrigger === 'onChange') {
            emitChange(value, option);
        }
    };

    const emitChange = (value, option) => {
        if (typeof onEmitChange === 'function') {
            onEmitChange(value, option);
        }
    };
    const onBlur = () => {
        emitChange(value, option);
    };
    if (emitTrigger === 'onBlur') {
        selfProps.onBlur = onBlur;
    }
    if (isMultiple) {
        selfProps.mode = 'multiple';
    }
    return (
        <div className={styles.container} onBlur={onBlur}>
            <Select className={styles.select} {...selfProps} value={value} onChange={changeValue}>
                {options.map((item) => (
                    <Select.Option key={item.id} value={item.id}>
                        {item.name}
                    </Select.Option>
                ))}
            </Select>
        </div>
    );
};
export default ApolloSelect;
