import React,{useState,useEffect} from "react"
import {Empty,Tree,Spin} from "antd"
import {metaManageService,metaAdminManageService,metaUserManageService} from "@/services"
import {domainChagneUtil, httpUtil} from "@/utils"
import { useSetState } from "ahooks"
import {useDebounceFn} from "ahooks"

const SystemTree:React.FC<any>=(props)=>{

    const {onClick,domain,sysreload=0,readOnly=false,dic=false,treeupdate=0,
        search=false,rightclick=()=>{},counttype='',height=undefined,hideChildrenType=false} = props

    const [tree,setTree] = useState<any>([])
    const [isload,setIsload] = useState(false)
    const [selecttreekey,setSelecttreekey] = useState<any>([])
    const [lastmodel,setLastmodel] = useState<any>([])
    const [expandkeys,setExpandkeys] = useState<any>([])
    const [totalcount,setTotalCount] = useSetState<any>({})

    useEffect(()=>{
        if(domain.value!==null){
            run()
            countSystem()
        }else{
            setTree([])
        }
    },[domain])

    useEffect(()=>{
        if(domain.value!==null){
            run()
        }else{
            setTree([])
        }
    },[sysreload,dic])

    useEffect(()=>{
        if(treeupdate){
            if(domain.value!==null){
                getTreeInfoReload()
            }else{
                setTree([])
            }
        }
    },[treeupdate])

    const {run} = useDebounceFn(()=>{
        getTreeInfo()
    },{wait:200})

    const getTreeInfo=async()=>{
        setIsload(true)
        const result:any = await metaManageService.getSearchType()
        let models:any = []
        if(httpUtil.checkSuccess(result,1)){
            for(let key in result.data){
                let types = result.data[key].split(',')
                let type = types[types.length-1]
                models.push(type)
            }
        }
        let systeminfo:any = null;
        if(search){
            systeminfo = await metaUserManageService.getTreeSystem({catalog:domain.domainId})
        }else{
            systeminfo = await metaAdminManageService.getTreeSystem({catalog:domain.domainId})
        }
        if(httpUtil.checkSuccess(systeminfo,1)){
            const childrendata = domainChagneUtil.getSystemInfoFromCatalog(systeminfo.data,domain.domainId)
            let firstsystem:any = {}
            let temp = []
            try {
                temp = JSON.parse(JSON.stringify(childrendata))
            } catch (error) {
                
            }
            // const childrens = usedataadmin(temp)
            const childrens = temp
            for(let i=0;i<(childrens).length;i++){
                const catalog = childrens[i];
                for(let j=0;j<(catalog.children||[]).length;i++){
                    if(!firstsystem.value){
                        let temp = catalog.children[j]
                        temp.pid = childrens[i].key
                        firstsystem=catalog.children[j]
                        break;
                    }
                }
                if(firstsystem.value)
                    break;
            }
            let treeobj:any = {
                title:firstsystem.label,
                key:firstsystem.key,
                ...firstsystem,
                isLeaf:false,
            }
            const list = (childrens).map((item:any)=>{
                item.disabled = false;
                item.unselected = true
                return item
            })
            setTree(list)
            if(!readOnly){
                setSelecttreekey([firstsystem.key])
                onClick(treeobj)
            }
            setExpandkeys([firstsystem.key,firstsystem.pid])
            setLastmodel(models)
        }
        setIsload(false)
    }

    const getTreeInfoReload=async()=>{
        setIsload(true)
        const result:any = await metaManageService.getSearchType()
        let models:any = []
        if(httpUtil.checkSuccess(result,1)){
            for(let key in result.data){
                let types = result.data[key].split(',')
                let type = types[types.length-1]
                models.push(type)
            }
        }
        let systeminfo:any = null;
        if(search){
            systeminfo = await metaUserManageService.getTreeSystem({catalog:domain.domainId})
        }else{
            systeminfo = await metaAdminManageService.getTreeSystem({catalog:domain.domainId})
        }
        if(httpUtil.checkSuccess(systeminfo,1)){
            const childrendata = domainChagneUtil.getSystemInfoFromCatalog(systeminfo.data,domain.domainId)
            let firstsystem:any = {}
            let temp = []
            try {
                temp = JSON.parse(JSON.stringify(childrendata))
            } catch (error) {
                
            }
            // const childrens = usedataadmin(temp)
            const childrens = temp
            for(let i=0;i<(childrens).length;i++){
                const catalog = childrens[i];
                for(let j=0;j<(catalog.children||[]).length;i++){
                    if(!firstsystem.value){
                        let temp = catalog.children[j]
                        temp.pid = childrens[i].key
                        firstsystem=catalog.children[j]
                        break;
                    }
                }
                if(firstsystem.value)
                    break;
            }
            const list = (childrens).map((item:any)=>{
                item.disabled = false;
                item.unselected = true
                return item
            })
            setTree(list)
            setIsload(false)
        }
    }

    const usedataadmin=(children:any)=>{
        const list = children.map((item:any)=>{
            if(search){
                const tempchildren = item.children
                item.children = tempchildren
                return item
            }else{
                const tempchildren = (item.children||[]).filter((i:any)=>i.admin)
                item.children = tempchildren
                return item
            }
        })
        return list;
    }

    const updateTreeData=(list:any, key:any, children: any):any=> {
        return list.map((node:any) => {
            if (node.key === key) {
                return {
                ...node,
                children,
                };
            }
            if (node.children) {
                return {
                ...node,
                children: updateTreeData(node.children, key, children),
                };
            }
            return node;
        });
    }

    const onLoadData=({ key, children,value,systeminfo,system,...other }: any)=> {
        return new Promise<void>(async (resolve) => {
            if (children) {
                resolve();
                return;
            }else{
                if(typeof(value)==='string'&&(value.includes('='))){
                    const childtypes:any = await metaManageService.getChildrenModel({name:value.split('=')[0]})
                    let notinclude = false
                    try {
                        childtypes.data.map((item:any)=>{
                            if(lastmodel.includes(item.name)){
                                notinclude=true
                            }
                        })
                        if(notinclude){
                            if(readOnly||dic||hideChildrenType){
                                resolve()
                                return;
                            }else{
                                let countlist:any = []
                                const childrens:any=childtypes.data.map((item:any)=>{
                                    item.key=`${system}${item.name}${value.split('=').join(',')}`;
                                    item.title=item.cnName;
                                    item.parentId=value
                                    item.system=system
                                    item.systeminfo=systeminfo?systeminfo:other
                                    item.parent=other
                                    countlist.push({key:item.key,path:item.path,system:item.system,filterId:other?.idPath})
                                    return item
                                })
                                countModelNode(countlist)
                                setTree((origin:any)=>{
                                    const datal = updateTreeData(origin,key,childrens)
                                    return datal
                                })
                                setTimeout(()=>{
                                    if(expandkeys.includes(key)){
                                        setExpandkeys([...expandkeys,key])
                                    }
                                },500)
                                resolve()
                                return;
                            }
                        }
                        let result:any = null;
                        //const result:any = await metaManageService.getChildByIdAndSys({parentId:value,sysId:system})
                        if(search){
                            result = await metaUserManageService.getChildrenByParentId({parentId:value,system:system,catalog:domain.domainId})
                        }else{
                            result = await metaAdminManageService.getChildrenByParentId({parentId:value,system:system,catalog:domain.domainId})
                        }
                        if(httpUtil.checkSuccess(result,1)){
                            let countlist:any = []
                            const childrens:any=result.data.map((item:any)=>{
                                item.title=item.name
                                item.key=`${system}-${item._id}`
                                item.value=item._id
                                item.system=system
                                item.systeminfo=systeminfo?systeminfo:other
                                countlist.push({key:item.key,idPath:item.idPath,system:item.system,parentIdPath:other.idPath,parentId:other._id,_id:item._id})
                                return item
                            })
                            countMetaNode(countlist)
                            setTree((origin:any)=>{
                                const datal = updateTreeData(origin,key,childrens)
                                return datal
                            })
                            setTimeout(()=>{
                                if(expandkeys.includes(key)){
                                    setExpandkeys([...expandkeys,key])
                                }
                            },500)
                            resolve()
                        }else{
                            resolve()
                        }
                        resolve()
                    } catch (error) {
                        console.log(error)
                        resolve()
                        return;
                    }
                }else if(typeof(value)==='number'){
                    // let payload:any={
                    //     data:[],
                    //     params:{
                    //         parentClass:'Catalog',
                    //         parentNamePath:domain.domainId,
                    //         system:value
                    //     }
                    // }
                    let result:any = null;
                    //const result:any = await metaManageService.getSystemChildren(payload)
                    if(search){
                        result = await metaUserManageService.getChildrenBySystem({system:value,catalog:domain.domainId})
                    }else{
                        result = await metaAdminManageService.getChildrenBySystem({system:value,catalog:domain.domainId})
                    }
                    if(httpUtil.checkSuccess(result,1)){
                        let countlist:any = []
                        const childrens:any=result.data.map((item:any)=>{
                            item.title=item.name
                            item.key=`${key}-${item._id}`
                            item.value=item._id
                            item.system=value
                            item.systeminfo=systeminfo?systeminfo:other
                            countlist.push({key:item.key,idPath:item.idPath,system:item.system})
                            return item
                        })
                        countMetaNode(countlist)
                        setTree((origin:any)=>{
                            const datal = updateTreeData(origin,key,childrens)
                            return datal
                        })
                        setTimeout(()=>{
                            if(expandkeys.includes(key)){
                                setExpandkeys([...expandkeys,key])
                            }
                        },500)
                        resolve()
                    }else{
                        resolve()
                    }
                }else{
                    resolve()
                }
            }
        });
    }

    const onSelectNode=(keys:any,datas:any)=>{
        if(datas?.node.unselected){
            if(expandkeys.includes(keys[0])){
                const key = expandkeys.filter((i:any)=>i!==keys[0])
                setExpandkeys(key)
            }else{
                const key = [...expandkeys,...keys]
                setExpandkeys(key)
            }
        }else{
            if(keys.length){
                setSelecttreekey(keys)
                onClick(datas.node)
            }
        }
    }

    const expand=(keys:any)=>{
        setExpandkeys(keys)
    }

    const countSystem=async()=>{
        if(counttype==='system'){
            const result:any = await metaManageService.countSystem({catalog:domain.domainId})
            if(httpUtil.checkSuccess(result,1)){
                let map:any={};
                (result?.data||[]).forEach((item:any)=>{
                    map[`system-${item._id}`]=item.total
                })
                setTotalCount(map)
            }
        }
    }

    const countMetaNode=async(ids:any)=>{
        if(counttype==='system'){
            if(ids.length){
                console.log(ids)
                let system = ids[0].system;
                let parentIdPath = ids[0].parentIdPath
                let parentId = ids[0].parentId;
                let pathkey:any = {}
                let filterIds=ids.map((item:any)=>{
                    pathkey[item.idPath] = item.key
                    return item.idPath
                })
                const result:any = await metaManageService.countMetaNode({catalog:domain.domainId,system,filterIds:filterIds.join(',')})
                if(httpUtil.checkSuccess(result,1)){
                    let data = result.data||{}
                    let map:any={};
                    for(let key in data){
                        let mkey = pathkey[key];
                        map[mkey] = data[key]
                    }
                    setTotalCount(map)
                }
                // if(parentId&&parentId.includes('Database')){
                //     let pathkey:any = {}
                //     ids.forEach((item:any)=>{
                //         pathkey[item._id] = item.key
                //     })
                //     const result:any = await metaManageService.countMetaDatabaseNode({catalog:domain.domainId,system,databaseIdPath:parentIdPath})
                //     if(httpUtil.checkSuccess(result,1)){
                //         let data = result.data||[]
                //         let map:any={};
                //         data.forEach((item:any)=>{
                //             let mkey = pathkey[item._id];
                //             map[mkey] = item.total
                //         })
                //         for(let key in pathkey){
                //             let mkey = pathkey[key];
                //             if(!map[mkey]){
                //                 map[mkey]=0
                //             }
                //         }
                //         setTotalCount(map)
                //     }
                // }else{
                //     let pathkey:any = {}
                //     let filterIds=ids.map((item:any)=>{
                //         pathkey[item.idPath] = item.key
                //         return item.idPath
                //     })
                //     const result:any = await metaManageService.countMetaNode({catalog:domain.domainId,system,filterIds:filterIds.join(',')})
                //     if(httpUtil.checkSuccess(result,1)){
                //         let data = result.data||{}
                //         let map:any={};
                //         for(let key in data){
                //             let mkey = pathkey[key];
                //             map[mkey] = data[key]
                //         }
                //         setTotalCount(map)
                //     }
                // }
            }
        }
    }

    const countModelNode=async(ids:any)=>{
        if(counttype==='system'){
            if(ids.length){
                let system = ids[0].system;
                let filterId=ids[0].filterId;
                let pathkey:any = {}
                console.log(ids)
                let modelPaths=ids.map((item:any)=>{
                    pathkey[item.path] = item.key
                    return item.path
                })
                const result:any = await metaManageService.countModelNode({data:modelPaths,params:{system,filterId,catalog:domain.domainId}})
                if(httpUtil.checkSuccess(result,1)){
                    let data = result.data||{}
                    let map:any={};
                    console.log(pathkey)
                    for(let key in data){
                        let keys = key.split(',');
                        keys[0] = 'Catalog'
                        let keyname = keys.join(',')
                        console.log(keyname)
                        let mkey = pathkey[keyname];
                        map[mkey] = data[key]
                    }
                    console.log(map)
                    setTotalCount(map)
                }
            }
        }
    }

    const titleRender=(node:any)=>{
        if(counttype==='system'){
            if(node.scopeId){//系统节点
                return <span>{node.title}<span style={{marginLeft:5}}>{totalcount[node.key]?`(${totalcount[node.key]})`:'(0)'}</span></span>
            }else if(node.namePathList&&node.namePathList.length){//元数据节点
                return <span>{node.title}{totalcount[node.key]!==undefined&&<span style={{marginLeft:5}}>{totalcount[node.key]?`(${totalcount[node.key]})`:'(0)'}</span>}</span>
            }else if(node.parent){
                return <span>{node.title}{totalcount[node.key]!==undefined&&<span style={{marginLeft:5}}>{totalcount[node.key]?`(${totalcount[node.key]})`:'(0)'}</span>}</span>
            }else{
                return node.title
            }
        }else{
            return node.title
        }
    }

    if(isload){
        return (
            <Spin style={{width:'100%',marginTop:20}} tip="数据加载中...">
      
            </Spin>
        )
    }
    if(tree.length===0&&!isload){
        return <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
    }
    if(tree.length||!isload){
        return(
            <Tree 
                showLine 
                autoExpandParent={false} 
                selectedKeys={selecttreekey} 
                expandedKeys={expandkeys} 
                onExpand={expand} 
                loadData={onLoadData} 
                onSelect={onSelectNode} 
                treeData={tree}
                style={{minWidth:200}}
                onRightClick={rightclick}
                titleRender={titleRender}
                height={height}
            />
        )
    }
    return (
        <Spin style={{width:'100%',marginTop:20}} tip="数据加载中...">
  
        </Spin>
    )
}

export default SystemTree