import React, { useEffect, useRef, useState } from 'react';
import InputSearch from '../../extra/dataEntry/textSelect';
import { ApolloInputSearchProps } from '../editInterface';
import { antiAssign } from '@/apollo-table/utils/utils';
import s from './index.less';

const ApolloInputSearch = (props: ApolloInputSearchProps) => {
    const { onChange, request, type, emitTrigger, onEmitChange } = props;
    const selfProps = antiAssign(props, [
        'columnConfig',
        'value',
        'onChange',
        'emitTrigger',
        'onEmitChange',
        'request',
    ]);
    const [value, setValue] = useState(props.value);
    const dom = useRef(value);
    useEffect(() => {
        setValue(props.value);
    }, [props.value]);
    const changeValue = (value) => {
        setValue(value);
        dom.current = value;
        if (typeof onChange === 'function') {
            onChange(value, value);
        }
        if (!emitTrigger || emitTrigger === 'onChange') {
            emitChange(value, value);
        }
    };
    const emitChange = (value, option) => {
        if (typeof onEmitChange === 'function') {
            onEmitChange(value, option);
        }
    };
    const onBlur = () => {
        if (!dom.current) {
        }
        emitChange(dom.current, dom.current);
    };
    if (emitTrigger === 'onBlur') {
        selfProps.onBlur = onBlur;
    }
    useEffect(() => {
        document.addEventListener('click', onBlur, false);
        return () => {
            document.removeEventListener('click', onBlur, false);
        };
    }, []);
    const onClick = (e) => {
        e.stopPropagation(); //阻止事件冒泡
        e.nativeEvent.stopImmediatePropagation();
    };
    return (
        <div className={s.searchContainer} onClick={onClick}>
            <InputSearch
                className={s.select}
                request={(val) => request({ name: val, fieldValueName: type })}
                fieldNames={{ value: 'fieldValueValue', label: 'fieldValueName' }}
                {...selfProps}
                onChange={changeValue}
                value={value}
                initDataType="onfocus"
            />
        </div>
    );
};
export default ApolloInputSearch;
