import './menu-tree-with-top-button.css';
import MenuTree from "./MenuTree.tsx";
import { IMenuTreeItem } from "../../interfaces/menu/IMenuTree.ts";
import { useContext, useEffect, useState } from "react";
import { del, get, post, put } from "../../util/AjaxUtils.ts";
import useMessage from "antd/es/message/useMessage";
import { IndexListDataType, IndexListDispatchContext, } from "../../context/IndexListContext.ts";
import { Input, MenuProps, Modal } from "antd";
import srcImg from '../../static/left/src.png'
import newImg from '../../static/left/new.png'
type ProjCategoryDTO = {
    projCategoryId: string;
    projCategoryParentId: string;
    projCategoryParentName: string;
    isParent: boolean;
    projCategoryName: string;
    projCategoryCode: string;

    subProjCategory: ProjCategoryDTO[];
}

class MenuTreeItem implements IMenuTreeItem {
    children: Array<IMenuTreeItem> | null;
    id: string;
    pId: string;
    level: number;
    isOpen: boolean;
    isParent: boolean;
    name: string;
    oldName: string;
    parent?: IMenuTreeItem | null;

    constructor(id: string, pId: string, name: string, level: number) {
        this.id = id;
        this.pId = pId;
        this.level = level;
        this.name = name;
        this.oldName = name;
        this.isOpen = false;
        this.isParent = false;
        this.children = null;
        this.parent = null;
    }

}

export default function MenuTreeWithTopButton() {
    const indexListDispatchContext = useContext(IndexListDispatchContext);

    const [messageApi, messageContext] = useMessage();
    const menuTrees: Array<IMenuTreeItem> = [];
    const [menuTreeArray, setMenuTreeArray] = useState(menuTrees);
    const [saveCategory, setSaveCategory] = useState<IMenuTreeItem>(new MenuTreeItem('-1', '0', '新目录', 1));
    const [editCategory, setEditCategory] = useState<IMenuTreeItem>(new MenuTreeItem('-1', '0', '新目录', 1));
    const [saveModal, setSaveModal] = useState(false);
    const [editModal, setEditModal] = useState(false);

    const menuArray = (datas: ProjCategoryDTO[], level: number) => {
        const menus: MenuTreeItem[] = [];
        datas.forEach((item) => {
            const menu = new MenuTreeItem(item.projCategoryId, item.projCategoryParentId, item.projCategoryName, level);
            if (item.subProjCategory && item.subProjCategory.length > 0) {
                menu.isParent = true;
                menu.children = menuArray(item.subProjCategory, level + 1);
            }
            menus.push(menu);
        })
        return menus;
    }

    const menus2Dropdowns = (datas: IMenuTreeItem[] | null) => {
        if (!datas) {
            return;
        }
        const dropdowns: MenuProps['items'] = [];
        datas.forEach((item) => {
            const children = menus2Dropdowns(item.children);
            dropdowns.push({
                key: item.id,
                label: item.name,
                title: item.name,
                children: children
            })
        })
        return dropdowns;
    }

    const clearActive = (array: IMenuTreeItem[]) => {
        array.forEach(item => {
            item.active = false;
            if (item.children) {
                clearActive(item.children)
            }
        })
    }

    useEffect(() => {
        get<ProjCategoryDTO[]>({
            messageApi,
            url: '/api/proj/category/listallbyparentid/0',
            onSuccess({ data }) {
                const menus = menuArray(data, 1);
                setMenuTreeArray(menus);
                indexListDispatchContext({
                    type: IndexListDataType.CATEGORY,
                    value: menus2Dropdowns(menus)
                })
            }
        })
    }, []);

    return (
        <>
            {/* <div className="center-top">
                <div className="center-top-lift">
                    <img src={srcImg} alt="" />
                    <div >目录</div>
                </div>
                <div className='center-top-right' onClick={() => {
                    setSaveCategory(new MenuTreeItem('-1', '0', '新目录', 1));
                    setSaveModal(true)
                }}>
                    <img src={newImg} alt="" />
                    <div>创建</div>
                </div> */}
            <div className="menu-tree-with-top-button">
                <button type="button" className="btn-cennter" >
                    <div className="center-top-lift">
                        <img src={srcImg} alt="" />
                        <div >目录</div>
                    </div>
                    <div className='center-top-right' onClick={() => {
                        setSaveCategory(new MenuTreeItem('-1', '0', '新目录', 1));
                        setSaveModal(true)
                    }}>
                        <img src={newImg} alt="" />
                        <div>创建</div>
                    </div>
                </button>
                <MenuTree
                    menus={menuTreeArray}
                    url={''}
                    setMenuTreeArray={() => {
                        setMenuTreeArray([
                            ...menuTreeArray
                        ])
                    }}
                    handleClick={(item) => {
                        const isActive = item.active;
                        clearActive(menuTreeArray);
                        if (!isActive) {
                            item.active = true;
                        }
                        setMenuTreeArray([
                            ...menuTreeArray
                        ])
                        indexListDispatchContext({
                            type: IndexListDataType.CATEGORY_CHANGE,
                            value: item.active ? item.id : ''
                        })
                    }}
                    handleExpand={() => {
                    }}
                    handleAddClick={(item) => {
                        const menuTreeItem = new MenuTreeItem('-1', item.id, '新目录', item.level + 1);
                        menuTreeItem.parent = item;
                        setSaveCategory(menuTreeItem);
                        setSaveModal(true)
                    }}
                    handleEditClick={(item) => {
                        setEditCategory(item);
                        setEditModal(true);
                    }}
                    handleRemoveClick={(item, index, parent) => {
                        del<any>({
                            messageApi,
                            url: `/api/proj/category/delete/${item.id}`,
                            onSuccess() {
                                if (parent) {
                                    parent?.children?.splice(index, 1);
                                } else {
                                    menuTreeArray.splice(index, 1);
                                }
                                setMenuTreeArray([
                                    ...menuTreeArray
                                ])
                                indexListDispatchContext({
                                    type: IndexListDataType.CATEGORY_DELETE,
                                    value: menus2Dropdowns(menuTreeArray)
                                })
                            }
                        })
                    }}

                    handleNameChange={(item) => {
                        indexListDispatchContext({
                            type: IndexListDataType.CATEGORY_CHANGE,
                            value: item.id
                        })
                    }}
                />
            </div>
            <Modal open={saveModal}
                title="添加目录"
                okText="确定"
                cancelText="取消"
                okButtonProps={{
                    style: {
                        backgroundColor: 'var(--color-primary)'
                    }
                }}
                onCancel={() => {
                    setSaveModal(false);
                }}
                onOk={() => {
                    if (!saveCategory.name) {
                        messageApi.error('请输入名称');
                        return;
                    }
                    // 新增
                    post<any>({
                        messageApi,
                        url: '/api/proj/category/save',
                        body: {
                            projCategoryParentId: saveCategory.pId,
                            projCategoryName: saveCategory.name
                        },
                        onSuccess({ data }) {
                            if (!saveCategory.parent) {
                                const menuTreeItem = new MenuTreeItem(`${data.data}`, '0', saveCategory.name, 1);
                                menuTreeItem.isParent = false;
                                menuTreeArray.push(menuTreeItem);
                                setMenuTreeArray([...menuTreeArray]);
                                indexListDispatchContext({
                                    type: IndexListDataType.CATEGORY,
                                    value: menus2Dropdowns(menuTreeArray)
                                })
                            } else {
                                saveCategory.parent.isParent = true;
                                saveCategory.parent.isOpen = true;
                                if (!saveCategory.parent.children) {
                                    saveCategory.parent.children = new Array<IMenuTreeItem>();
                                }
                                const menuTreeItem = new MenuTreeItem(`${data.data}`, saveCategory.id, saveCategory.name, saveCategory.level);
                                menuTreeItem.isParent = false;
                                saveCategory.parent.children.push(menuTreeItem);
                                setMenuTreeArray([
                                    ...menuTreeArray
                                ])
                                indexListDispatchContext({
                                    type: IndexListDataType.CATEGORY,
                                    value: menus2Dropdowns(menuTreeArray)
                                })
                            }

                            setSaveModal(false);
                        }
                    })
                }}
            >
                <Input value={saveCategory?.name} placeholder="请输入目录标题" maxLength={10} onChange={(e) => {
                    saveCategory.name = e.target.value;
                    setSaveCategory({ ...saveCategory })
                }} />
            </Modal>
            <Modal open={editModal}
                title="编辑目录"
                okText="确定"
                cancelText="取消"
                okButtonProps={{
                    style: {
                        backgroundColor: 'var(--color-primary)'
                    }
                }}
                onCancel={() => {
                    setEditModal(false);
                }}
                onOk={() => {
                    if (editCategory.name === '') {
                        messageApi.error('请输入名称');
                        return;
                    }
                    put<any>({
                        messageApi,
                        url: `/api/proj/category/update/${editCategory.id}`,
                        body: {
                            projCategoryParentId: editCategory.pId,
                            projCategoryName: editCategory.name
                        },
                        onSuccess() {
                            editCategory.oldName = editCategory.name;
                            setMenuTreeArray([
                                ...menuTreeArray
                            ])
                            indexListDispatchContext({
                                type: IndexListDataType.CATEGORY,
                                value: menus2Dropdowns(menuTreeArray)
                            })
                            setEditModal(false);
                        }
                    })
                }}
            >
                <Input value={editCategory?.name} placeholder="请输入目录标题" maxLength={10} onChange={(e) => {
                    editCategory.name = e.target.value;
                    setEditCategory({ ...editCategory })
                }} />
            </Modal>
            {messageContext}
        </>
    )
}