import React, {useRef, useState} from 'react';
import {Input, message, Modal} from 'antd';
import {useDispatch, useSelector} 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";
import {fileNameFormat, fullFileNameFormat} from "../../../utils/PathOperate";

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 = inputValue.current.input.value+prop.fileExt;
        let filePath = fullFileNameFormat(prop.fileDir,fileName)
        newFile(filePath)
        // 更新树
        dispatch(dirFileAdd({"fileDir":prop.fileDir,"filePath":filePath,fileName}))
        // 选中key，添加bar
        dispatch(addTableBarItem({
            label: fileName,
            children: filePath,
            key: filePath,
            activeKey: filePath
        }))
        setIsModalOpen(false);
    };
    const handleCancel = () => {
        setIsModalOpen(false);
    };
    return <>
        {contextHolder}
        <span className="menuItemClick" onClick={showModal}>{prop.fileExt}</span>
        <Modal title="新建文件名" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
            <Input ref={inputValue} placeholder="文件名不能为空" />
        </Modal>
    </>;
};
export default DirAddFile;