import React, { useEffect, useState } from 'react';
import { Input } from 'antd';
import styles from './styles.less';
import { antiAssign } from '../../../../utils/utils';
import { ApolloTextAreaProps } from '../editInterface';
import { Consumer } from '../../../context';

export const ApolloTextArea = (props: ApolloTextAreaProps) => {
    const { maxLength, onChange, value, cutLength, getDetail, rowData } = props;
    const selfProps = antiAssign(props, ['columnConfig', 'onChange', 'value']);
    const [curValue, setCurValue] = useState(value);
    useEffect(() => {
        setCurValue(value);
    }, [value]);
    useEffect(() => {
        if (value.length === cutLength) {
            getMore();
        }
    }, []);

    const changeValue = (e) => {
        if (typeof onChange === 'function') {
            onChange(e.target.value);
        }
    };

    const getMore = async () => {
        let newValue = await getDetail({ rowId: rowData.id });
        if (newValue) {
            newValue = newValue[0] && newValue[0].value;
            setCurValue(newValue);
        }
    };

    return (
        <Consumer>
            {({ locale }) => {
                return (
                    <div className={styles.container}>
                        <Input.TextArea
                            className={styles.input}
                            {...selfProps}
                            value={curValue}
                            onChange={changeValue}
                        />
                        {!!maxLength && (
                            <span className={styles.wordNumber}>
                                {`${locale.alreadyInput} ${(curValue || '').length}/${maxLength}`}
                            </span>
                        )}
                    </div>
                );
            }}
        </Consumer>
    );
};
