import React, {useRef, useState} from 'react';
import {Input, message, Modal} from 'antd';
import {useDispatch} from "react-redux";
import {newFile} from "../../../utils/File";
import {dirFileAdd} from "../../../redux/dirMessage_reducer";
import {addTableBarItem} from "../../../redux/tableBarItem_reducer";
import {isEmpty} from "../../../utils/ObjectUtils";

const DirAddFile = (prop) => {
    console.log("prop",prop)
    const [isModalOpen, setIsModalOpen] = useState(false);
    const dispatch = useDispatch();
    const inputValue = useRef(null);
    const [messageApi, contextHolder] = message.useMessage();

    const showModal = () => {
        setIsModalOpen(true);
    };
    const handleOk = () => {
        console.log("inputValue",inputValue.current.input.value)
        // 如果为空则提示
        if (isEmpty(inputValue.current.input.value)){
            let messageType = messageApi.open({
                type: 'error',
                content: '文件名不能为空',
            });
            return
        }
        // 新建文件
        let fileName = prop.filePath+"/"+inputValue.current.input.value+".lexical"
        newFile(fileName)
        // 更新树
        dispatch(dirFileAdd({"filePath":prop.filePath,fileName}))
        // 选中key，添加bar
        dispatch(addTableBarItem({
            label: inputValue.current.input.value+".lexical",
            children: fileName,
            key: fileName,
            activeKey: fileName
        }))
        setIsModalOpen(false);
        prop.closeMenu()
    };
    const handleCancel = () => {
        setIsModalOpen(false);
        prop.closeMenu()
    };
    return <>
        {contextHolder}
        <span onClick={showModal}>添加文件</span>
        <Modal title="新建文件名" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
            <Input ref={inputValue} placeholder="文件名不能为空" />
        </Modal>
    </>;
};
export default DirAddFile;