import { Button, Card, Form, message, Modal, Space, TreeSelect } from "antd"
import React, { useEffect, useState } from "react"
import '../../tencentAdPutIn/index.less'
import { addRemoteMaterialApi, getFolderListApi } from "@/services/adqV3/cloudNew"
import { useAjax } from "@/Hook/useAjax"
import { DataNode } from "antd/lib/tree"
import { updateTreeData } from "../cloudNew/const"

interface Props {
    data: any[]
    visible?: boolean
    onChange?: () => void
    onClose?: () => void
}
/**
 * 移动至素材库
 * @returns 
 */
const SaveMaterial: React.FC<Props> = ({ data, visible, onChange, onClose }) => {

    /*************************************/
    const [treeData, setTreeData] = useState<DataNode[]>([]);
    const [form] = Form.useForm();

    const getFolderList = useAjax((params) => getFolderListApi(params))
    const addRemoteMaterial = useAjax((params) => addRemoteMaterialApi(params))
    /*************************************/

    const handleOk = (values: any) => {
        console.log(values)
        addRemoteMaterial.run({
            ...values,
            data: data.map(item => ({
                aspectRatio: item.aspect_ratio,
                description: item.description,
                designerId: localStorage.getItem('userId'),
                fileSize: item.file_size,
                height: item.height,
                width: item.width,
                materialName: item.description,
                materialType: item.source,
                md5: item.signature,
                url: item.preview_url,
            }))
        }).then(res => {
            if (res) {
                message.success('任务创建成功，结果要几分钟后返回')
                onChange?.()
            }
        })
    }

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

    const getFolder = () => {
        getFolderList.run({}).then(res => {
            setTreeData(() => res?.map((item: { folderName: any; id: any; createBy: number }) => ({
                title: item.folderName,
                value: item.id,
                key: item.id,
                disabled: localStorage.getItem('userId') !== item.createBy.toString()
            })) || [])
        })
    }

    // 下级目录
    const handleUpdateFolder = (parentId: number) => {
        return getFolderListApi({ parentId }).then(res => {
            setTreeData(origin =>
                updateTreeData(origin, parentId, res?.data?.map((item: { folderName: any; id: any; createBy: number }) => ({
                    title: item.folderName,
                    value: item.id,
                    key: item.id,
                    disabled: localStorage.getItem('userId') !== item.createBy.toString()
                })) || []),
            );
        })
    }

    return <Modal
        title={<strong>{'保存至素材库'}</strong>}
        open={visible}
        onCancel={onClose}
        footer={null}
        className="modalResetCss"
        bodyStyle={{ padding: '0 0 40px', position: 'relative', borderRadius: '0 0 8px 8px' }}
        maskClosable={false}
        width={600}
    >
        <Form
            form={form}
            name="newFolder"
            labelAlign='left'
            labelCol={{ span: 4 }}
            layout="horizontal"
            colon={false}
            style={{ backgroundColor: '#f1f4fc', maxHeight: 650, overflow: 'hidden', overflowY: 'auto', padding: '10px', borderRadius: '0 0 8px 8px' }}
            scrollToFirstError={{
                behavior: 'smooth',
                block: 'center'
            }}
            onFinishFailed={({ errorFields }) => {
                message.error(errorFields?.[0]?.errors?.[0])
            }}
            onFinish={handleOk}
        >
            <Card className="cardResetCss">
                <Form.Item label={<strong>文件夹</strong>} name={'folderId'} rules={[{ required: true, message: '请选择文件夹' }]}>
                    <TreeSelect
                        loading={getFolderList.loading}
                        allowClear
                        style={{ width: '100%' }}
                        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                        placeholder="请选择文件夹"
                        loadData={({ value }) => {
                            return new Promise<void>(async (resolve) => {
                                await handleUpdateFolder(Number(value))
                                resolve()
                            })
                        }}
                        treeData={treeData}
                    />
                </Form.Item>
            </Card>

            <Form.Item className="submit_pull">
                <Space>
                    <Button onClick={onClose}>取消</Button>
                    <Button type="primary" htmlType="submit" loading={addRemoteMaterial.loading} className="modalResetCss">
                        确定
                    </Button>
                </Space>
            </Form.Item>
        </Form>
    </Modal>
}

export default React.memo(SaveMaterial)