import { useAjax } from "@/Hook/useAjax"
import { copyMaterialApi, getFolderListApi } from "@/services/adqV3/cloudNew"
import { FolderOpenOutlined, FolderOutlined } from "@ant-design/icons"
import { Card, message, Modal, Spin } from "antd"
import Tree, { DataNode, EventDataNode } from "antd/lib/tree"
import React, { useEffect, useState } from "react"
import { updateTreeData } from "./const"
import '../../tencentAdPutIn/index.less'
import { CheckboxValueType } from "antd/lib/checkbox/Group"

interface Props {
    checkedList: CheckboxValueType[]
    userId: string,
    visible?: boolean
    onChange?: () => void
    onClose?: () => void
}
const CopyFile: React.FC<Props> = ({ checkedList, visible, userId, onChange, onClose }) => {

    /**********************************/
    const [treeData, setTreeData] = useState<DataNode[]>([]);
    const [folderLoading, setFolderLoading] = useState<boolean>(false)
    const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([])

    const getFolderList = useAjax((params) => getFolderListApi(params))
    const copyMaterial = useAjax((params) => copyMaterialApi(params))
    /**********************************/

    useEffect(() => {
        handleGetFolder()
    }, [])

    // 获取顶级文件夹列表
    const handleGetFolder = () => {
        setFolderLoading(() => true)
        getFolderList.run({}).then(res => {
            setFolderLoading(() => false)
            setTreeData(() => res?.map((item: { folderName: any; id: any; createBy: number }) => ({
                title: item.folderName,
                key: '0-' + item.id,
                disabled: userId !== item.createBy.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 => {
            setTreeData(origin =>
                updateTreeData(origin, parentIdStr, res?.data?.map((item: { folderName: any; id: any; createBy: number }) => ({
                    title: item.folderName,
                    key: parentIdStr + '-' + item.id,
                    disabled: userId !== item.createBy.toString(),
                    icon: ({ selected }: any) => (selected ? <FolderOpenOutlined /> : <FolderOutlined />)
                })) || []),
            );
        })
    }

    const handleOk = () => {
        if (selectedKeys?.length) {
            const parentIdArr = (selectedKeys[0] as string).split('-')
            const parentIdArrLength = parentIdArr.length
            const parentId = Number(parentIdArr[parentIdArrLength - 1])
            copyMaterial.run({ folderId: parentId, materialIds: checkedList }).then(res => {
                if (res) {
                    message.success('移动成功')
                    onChange?.()
                }
            })
        } else {
            message.error('请选择文件夹')
        }
    }

    return <Modal
        title={<strong>复制素材到</strong>}
        open={visible}
        onCancel={onClose}
        onOk={handleOk}
        className="modalResetCss"
        bodyStyle={{ backgroundColor: '#f1f4fc', maxHeight: 650, overflow: 'hidden', overflowY: 'auto', padding: '10px' }}
        maskClosable={false}
        okText="复制"
        confirmLoading={copyMaterial.loading}
    >
        <Card className="cardResetCss" title={<strong style={{ fontSize: 12 }}>文件夹列表</strong>}>
            <Spin spinning={folderLoading}>
                <Tree
                    showIcon
                    blockNode={true}
                    selectedKeys={selectedKeys}
                    loadData={(treeNode: EventDataNode<DataNode>) => {
                        return new Promise<void>(async (resolve) => {
                            await handleUpdateFolder(treeNode.key as string)
                            resolve()
                        })
                    }}
                    onSelect={(keys) => setSelectedKeys(keys)}
                    treeData={treeData}
                />
            </Spin>
        </Card>
    </Modal>
}

export default React.memo(CopyFile)