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

const ApolloInput = (props: ApolloInputProps) => {
    const { maxLength, onChange, emitTrigger, onEmitChange, style } = props;
    const selfProps = antiAssign(props, ['columnConfig', 'value', 'onChange', 'emitTrigger', 'onEmitChange', 'style']);
    const [value, setValue] = useState(props.value);
    useEffect(() => {
        setValue(props.value);
    }, [props.value]);
    const changeValue = (e) => {
        setValue(e.target.value);
        if (typeof onChange === 'function') {
            onChange(e.target.value);
        }
        if (!emitTrigger || emitTrigger === 'onChange') {
            emitChange(e);
        }
    };

    const emitChange = (e) => {
        if (typeof onEmitChange === 'function') {
            onEmitChange(e.target.value);
        }
    };
    if (emitTrigger === 'onBlur') {
        selfProps.onBlur = emitChange;
    }
    const newStyle:any = {
        ...style
    };
    if (maxLength && style) {
        newStyle.minHeight = Number(style.minHeight) + 10;
        newStyle.paddingBottom = 18;
    }
    return (
        <div className={styles.container}>
            <Input
                className={styles.input}
                style={newStyle}
                {...selfProps}
                value={value}
                onChange={changeValue}
            />
            {!!maxLength && (
                <span className={styles.wordNumber}>
                    已输入{(value || '').length}/{maxLength}
                </span>
            )}
        </div>
    );
};
export default ApolloInput;
