import React, { useEffect, useRef, useState } from "react"
import style from './index.less'
import Folder from "./folder";
import Material from "./material";
import { Card, message, Modal } from "antd";
import '../../tencentAdPutIn/index.less'
import { DataNode, EventDataNode } from "antd/lib/tree";
import { delFolderApi, getFolderListApi } from "@/services/adqV3/cloudNew";
import { useAjax } from "@/Hook/useAjax";
import ManageFolder from "./manageFolder";
import { ExclamationCircleOutlined, FolderOpenOutlined, FolderOutlined } from "@ant-design/icons";
import { updateTreeData } from "./const";
import Search from "./search";
import { useModel } from "umi";

export const DispatchCloudNew = React.createContext<CLOUDNEW.CloudNewReactContent | null>(null);

/**
 * 新版素材库
 * @returns 
 */
const CloudNew: React.FC = () => {

    /**********************************/
    const { initialState } = useModel('@@initialState');
    const refMaterial = useRef(null);
    const [treeData, setTreeData] = useState<DataNode[]>([]);
    const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
    const [queryFormFolder, setQueryFormFolder] = useState<CLOUDNEW.GetFolderListProps>({})
    const [folderVisible, setFolderVisible] = useState<boolean>(false)
    const [folderLoading, setFolderLoading] = useState<boolean>(false)
    const [breadcrumdData, setBreadcrumdData] = useState<CLOUDNEW.BreadcrumdData[]>([{ label: '全部素材', key: 0, currentKey: '0' }])
    const [loadedKeys, setLoadedKeys] = useState<string[]>([])  // 已经加载了的节点
    const [initialValuesFolder, setInitialValuesFolder] = useState<any>({})
    const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]); // 目录树打开控制
    const [folderCreateBy, setFolderCreateBy] = useState<number>()     // 获取最上层文件夹创建人
    const [batchFolderVisible, setBatchFolderVisible] = useState<boolean>(false) // 批量操作文件夹控制
    const [handleType, setHandleType] = useState<'folder' | 'file'>('file') // 操作类型
    const [materialParams, setMaterialParams] = useState<CLOUDNEW.GetMaterialListProps>({ pageNum: 1, pageSize: 30 })
    const [dragging, setDragging] = useState<any>()

    const getFolderList = useAjax((params) => getFolderListApi(params))
    const delFolderAjax = useAjax((params) => delFolderApi(params))
    /**********************************/

    useEffect(() => {
        handleGetFolder()
    }, [queryFormFolder?.folderName])

    useEffect(() => {
        if (breadcrumdData.length > 1) {
            let folderId = breadcrumdData[1].key
            setFolderCreateBy(getFolderList.data.find((item: { id: number; }) => item.id === folderId).createBy)
        } else {
            setFolderCreateBy(undefined)
        }
    }, [breadcrumdData, getFolderList.data])

    // 获取顶级文件夹列表
    const handleGetFolder = () => {
        setFolderLoading(() => true)
        setLoadedKeys(() => [])
        getFolderList.run({ folderName: queryFormFolder?.folderName }).then(res => {
            setFolderLoading(() => false)
            setTreeData(() => res?.map((item: { folderName: any; id: any; createBy: number }) => ({
                title: item.folderName,
                key: '0-' + item.id,
                isSelf: item.createBy?.toString() === initialState?.currentUser?.userId?.toString(),
                icon: ({ selected }: any) => (selected ? <FolderOpenOutlined style={{ color: 'rgb(255, 202, 40)' }} /> : <FolderOutlined style={{ color: 'rgb(255, 202, 40)' }} />),
            })) || [])
        }).catch(() => setFolderLoading(false))
    }

    // 下级目录
    const handleUpdateFolder = (parentIdStr: string) => {
        const parentIdArr = parentIdStr.split('-')
        const parentIdArrLength = parentIdArr.length
        const parentId = Number(parentIdArr[parentIdArrLength - 1])
        return getFolderListApi({ parentId }).then(res => {
            setLoadedKeys(loadedkeys => [...loadedkeys, parentIdStr].filter(item => !item.includes(parentIdStr + '-')))
            setExpandedKeys(expandedKeys => [...expandedKeys, parentIdStr])
            setTreeData(origin =>
                updateTreeData(origin, parentIdStr, res?.data?.map((item: { folderName: any; id: any; createBy: number }) => ({
                    title: item.folderName,
                    key: parentIdStr + '-' + item.id,
                    isSelf: item.createBy?.toString() === initialState?.currentUser?.userId?.toString(),
                    icon: ({ selected }: any) => (selected ? <FolderOpenOutlined /> : <FolderOutlined />)
                })) || []),
            );
        })
    }

    // 查找所有菜单列表（m面包屑）
    const findParentKeys = (key: string, tree: DataNode[]) => {
        let newBreadcrumdData: CLOUDNEW.BreadcrumdData[] = [{ label: '全部素材', key: 0, currentKey: '0' }]
        let keys = key.split('-')
        let treeData: DataNode[] = JSON.parse(JSON.stringify(tree))
        let currentKey: string = '0'
        keys.forEach((item, index) => {
            if (index !== 0) {
                currentKey = currentKey + '-' + item
                let treeD = treeData.find(item => item.key === currentKey)
                if (treeD) {
                    if (treeD?.children) {
                        treeData = treeD.children
                    }
                    newBreadcrumdData.push({ label: treeD?.title as string, key: Number(item), currentKey })
                }
            }
        })
        setBreadcrumdData(newBreadcrumdData)
    };

    // 删除文件夹
    const delFolder = (id: number, name: string) => {
        Modal.confirm({
            title: <strong>{`删除文件夹“${name}”`}</strong>,
            icon: <ExclamationCircleOutlined />,
            content: '是否确定删除该文件夹',
            okText: '确认',
            cancelText: '取消',
            className: 'modalResetCss',
            onOk: () => {
                return new Promise((resolve: (value: unknown) => void) => {
                    delFolderAjax.run(id).then(res => {
                        if (res) {
                            message.success('删除成功');
                            (refMaterial.current as any).folderRefresh()
                            if (selectedKeys[0] === '0' || !selectedKeys[0]) {
                                setTreeData(data => data.filter(item => item.key !== ('0-' + id)))
                            } else {
                                handleUpdateFolder(selectedKeys[0] as string)
                            }
                            resolve('')
                        }
                    })
                })
            }
        });
    }

    return <>
        <div className={style.cloudNew_layout}>
            <DispatchCloudNew.Provider value={{
                treeData, setTreeData,
                selectedKeys, setSelectedKeys,
                queryFormFolder, setQueryFormFolder,
                breadcrumdData, setBreadcrumdData,
                loadedKeys, setLoadedKeys,
                findParentKeys, handleUpdateFolder,
                expandedKeys, setExpandedKeys,
                folderCreateBy, setFolderCreateBy,
                batchFolderVisible, setBatchFolderVisible,
                handleType, setHandleType,
                materialParams, setMaterialParams,
                dragging, setDragging
            }}>
                {/* 搜索 */}
                <Search
                    onSearch={(value) => (refMaterial.current as any)?.search(value)}
                />
                <Card
                    style={{ height: '100%', flex: '1 0', overflow: 'hidden' }}
                    bodyStyle={{ padding: 0, overflow: 'auto hidden', height: '100%' }}
                    className="cardResetCss buttonResetCss"
                    bordered
                >
                    <div className={style.cloudNew}>
                        {/* 文件夹 */}
                        <Folder
                            loading={folderLoading}
                            onLoadData={(treeNode: EventDataNode<DataNode>) => {
                                return new Promise<void>(async (resolve) => {
                                    console.log('Trigger Select', treeNode);
                                    await handleUpdateFolder(treeNode.key as string)
                                    resolve()
                                })
                            }}
                            onRefreshMaterial={() => {
                                (refMaterial.current as any)?.onRefreshMaterial()
                            }}
                        />
                        {/* 素材列表 */}
                        <Material
                            onAddFolder={() => {
                                setFolderVisible(true)
                            }}
                            onUpdateFolder={(data) => {
                                setInitialValuesFolder(data)
                                setFolderVisible(true)
                            }}
                            onDelFolder={delFolder}
                            ref={refMaterial}
                        />
                    </div>
                </Card>
            </DispatchCloudNew.Provider>
        </div>

        {/* 文件夹新增修改 */}
        {folderVisible && <ManageFolder
            initialValues={initialValuesFolder}
            parentIdStr={selectedKeys?.[0] as string || '0'}
            visible={folderVisible}
            onClose={() => {
                setFolderVisible(false)
            }}
            onChange={(newData) => {
                setFolderVisible(false)
                if (initialValuesFolder?.id) {
                    (refMaterial.current as any).folderRefresh()
                    if (selectedKeys?.[0]) {
                        handleUpdateFolder(selectedKeys[0] as string)
                    } else {
                        setTreeData(data => data.map(item => {
                            return item.key === ('0-' + newData.id) ? { ...item, title: newData.folderName } : item
                        }))
                    }
                    setInitialValuesFolder(undefined)
                } else {
                    (refMaterial.current as any).folderRefresh()
                    if (selectedKeys?.[0]) {
                        handleUpdateFolder(selectedKeys[0] as string)
                    } else {
                        // handleGetFolder()
                        setTreeData(data => [...data, { title: newData.folderName, key: '0-' + newData.id, icon: ({ selected }: any) => (selected ? <FolderOpenOutlined style={{ color: 'rgb(255, 202, 40)' }} /> : <FolderOutlined style={{ color: 'rgb(255, 202, 40)' }} />) }])
                    }
                }
            }}
        />}
    </>
}

export default CloudNew