import React, { useEffect, useRef, useState } from 'react';
import { Modal, Tooltip } from 'antd';
import { ApolloUploadProps } from '../editInterface';
import { antiAssign } from '../../../../utils/utils';
import s from './index.less';
import Upload from '../../extra/upload';
import addIcon from '../../../../assets/addIcon.png';

export const ApolloUpload = (props: ApolloUploadProps) => {
    const { isMultiple, onEmitChange } = props;
    const selfProps = antiAssign(props, ['onChange', 'value']);
    if (isMultiple) {
        selfProps.multiple = true;
    }
    const [value, setValue] = useState(props.value || []);
    const changeValue = (value) => {
        setValue(value);
    };
    const [visible, setVisible] = useState(false);
    const refHelper = useRef(visible);
    const toggleUploadDialog = (flag) => {
        refHelper.current = flag;
        setVisible(flag);
    };
    // 点击Modal中上传时回调用浏览器弹框，触发onBlur，而此时并不希望触发onBlur，因此在组件内自定义监听
    useEffect(() => {
        document.addEventListener('click', onBlur, false);
        return () => {
            document.removeEventListener('click', onBlur, false);
        };
    }, []);
    const onBlur = () => {
        // 当弹框显示时，不触发emit事件
        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)}>
                <img alt="" className={s.addIcon} src={addIcon} />
            </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>
    );
};
