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

interface Props {
    mediaType: 'IMG' | 'VIDEO'
    selectSc: any[]
    visible?: boolean
    onClose?: () => void
}

/**
 * 批量迁移素材
 * @returns 
 */
const Migrate: React.FC<Props> = ({ visible, onClose, mediaType, selectSc }) => {

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

    const getFolderList = useAjax((params) => getFolderListApi(params))
    const moveOldMaterial = useAjax((params) => moveOldMaterialApi(params))
    /******************************/

    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()
                })) || []),
            );
        })
    }

    const handleOk = (values: any) => {
        console.log(values)
        moveOldMaterial.run({ ...values, materialType: mediaType === 'IMG' ? 'image' : 'video', materialIds: selectSc.map(item => item.id) }).then(res => {
            console.log(res)
            if (res) {
                message.success('迁移成功')
                onClose?.()
            }
        })
    }

    return <Modal
        title={<strong>批量迁移素材</strong>}
        className='modalResetCss'
        open={visible}
        onCancel={onClose}
        footer={null}
        bodyStyle={{ padding: '0 0 40px', position: 'relative', borderRadius: '0 0 8px 8px' }}
        maskClosable={false}
    >

        <Form
            form={form}
            name="migrate"
            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'
            }}
            onFinish={handleOk}
            onFinishFailed={({ errorFields }) => {
                message.error(errorFields?.[0]?.errors?.[0])
            }}
        >
            <Card className="cardResetCss">
                <Form.Item label={<strong>文件夹</strong>} name={'targetFolderId'} rules={[{ message: '请选择文件夹', required: true }]}>
                    <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={moveOldMaterial.loading} className="modalResetCss">
                        确定
                    </Button>
                </Space>
            </Form.Item>
        </Form>
    </Modal>
}

export default React.memo(Migrate)