import React, { useEffect, useRef, useState } from 'react';
import { ApolloUploadProps } from '../editInterface';
import { antiAssign } from '@/apollo-table/utils/utils';
import CellContainer from '../container';
import s from './index.less';
import Upload from '../../extra/upload';
import IconFont from '@/apollo-table/component/base/extra/iconFont';
import { Modal, Tooltip } from 'antd';

const ApolloUpload = (props) => {
    const { isMultiple, onEmitChange } = props;
    const selfProps = antiAssign(props, ['onChange', 'value']);
    if (isMultiple) {
        selfProps.multiple = true;
    }
    const [value, setValue] = useState(props.value || []);
    const changeValue = (value) => {
        console.log(value);
        setValue(value);
    };
    const [visible, setVisible] = useState(false);
    const refHelper = useRef(visible);
    const toggleUploadDialog = (flag) => {
        refHelper.current = flag;
        setVisible(flag);
    };
    useEffect(() => {
        document.addEventListener('click', onBlur, false);
        return () => {
            document.removeEventListener('click', onBlur, false);
        };
    }, []);
    const onBlur = () => {
        if (refHelper.current) {
            return;
        }
        if (typeof onEmitChange === 'function') {
            onEmitChange(props.value);
        }
    };
    const onOk = () => {
        if (typeof onEmitChange === 'function') {
            onEmitChange(value);
        }
        toggleUploadDialog(false);
    };
    const onCancel = () => {
        if (typeof onEmitChange === 'function') {
            onEmitChange(props.value);
        }
        toggleUploadDialog(false);
    };
    const onClickContainer = (e) => {
        e.stopPropagation(); //阻止事件冒泡
        e.nativeEvent.stopImmediatePropagation();
    };
    return (
        <div className={s.container} onClick={onClickContainer}>
            <div className={s.add} onClick={toggleUploadDialog.bind(null, true)}>
                <IconFont type="iconxinzeng" />
            </div>
            {value &&
                value.map((item, i) => {
                    return (
                        <div key={i} className={s.picContainer}>
                            <Tooltip placement="bottom" title={item.name}>
                                <img className={s.pic} src={item.thumbUrl} />
                            </Tooltip>
                        </div>
                    );
                })}
            <Modal visible={visible} title="文件上传" onOk={onOk} onCancel={onCancel}>
                <div className={s.uploadContainer}>
                    <Upload {...selfProps} value={value} onChange={changeValue} />
                </div>
            </Modal>
        </div>
    );
};

export default ApolloUpload;
