import React, { forwardRef, Ref, useContext, useImperativeHandle } from "react"
import style from './index.less'
import { Button, Empty, message, Spin, Tree } from "antd"
import { DataNode, DirectoryTreeProps, EventDataNode } from "antd/lib/tree";
import { DispatchCloudNew } from ".";
import { useDrop } from "ahooks";
import { useAjax } from "@/Hook/useAjax";
import { moveMaterialApi } from "@/services/adqV3/cloudNew";

interface FolderRef {
    folderRefresh: () => void
}
interface Props {
    loading: boolean
    onLoadData: (treeNode: EventDataNode<DataNode>) => Promise<void>
    onRefreshMaterial?: () => void
}

/**
 * 自定义头部
 * @param param0 
 * @returns 
 */
const TreeTitleRender: React.FC<{ nodeData: any, dragging: any, onChange: () => void }> = ({ nodeData, dragging, onChange }) => {

    /***************************/
    const moveMaterial = useAjax((params) => moveMaterialApi(params))
    /***************************/

    const [props, { isHovering }] = useDrop({
        onDom: (content: any) => {
            const hide = message.loading('移动中。。。', 0)
            const parentIdArr = nodeData.key.split('-')
            const parentIdArrLength = parentIdArr.length
            const parentId = Number(parentIdArr[parentIdArrLength - 1])
            moveMaterial.run({ folderId: parentId, materialIds: [content.id] }).then(res => {
                hide()
                if (res) {
                    message.success('移动成功')
                    onChange?.()
                }
            }).catch(() => hide())
        },
    });

    return <span {...props} style={dragging ? { border: '1px dashed #f3c6c6', borderColor: isHovering ? '#1890ff' : '#f3c6c6' } : {}}>{nodeData.title}</span>
}

/**
 * 文件夹
 * @returns 
 */
const Folder = forwardRef(({ loading, onLoadData, onRefreshMaterial }: Props, ref: Ref<FolderRef>) => {

    /******************************/
    const { treeData, setSelectedKeys, selectedKeys, setMaterialParams, setBreadcrumdData, findParentKeys, loadedKeys, setBatchFolderVisible, handleUpdateFolder, expandedKeys, setExpandedKeys, dragging } = useContext(DispatchCloudNew)!;

    /******************************/

    useImperativeHandle(ref, () => ({
        folderRefresh() {

        }
    }));

    // 选中文件
    const onSelect: DirectoryTreeProps['onSelect'] = (keys, info) => {
        console.log('Trigger Expand', keys, info);
        if (!info.selected) {
            return
        }
        if (keys?.length) {
            findParentKeys(keys?.[0] as string, treeData)
        } else {
            setBreadcrumdData([{ label: '全部素材', key: 0, currentKey: '0' }])
        }
        // 判断是否加载了下级文件  加载了 就不更新
        if (!loadedKeys.includes(keys[0] as string))
            handleUpdateFolder(keys[0] as string)
        setBatchFolderVisible(false)
        setSelectedKeys(keys);
        setMaterialParams(data => ({ ...data, pageNum: 1 }))
    };

    const onExpand = (expandedKeysValue: React.Key[]) => {
        setExpandedKeys(expandedKeysValue);
    };

    return <div className={style.folder}>
        <div className={style.top}>
            <Button
                style={{ padding: 0, height: 'auto', width: 71, fontSize: 14 }}
                onClick={() => {
                    setSelectedKeys([])
                    setBreadcrumdData([{ label: '全部素材', key: 0, currentKey: '0' }])
                }}
                type="text"
            >全部素材</Button>
            {/* <Input.Search enterButton style={{marginTop: 6,}} allowClear placeholder="文件夹名称" onSearch={(value) => { setQueryFormFolder({ folderName: value }) }} /> */}
        </div>
        <div className={style.bottom}>
            <Spin spinning={loading}>
                <Tree
                    showIcon
                    blockNode={true}
                    selectedKeys={selectedKeys}
                    loadData={onLoadData}
                    onSelect={onSelect}
                    treeData={treeData}
                    loadedKeys={loadedKeys}
                    onExpand={onExpand}
                    expandedKeys={expandedKeys}
                    titleRender={(nodeData: any) => nodeData.isSelf ? <TreeTitleRender nodeData={nodeData} dragging={dragging} onChange={() => onRefreshMaterial?.()}/> : <span>{nodeData.title}</span>}
                />
                {!(treeData?.length > 0) && (loading ? <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: 200 }} ></div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无文件夹" />)}
            </Spin>
        </div>
    </div>
})

export default React.memo(Folder)