import './menu-tree.css';
import {useState} from "react";
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome'
import {faCaretRight, faCaretDown, faEdit, faPlus, faRemove} from '@fortawesome/free-solid-svg-icons';
import {IMenuTree, IMenuTreeItem} from "../../interfaces/menu/IMenuTree.ts";


export default function MenuTree(props: IMenuTree) {

    const [menusArray, setMenuArray] = useState([
        {
            id: '1',
            name: '一级目录',
            active: true,
            level: 1,
            children: [
                {
                    id: '1-1',
                    name: '二级目录',
                    active: false,
                    level: 1,
                    children: [
                        {
                            id: '1-1-1',
                            name: '三级目录',
                            active: false,
                            level: 1,
                            children: []
                        }
                    ]
                }
            ]
        }
    ]);

    const triggerChildren = (item: IMenuTreeItem) => {
        item.active = !item.active;
        setMenuArray([
            ...menusArray
        ]);
    }

    const renderMenu = (children: Array<IMenuTreeItem>, parent?: IMenuTreeItem) => {
        if (!children || children.length == 0) {
            return <></>
        }
        const lis = children.map((item, index) => {
            const isParent = item.children && item.children.length > 0;
            const icon = item.active ? faCaretDown : faCaretRight;
            const renderChildrenMenu = renderMenu(item.children, item);
            return (
                <li key={item.id}>
                    <div className="menu-title">
                        <div className="label">
                            {isParent ? <FontAwesomeIcon className="icon" icon={icon} onClick={() => {
                                triggerChildren(item)
                            }}/> : <></>}
                            <span onDoubleClick={() => {
                                triggerChildren(item)
                            }}>{item.name}</span>
                        </div>
                        <div className="icon-group">
                            <FontAwesomeIcon className="icon" icon={faEdit}/>
                            <FontAwesomeIcon className="icon" icon={faPlus}/>
                            <FontAwesomeIcon className="icon" icon={faRemove}/>
                        </div>
                    </div>
                    {renderChildrenMenu}
                </li>
            )
        })
        const active = parent ? parent.active : true;
        return <ul style={{display: active ? 'block' : 'none'}}>{lis}</ul>
    }

    const menuUl = renderMenu(menusArray);
    return <div className="menu-tree">{menuUl}</div>
}