import React, { useState, useMemo, useRef, createContext } from 'react';
import { Tree, Input, Popconfirm, Tooltip, Divider, Modal, message } from 'antd';
import { MinusSquareOutlined, FormOutlined, PlusSquareOutlined } from '@ant-design/icons';
import getPrem from '@/utils/getPrem';
import { useRequest } from 'ahooks';
import { doFetch } from '@/utils/doFetch';

const ReachableContext = createContext(null);
let { Search } = Input,
    { TreeNode } = Tree;




function TreeRender({ url, deleteurl, saveurl, onselected }) {
    const [search, setsearch] = useState("");
    const [savetitle, setsavetitle] = useState(null);
    const [modal, setModal] = useState({
        visible: false
    });
    const { data, loading, refresh } = useRequest(() => {
        return doFetch({ url, params: { title:  search } })
    },{
        refreshDeps:[search]
    });
    const ref1 = useRef(), ref2 = useRef();
    const treeData = useMemo(() => {
        return data?.data?.dataList ?? []
    }, [data]);

    const loop = data => data.map(item => {
        const index = item.title.indexOf(search);
        const beforeStr = item.title.substr(0, index);
        const afterStr = item.title.substr(index + search.length);
        const title =
            index > -1 ? (
                <Tooltip title={item.title} placement="bottom">
                    <span style={{ display: "inline-block", maxWidth: 88, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                        {beforeStr}
                        <span style={{ color: '#f50' }}>{search}</span>
                        {afterStr}
                    </span>
                </Tooltip>
            ) : (
                <Tooltip title={item.title} placement="bottom">
                    <span style={{ display: "inline-block", maxWidth: 88, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{item.title}</span>
                </Tooltip>
            );

        const actiontitle = (
            <div style={{ display: "flex", alignItems: "center" }}>
                {title}
                <Divider type='vertical' style={{ margin: "0 6px" }}></Divider>
                <Tooltip title="编辑" onClick={(e) => {
                    e.stopPropagation();
                    setsavetitle(null)
                    if (getPrem("enElectricityMeterType_save", "ifs")) {
                        setModal({
                            visible: true,
                            closable: true,
                            title: "修改节点名称",
                            okText: "修改",
                            cancelText: "取消",
                            placeholder: item.title,
                            key: item.key
                        })
                    }
                }}>
                    <FormOutlined style={{ color: "#1890ff" }} />
                </Tooltip>
                <Divider type='vertical' style={{ margin: "0 6px" }}></Divider>
                <Tooltip title="新增">
                    <PlusSquareOutlined
                        disabled={!getPrem("enElectricityMeterType_save", "ifs")}
                        onClick={(e) => {
                            e.stopPropagation();
                            setsavetitle(null)
                            if (getPrem("enElectricityMeterType_save", "ifs")) {
                                setModal({
                                    visible: true,
                                    closable: true,
                                    title: "新增子结构",
                                    okText: "新增",
                                    cancelText: "取消",
                                    placeholder: item.title,
                                    key: item.key
                                })
                            }
                        }}
                        style={{ color: `${getPrem("enElectricityMeterType_save", "ifs") ? "green" : ""}` }}
                    /></Tooltip>
                {
                    (!item.children || item.children.length == 0) &&
                    <Divider type='vertical' style={{ margin: "0 6px" }}></Divider>
                }
                {
                    (!item.children || item.children.length == 0) &&
                    <Popconfirm
                        placement='bottom'
                        title="是否删除该节点？"
                        okText="删除"
                        cancelText="取消"
                        onConfirm={() => {
                            doFetch({ url: deleteurl, params: { id: item.key } }).then(res => {
                                if (res.code == '0000') {
                                    message.success("操作成功")
                                    refresh();
                                }
                            })
                        }}
                        disabled={!getPrem("enElectricityMeterType_deleteById", "ifs")}
                    >
                        <Tooltip title="删除">
                            <MinusSquareOutlined onClick={(e) => { e.stopPropagation() }} style={{ color: "red" }} />
                        </Tooltip>
                    </Popconfirm>

                }


            </div>
        )
        // if (item.children) {
        //     return (
        //         <TreeNode key={item.key} title={actiontitle}>
        //             {loop(item.children)}
        //         </TreeNode>
        //     );
        // }
        // return <TreeNode key={item.key} title={title} />;
        return (
            <TreeNode key={item.key} title={actiontitle}>
                {item.children && loop(item.children)}
            </TreeNode>
        );
    });


    return (
        <div>
            <Modal
                {...modal}
                onCancel={() => {
                    setModal(s => ({
                        ...s,
                        visible: false
                    }))
                }}
                onOk={() => {
                    if (modal.okText == "修改") {
                        return new Promise((resolve, reject) => {
                            if (savetitle) {
                                console.log(ref1.current);
                                doFetch({
                                    url: saveurl,
                                    params: {
                                        materieTypeName: savetitle,
                                        id: modal.key,
                                    }
                                }).then(res => {
                                    if (res.code == "0000") {
                                        message.success("操作成功")

                                        refresh()
                                        setModal({
                                            visible: false
                                        })
                                    }
                                })
                                resolve()
                            } else {
                                message.warn("请输入修改的名称")
                                reject()
                            }
                        })
                    } else {
                        return new Promise((resolve, reject) => {
                            if (savetitle) {
                                doFetch({
                                    url: saveurl,
                                    params: {
                                        materieTypeName: savetitle,
                                        parentId: modal.key,
                                    }
                                }).then(res => {
                                    if (res.code == "0000") {
                                        message.success("操作成功")
                                        refresh()
                                        setModal({
                                            visible: false
                                        })
                                    }
                                })
                                resolve()
                            } else {
                                message.warn("请输入修改的名称")
                                reject()
                            }
                        })
                    }

                }}
            >
                {
                    modal.okText == "修改" ?
                        <div>
                            <Input placeholder={modal.placeholder} allowClear value={savetitle} onChange={(e) => {
                                setsavetitle(e.target.value)
                            }}></Input>
                        </div> :
                        <div>
                            <div style={{ marginBottom: 15, color: "#f50", fontSize: 16 }}>当前结构：{modal.placeholder}</div>
                            <Input placeholder="子结构" allowClear onChange={(e) => {
                                setsavetitle(e.target.value)
                            }}></Input>
                        </div>
                }
            </Modal>
            <Search value={search} style={{ margin: '16px 0 8px 0' }} placeholder="搜索" onChange={(e)=>{
                setsearch(e.target.value)
            }} />

            <Tree
                onSelect={(selectedKeys, e) => {
                    onselected?.(selectedKeys)
                }}
                autoExpandParent={true}
            >
                {loop(treeData ? treeData : [])}
            </Tree>
        </div>

    );
}

export default TreeRender;