import React, { useState, useMemo } from 'react';
import { Tree, Input, Card, Tooltip,Divider } from 'antd';
import { MinusSquareOutlined,FormOutlined,PlusSquareOutlined } from '@ant-design/icons';
import getPrem from '@/utils/getPrem';
import { useRequest } from 'ahooks';
import { doFetch } from '@/utils/doFetch';
let { Search } = Input;



function TreeRender({ url, deleteurl, saveurl, onselected }) {
    const [search, setsearch] = useState("");
    const { data, loading } = useRequest(() => {
        return doFetch({ url, params: { title: search } })
    });

    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: 68, 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: 68, 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();
                    const _it = this;
                    this.setState({
                        savetitle: null
                    })
                    if (getPrem("enElectricityMeterType_save", "ifs")) {
                        Modal.confirm({
                            icon: <></>,
                            closable: true,
                            title: "修改电表结构名称",
                            content: <div>
                                <Input placeholder={item.title} allowClear onChange={(e) => {
                                    _it.setState({
                                        savetitle: e.target.value
                                    })
                                }}></Input>
                            </div>,
                            okText: "修改",
                            cancelText: "取消",
                            onOk: () => {
                                return new Promise((resolve, reject) => {
                                    if (_it.state.savetitle) {
                                        ammeterTreeSave({
                                            electricityMeterTypeName: _it.state.savetitle,
                                            id: item.key,
                                        }).then(res => {
                                            if (res.code == "0000") {
                                                _it.resetData()
                                            }
                                        })
                                        resolve()
                                    } else {
                                        message.warn("请输入修改的名称")
                                        reject()
                                    }
                                })
                            }

                        })
                    }
                }}>
                    <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();
                            const _it = this;
                            this.setState({
                                savetitle: null
                            })
                            if (getPrem("enElectricityMeterType_save", "ifs")) {
                                Modal.confirm({
                                    icon: <></>,
                                    closable: true,
                                    title: "新增子结构",
                                    content: <div>
                                        <div style={{ marginBottom: 15, color: "#f50", fontSize: 16 }}>当前结构：{item.title}</div>
                                        <Input placeholder="子结构" allowClear onChange={(e) => {
                                            _it.setState({
                                                savetitle: e.target.value
                                            })
                                        }}></Input>
                                    </div>,
                                    okText: "新增",
                                    cancelText: "取消",
                                    onOk: () => {
                                        return new Promise((resolve, reject) => {
                                            if (_it.state.savetitle) {
                                                ammeterTreeSave({
                                                    electricityMeterTypeName: _it.state.savetitle,
                                                    parentId: item.key
                                                }).then(res => {
                                                    if (res.code == "0000") {
                                                        _it.resetData()
                                                    }
                                                })
                                                resolve()
                                            } else {
                                                message.warn("请输入修改的名称")
                                                reject()
                                            }
                                        })
                                    }
                                })
                            }

                        }}
                        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={() => {
                            ammeterTreeDelete({ id: item.key }).then(res => {
                                if (res.code == '0000') {
                                    this.resetData()
                                }
                            })
                        }}
                        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>
            <Search style={{ margin: '16px 0 8px 0' }} placeholder="搜索电表结构" onChange={setsearch} />

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

    );
}

export default TreeRender;