import React,{useEffect,useState,useMemo,useContext} from "react"
import {Input,Table,Row,Col} from "antd"
import LeftTreePanel from "@/component/layout/lefttreepanel"
import SystemTree from "./SystemTree"
import {useSelector} from "react-redux"
// import {setField,getTableInfo} from "@/view/meta/metamanage/store/action"
import { httpUtil, pageUtil } from "@/utils"
import {useDebounceEffect,useSetState} from "ahooks"
import {metaManageService} from "@/services"
import "./list.less"
import { useGetMetaCnName, useGetMetaTableInfo, useGetSearchType } from "./hooks"
import { AppContext } from "@/App"

// 元数据选择
const SelectMeta:React.FC<any>=(dprops)=>{

    const props=useSelector((state:any)=>{
        return {...state.session,...state.metaManage}
    })

    const {treeNode,keyword} = props

    const {selectType='checkbox',dellevel,selectMeta,height,selectedChild,setChildrenIds,setSystemId, setTablelist, tlist} = dprops
    
    const app = useContext(AppContext)

    const {env,hostParams} = app

    const systemmap = hostParams?.systemmap||{}

    const currentDomain = useMemo(()=>{
        if(env){
            return env
        }else{
            return {
                domainId: 2980796,
                domainName: "默认",
                key: "domain-2980796",
                label: "默认",
                options: null,
                title: "默认",
                value: 2980796
            }
        }
    },[env])


    const [value,setValues] = useState('')
    const [selectId,setSelectId] = useState('')
    const [ selectCache, setSelectCache ] = useState<any[]>([])
    const [ selectRowCache, setSelectRowCache ] = useState<any[]>([])

    const {modelCnName} = useGetMetaCnName()
    const {typelist} = useGetSearchType()

    const [state,setState] = useSetState({
        dataSource:[],
        total:0,
        pageable:{
            pageNum:1,
            pageSize:20
        },
        keyword:'',
        load:false,
        selectNode:{}
    })


    const {tablelist,tableload,tabletotal,changeOrder,changePage,pageable,changeSelect,selectedRowKeys} = useGetMetaTableInfo({treeNode:state.selectNode,currentDomain,keyword:value})

    

    useEffect(()=>{
        //dispatch(getUserSystm())
        setSelectCache([])
        setSelectRowCache([])
    },[])

    useDebounceEffect(()=>{
        if(selectId)
            getChildInfo()
    },[state.keyword,selectId,state.pageable],{wait:300})

    useDebounceEffect(() => {
        changekeyword()
    },[value],{wait: 1000,},);

    const changekeyword=()=>{
        //dispatch(setField({keyword:value}))
    }

    const getTableInfos=()=>{
        //dispatch(getTableInfo())
    }

    const nodeClick =(treeNode:any)=>{
        setSystemId?.(treeNode.system)
        setState({selectNode:treeNode})
        //dispatch(setField({treeNode:treeNode,pageable:{current:1,pagesize:20},selectedRowKeys:[]}))
    }

    const onChange = (a:any,b:any,sorter:any)=>{
        if(sorter.order){
            let orders:any = 'desc'
            if(sorter.order==='ascend')
                orders = 'asc'
            const order:any={orderBy:sorter.columnKey?sorter.columnKey:'lastUpdateTime',order:orders}
            changeOrder(order)
            //dispatch(setField({order}))
        }else{
            const order:any={orderBy:'seq',order:''}
            changeOrder(order)
            //dispatch(setField({order}))
        }
    }

    const changecurrent=(current:any,pagesize:any)=>{
        changePage(current,pagesize)
        //dispatch(setField({pageable:{current,pagesize}}))
    }

    const changecurrentchild=(pageNum:any,pageSize:any)=>{
        setState({pageable:{pageNum,pageSize}})
    }

    const tablecolumns=useMemo(()=>{
        let list:Array<any> = [
            {
                title:'序号',
                key:'index',
                width:60,
                render:(a:any,b:any,c:any)=>{
                    return ((pageable.pageNum-1)*pageable.pageSize+c+1)
                }
            },
            {
                title:'类型',
                dataIndex:"_class",
                key:'_class',
                width:90,
                sorter:true,
                ellipsis:true,
                resize:true,
                render:(text:any,record:any)=>{
                    try {
                        return modelCnName[record._id.split('=')[0]]||record._id.split('=')[0]
                    } catch (error) {
                        return ''
                    }
                }
            },
            {
                title:'英文名称',
                dataIndex:'name',
                key:'name',
                sorter:true,
                ellipsis:true,
                resize:true,
                render:(text:any,record:any)=>{
                    if(record.readable)
                        return pageUtil.showToolTip(text) 
                    else
                        return text
                }
            },
            {
                title:'中文名称',
                dataIndex:'comment',
                key:'comment',
                sorter:true,
                ellipsis:true,
                resize:true,
                render:(text:any,record:any)=>{
                    let name = text;
                    if(!name){
                        name = record.cnName;
                    }
                    return pageUtil.showToolTip(name)
                }
            },
            // {
            //     title:'名称路径',
            //     dataIndex:'namePathList',
            //     key:'namePathList',
            //     width:'18%',
            //     sorter:true,
            //     ellipsis:true,
            //     resize:true,
            //     render:(text:any,record:any)=>{
            //         let temp = [...text];
            //         temp.shift();
            //         return pageUtil.showToolTip(temp.join('/')) 
            //     }
            // },
        ]
        return list
    },[modelCnName,pageable])

    const rowSelection:any={
        selectedRowKeys:selectedRowKeys,
        onChange:(keys:any,datas:any)=>{
            changeSelect(keys,datas)
            selectMeta(datas[0],systemmap)
        },
        type:'radio',
        getCheckboxProps: (record: any) =>{
            const type = (record._id.split('=')[0])||'';
            return {
                disabled: type !== 'Table', // Column configuration not to be checked
            }
        },
    }

    const getChildInfo=async()=>{
        setState({load:true})
        const result:any = await metaManageService.getChildByIdAndSysByPage({params:{...state.pageable,keyword:state.keyword,parentId:selectId,system:treeNode.system,data:{}}})
        if(httpUtil.checkSuccess(result,1)){
            let idList:any = []
            let newList:any = []
            let newRowList:any = []
            try{
                
                if(result?.data?.content?.length){
                    result?.data?.content.forEach((element:any) => {
                        idList.push(element._id)
                    });
                    selectedChild.forEach((_id:any) => {
                        if(!idList.includes(_id)){
                            newList.push(_id)
                        }
                    });

                    tlist.forEach((item:any)=> {
                        if(!newList.includes(item._id)){
                            newRowList.push(item)
                        }
                    })
                }
            }catch(err){
                console.log('err',err)
            }
            setSelectCache(newList)
            setSelectRowCache(newRowList)
            setState({dataSource:result.data.content,total:result.data.totalElements})
        }else{
            setState({dataSource:[],total:0})
        }
        setState({load:false})
    }

    return(
        <div className="selectmeta" style={{height:height}} >
            <LeftTreePanel 
                leftPanel={
                    <div style={{height:height,background:"#fff",overflow:'auto',padding:12}}>
                        <SystemTree {...props} search={true} domain={currentDomain} onClick={nodeClick} dellevel={dellevel} />
                    </div>
                }
                rightPanel={
                    <Row style={{height:height,background:"#fff",overflow:'hidden'}} gutter={20}>
                        <Col span={24}>
                            <Input value={value} onChange={(e)=>{setValues(e.target.value)}} placeholder="请输入关键字" style={{width:180}} />
                            <div style={{height:height-40,marginTop:8}}>
                                <Table 
                                    columns={tablecolumns}
                                    dataSource={tablelist}
                                    loading={tableload}
                                    rowSelection={rowSelection}
                                    rowKey={"_id"}
                                    scroll={{y: `calc(${height}px - 135px)`}}
                                    size="middle"
                                    pagination={{
                                        size:'default',
                                        showTotal:total => `共 ${total} 条`,
                                        pageSize:pageable?.pageSize,
                                        current:pageable?.pageNum,
                                        total:tabletotal,
                                        onChange:changecurrent,
                                        position:['bottomLeft']
                                    }}
                                    onChange={onChange}
                                    // onRow={(record:any)=>{
                                    //     return {
                                    //         id:record._id,
                                    //         className:selectId===record._id?'selectTable':'',
                                    //         onClick:(e:any)=>{
                                    //             setSelectId(record._id)
                                    //         },
                                    //     }
                                    // }}
                                />
                            </div>
                        </Col>
                        {/* <Col span={12}>
                            <Input value={state.keyword} onChange={(e)=>{setState({keyword:e.target.value})}} placeholder="请输入关键字" style={{width:180}} />
                            <div style={{height: height - 80,marginTop:8, overflow: 'auto'}}>
                                <Table 
                                    columns={tablecolumns}
                                    dataSource={state.dataSource}
                                    loading={state.load}
                                    rowSelection={rowSelectionChild}
                                    rowKey={"_id"}
                                    scroll={{y: `calc(${height} - 135px)`}}
                                    size="middle"
                                    pagination={{
                                        showTotal:total => `共 ${total} 条`,
                                        pageSize:state.pageable.pageSize,
                                        current:state.pageable.pageNum,
                                        total:state.total,
                                        onChange:changecurrentchild,
                                        position:['bottomLeft']
                                    }}
                                />
                            </div>
                        </Col> */}
                    </Row>
                }
            />
        </div>
    )
}

export default SelectMeta