import { CloseCircleOutlined, DeleteOutlined, PlusOutlined } from "@ant-design/icons"
import { Button, Card, Dropdown, Empty, Form, InputNumber, Modal, Popconfirm, Space, message } from "antd"
import React, { useEffect, useState } from "react"
import styles from './index.less'
import VideoNews from "@/pages/launchSystemNew/components/newsModal/videoNews"
import { chunkArray1, getVideoImgUrl } from "@/utils/utils"
import VideoFrameSelect from "@/pages/launchSystemV3/components/VideoFrameSelect"
import New1Radio from "@/pages/launchSystemV3/components/New1Radio"
import SelectCloudNew from "@/pages/launchSystemV3/material/cloudNew/selectCloudNew"

interface Props {
    adLength: number,
    creativeTemplateId: number
    materialData: any
    deliveryMode: string,
    isSelectRemote?: boolean
    value?: any,
    visible?: boolean
    onClose?: () => void
    onChange?: (value: any) => void
    accountCreateLogs?: PULLIN.AccountCreateLogsProps[]
}

const AddMaterial: React.FC<Props> = ({ creativeTemplateId, materialData, deliveryMode, visible, isSelectRemote, value, onChange, onClose, adLength, accountCreateLogs }) => {

    /*********************************/
    const [form] = Form.useForm();
    const dynamicGroup = Form.useWatch('dynamicGroup', form)
    const mediaType = Form.useWatch('mediaType', form)

    const [materialConfig, setMaterialConfig] = useState<{
        adcreativeTemplateId?: number,
        type: string,
        cloudSize: { relation: string, width: number, height: number }[],
        list: any[],
        index: number,
        max: number,
        sliderImgContent: any,
        isGroup?: boolean
    }>({
        type: '',//类型
        cloudSize: [],//素材搜索条件
        list: [],//素材
        index: 0, // 素材组下标
        max: 1,//素材数量
        sliderImgContent: undefined
    })//图片素材配置
    const [selectVideoVisible, setSelectVideoVisible] = useState(false)
    const [mLength, setMLength] = useState<number>(1)
    const [videoUploads, setVideoUploads] = useState<any>()
    const [imgUploads, setImgUploads] = useState<any>()
    const [minNumber, setMinNumber] = useState<number>(3)
    const [mCount, setMCount] = useState<number>(1)
    const [selectCloudData, setSelectCloudData] = useState<{
        defaultParams: {
            sizeQueries?: {
                width: number,
                height: number,
                relation: string
            }[],
            materialType: 'image' | 'video'
            fileSize: number
        }
        num: number
    }>()
    /*********************************/

    useEffect(() => {
        if (materialData && Object.keys(materialData).length > 0) {
            let fKey = Object.keys(materialData)[0];
            let children = materialData[fKey]?.children
            let childrenKey = Object.keys(children)
            setMLength(childrenKey?.length)

            let videoData = childrenKey?.find(item => item === 'short_video1' || item === 'video_id')
            if (videoData) {
                setVideoUploads(children[videoData])
            }
            let imageData = childrenKey?.find(item => item === 'cover_id' || item === 'image_id')
            if (imageData) {
                setImgUploads(children[imageData])
            }
            let imageListData = childrenKey?.find(item => item === 'list')
            if (imageListData) {
                let data = children[imageListData]
                if (fKey === 'image_list') {
                    setMinNumber(data.arrayProperty.mixNumber)
                    setImgUploads({ ...data['children']['image_id'], arrayProperty: data.arrayProperty, name: 'image_list' })
                } else if (fKey === 'element_story') {
                    setMinNumber(data.arrayProperty.mixNumber)
                    setImgUploads({ ...data['children']['image'], arrayProperty: data.arrayProperty, name: 'element_story' })
                }
            }
        } else {
            setVideoUploads({})
            setImgUploads({})
        }
    }, [materialData])

    const setFrame = (url: string, num: number, field: string) => {
        let newDynamicGroup = dynamicGroup?.map((item: any, index: number) => {
            if (num === index) {
                if (item) {
                    item[field] = { ...item[field], url, id: null }
                    return { ...item }
                } else {
                    return { [field]: { url, id: null, materialType: 0 } }
                }
            }
            return item
        })
        form.setFieldsValue({ dynamicGroup: newDynamicGroup })
    }

    const handleOk = (values: any) => {
        const { mediaType, dynamicGroup } = values
        if (mediaType === 2 && dynamicGroup.length > adLength) {
            message.error({
                content: `创意组分配规则选择“顺序分配到广告”时，创意组总数必须小于等于广告总数。当前广告总数：${adLength}，创意组总数：${dynamicGroup.length}`,
                duration: 8
            })
            return
        }
        onChange?.({ mediaType, dynamicMaterialDTos: { dynamicGroup } })
    }

    useEffect(() => {
        console.log('value--->', value)
        if (value) {
            const { dynamicMaterialDTos, mediaType } = value
            form.setFieldsValue({ ...dynamicMaterialDTos, mediaType })
        }
    }, [value])

    const clearTem = (index: number, count: number) => {
        let newDynamicGroup = dynamicGroup?.map((item: any, i: number) => {
            if (i === index) {
                let oldList = item?.list?.filter((_: any, li: number) => count !== li)
                return { list: oldList }
            }
            return item
        })
        form.setFieldsValue({ dynamicGroup: newDynamicGroup })
    }

    const selectGroupImg = (index: number, num: number) => {
        setSelectCloudData({ defaultParams: { sizeQueries: [{ width: 800, height: 800, relation: '=' }], fileSize: 400 * 1024, materialType: 'image' }, num })
        setMaterialConfig({
            ...materialConfig,
            type: 'image',
            max: num,
            index,
            adcreativeTemplateId: creativeTemplateId,
            isGroup: true
        })
        setTimeout(() => {
            setSelectVideoVisible(true)
        }, 100)
    }

    // 获取组件化创意素材数量
    const getComponentCount = (list: any[]): string => {
        let arrayImgCount = 0, imageCount = 0, videoCount = 0
        list?.forEach((item: any) => {
            if (Array.isArray(item)) {
                arrayImgCount++
            } else if (item?.url?.includes('mp4')) {
                videoCount++
            } else {
                imageCount++
            }
        })
        return `${imageCount}张图片，${videoCount}个视频，${arrayImgCount}个组图`
    }
    console.log('dynamicGroup---->', dynamicGroup)

    return <Modal
        title={<Space>
            <strong style={{ fontSize: 20 }}>创意素材</strong>
            {deliveryMode === 'DELIVERY_MODE_CUSTOMIZE' ? <>
                {videoUploads && Object.keys(videoUploads)?.length > 0 && <Button type="link" onClick={() => {
                    setSelectCloudData({ defaultParams: { sizeQueries: creativeTemplateId === 1708 ? [{ relation: '>=', width: 1280, height: 720 }] : [{ relation: '>=', width: videoUploads.restriction.videoRestriction.minWidth, height: videoUploads.restriction.videoRestriction.minHeight }], fileSize: videoUploads.restriction.videoRestriction.fileSize * 1024, materialType: 'video' }, num: 100 })
                    setMaterialConfig({
                        ...materialConfig,
                        type: videoUploads.name,
                        max: 1,
                        index: 99999,
                        adcreativeTemplateId: creativeTemplateId
                    })
                    setTimeout(() => {
                        setSelectVideoVisible(true)
                    }, 100)
                }}>批量添加视频素材</Button>}
                {imgUploads && Object.keys(imgUploads)?.length > 0 && <Button type="link" onClick={() => {
                    setSelectCloudData({ defaultParams: { sizeQueries: [{ relation: '=', width: imgUploads.restriction.imageRestriction.width, height: imgUploads.restriction.imageRestriction.height }], fileSize: imgUploads.restriction.imageRestriction.fileSize * 1024, materialType: 'image' }, num: 100 })
                    setMaterialConfig({
                        ...materialConfig,
                        type: imgUploads.name,
                        max: (imgUploads.name === 'image_list' || imgUploads.name === 'element_story') ? imgUploads.arrayProperty.maxNumber : 1,
                        index: 99999,
                        adcreativeTemplateId: creativeTemplateId
                    })
                    setTimeout(() => {
                        setSelectVideoVisible(true)
                    }, 100)
                }}>批量添加图片素材</Button>}
            </> : <>
                <InputNumber size="small" min={1} style={{ width: 50 }} value={mCount} max={15} onChange={(e) => setMCount(e || 0)} />
                <Button type="link" onClick={() => {
                    setSelectCloudData({
                        num: 100,
                        defaultParams: {
                            materialType: 'image',
                            sizeQueries: [
                                { relation: '=', width: 800, height: 800 },
                                { relation: '=', width: 1280, height: 720 },
                                { relation: '=', width: 720, height: 1280 },
                                { relation: '=', width: 960, height: 334 },
                                { relation: '=', width: 480, height: 320 },
                            ],
                            fileSize: 400 * 1024
                        }
                    })
                    setMaterialConfig({
                        ...materialConfig,
                        type: 'image',
                        max: 100,
                        index: 20000,
                        adcreativeTemplateId: creativeTemplateId,
                        isGroup: false
                    })
                    setTimeout(() => {
                        setSelectVideoVisible(true)
                    }, 100)
                }}>批量添加图片素材</Button>
                <Button type="link" onClick={() => {
                    setSelectCloudData({
                        num: 100,
                        defaultParams: {
                            materialType: 'video',
                            sizeQueries: [
                                { relation: '>=', width: 1280, height: 720 },
                                { relation: '>=', width: 720, height: 1280 }
                            ],
                            fileSize: 512000 * 1024
                        }
                    })
                    setMaterialConfig({
                        ...materialConfig,
                        type: 'video',
                        max: 100,
                        index: 20000,
                        adcreativeTemplateId: creativeTemplateId,
                        isGroup: false
                    })
                    setTimeout(() => {
                        setSelectVideoVisible(true)
                    }, 100)
                }}>批量添加视频素材</Button>
            </>}
            {(dynamicGroup && dynamicGroup?.length > 1) && <Popconfirm
                title="是否清空?"
                onConfirm={() => form.setFieldsValue({ dynamicGroup: [undefined] })}
                okText="是"
                cancelText="否"
            >
                <Button type="link" danger>一键清空</Button>
            </Popconfirm>}
        </Space>}
        open={visible}
        onCancel={onClose}
        footer={null}
        width={900}
        className={`modalResetCss`}
        bodyStyle={{ padding: '0 0 40px', position: 'relative', borderRadius: '0 0 8px 8px' }}
        maskClosable={false}
    >
        <Form
            form={form}
            name="newMaterial"
            labelAlign='left'
            layout="vertical"
            colon={false}
            style={{ backgroundColor: '#f1f4fc', maxHeight: 650, overflow: 'hidden', overflowY: 'auto', padding: 10, borderRadius: '0 0 8px 8px' }}
            scrollToFirstError={{
                behavior: 'smooth',
                block: 'center'
            }}
            onFinishFailed={({ errorFields }) => {
                message.error(errorFields?.[0]?.errors?.[0])
            }}
            onFinish={handleOk}
            initialValues={{
                dynamicGroup: [undefined]
            }}
        >
            <Card className="cardResetCss" style={{ marginBottom: 10 }}>
                <Form.Item name="mediaType" label={<strong>创意组分配规则</strong>} style={{ marginBottom: 0 }} rules={[{ required: true, message: '请选择创意组分配规则!' }]}>
                    <New1Radio
                        data={[{ label: '全广告复用', value: 0 }, { label: '平均分配到广告', value: 1 }, { label: '顺序分配到广告', value: 2 }, { label: '账号下平均分配到广告', value: 3 }]}
                        onChange={(e) => {
                            if (e === 2 && dynamicGroup?.length > adLength) {
                                form.setFieldsValue({ dynamicGroup: dynamicGroup.slice(0, adLength) })
                            }
                        }}
                    />
                </Form.Item>
            </Card>
            <Form.List name="dynamicGroup">
                {(fields, { add, remove }) => (<>
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10 }}>
                        {fields.map((field, num) => (<Card
                            title={<Space>
                                <strong style={{ fontSize: 18 }}>创意组{num + 1}</strong>
                                {deliveryMode === 'DELIVERY_MODE_COMPONENT' && <>
                                    <Dropdown
                                        menu={{
                                            items: [
                                                {
                                                    label: '添加视频',
                                                    key: 'addVideo',
                                                    onClick: () => {
                                                        setSelectCloudData({
                                                            num: 15 - (dynamicGroup?.[num]?.['list']?.length || 0),
                                                            defaultParams: {
                                                                materialType: 'video',
                                                                sizeQueries: [
                                                                    { relation: '>=', width: 1280, height: 720 },
                                                                    { relation: '>=', width: 720, height: 1280 }
                                                                ],
                                                                fileSize: 512000 * 1024
                                                            }
                                                        })
                                                        setMaterialConfig({
                                                            ...materialConfig,
                                                            type: 'video',
                                                            max: 15 - (dynamicGroup?.[num]?.['list']?.length || 0),
                                                            index: num,
                                                            adcreativeTemplateId: creativeTemplateId,
                                                            isGroup: false
                                                        })
                                                        setTimeout(() => {
                                                            setSelectVideoVisible(true)
                                                        }, 100)
                                                    }
                                                },
                                                {
                                                    label: '添加图片',
                                                    key: 'addImg',
                                                    onClick: () => {
                                                        setSelectCloudData({
                                                            num: 15 - (dynamicGroup?.[num]?.['list']?.length || 0),
                                                            defaultParams: {
                                                                materialType: 'image',
                                                                sizeQueries: [
                                                                    { relation: '=', width: 800, height: 800 },
                                                                    { relation: '=', width: 1280, height: 720 },
                                                                    { relation: '=', width: 720, height: 1280 },
                                                                    { relation: '=', width: 960, height: 334 },
                                                                    { relation: '=', width: 480, height: 320 },
                                                                ],
                                                                fileSize: 400 * 1024
                                                            }
                                                        })
                                                        setMaterialConfig({
                                                            ...materialConfig,
                                                            type: 'image',
                                                            max: 15 - (dynamicGroup?.[num]?.['list']?.length || 0),
                                                            index: num,
                                                            adcreativeTemplateId: creativeTemplateId,
                                                            isGroup: false
                                                        })
                                                        setTimeout(() => {
                                                            setSelectVideoVisible(true)
                                                        }, 100)
                                                    }
                                                }
                                            ]
                                        }}
                                        placement="bottomLeft"
                                        arrow
                                    >
                                        <Button type="primary">添加图片/视频</Button>
                                    </Dropdown>
                                    <Dropdown
                                        menu={{
                                            items: [
                                                { label: '1:1 六图', key: '1', disabled: dynamicGroup?.[num]?.['list']?.length >= 15, onClick: () => { selectGroupImg(num, 6) } },
                                                { label: '1:1 三图', key: '2', disabled: dynamicGroup?.[num]?.['list']?.length >= 15, onClick: () => { selectGroupImg(num, 3) } },
                                                { label: '1:1 四图', key: '3', disabled: dynamicGroup?.[num]?.['list']?.length >= 15, onClick: () => { selectGroupImg(num, 4) } },
                                            ]
                                        }}
                                        placement="bottomLeft"
                                        arrow
                                    >
                                        <Button type="primary">上传组图</Button>
                                    </Dropdown>
                                </>}
                            </Space>}
                            className="cardResetCss"
                            key={field.key}
                            style={{ width: deliveryMode === 'DELIVERY_MODE_CUSTOMIZE' ? ([641, 642, 643, 720, 721, 722, 1529, 618].includes(creativeTemplateId) || dynamicGroup?.length === 1) ? '100%' : 'calc(50% - 5px)' : '100%' }}
                            extra={fields?.length > 1 && <DeleteOutlined className={styles.clear} onClick={() => remove(field.name)} style={{ color: 'red' }} />}
                        >
                            {deliveryMode === 'DELIVERY_MODE_CUSTOMIZE' ? <Space size={30} style={{ width: '100%' }} className={styles.space}>
                                {Object.keys(materialData)?.map(key => {
                                    let m = materialData[key]
                                    let children = m.children

                                    return Object.keys(children).map(k => {
                                        let item = children[k]
                                        if (k === 'short_video1' || k === 'video_id') {
                                            return <Form.Item
                                                {...field}
                                                label={<strong>{item.description}</strong>}
                                                rules={[{ required: true, message: '请选择素材!' }]}
                                                name={[field.name, item.name]}
                                                key={k}
                                            >
                                                <div className={`${styles.box} ${styles.video}`} style={{ width: 300, height: 160 }} onClick={() => {
                                                    setSelectCloudData({
                                                        num: 1,
                                                        defaultParams: {
                                                            materialType: 'video',
                                                            sizeQueries: creativeTemplateId === 1708 ? [{ relation: '=', width: 1280, height: 720 }] : [{ relation: item.restriction.videoRestriction.minWidth > item.restriction.videoRestriction.minHeight ? '=' : '>=', width: item.restriction.videoRestriction.minWidth, height: item.restriction.videoRestriction.minHeight }],
                                                            fileSize: item.restriction.videoRestriction.fileSize * 1024
                                                        }
                                                    })
                                                    setMaterialConfig({
                                                        ...materialConfig,
                                                        type: item.name,
                                                        max: 1,
                                                        index: num,
                                                        adcreativeTemplateId: creativeTemplateId
                                                    })
                                                    setTimeout(() => {
                                                        setSelectVideoVisible(true)
                                                    }, 100)
                                                }}>
                                                    <div className={styles.p}>
                                                        {dynamicGroup?.length > 0 && dynamicGroup[num] && Object.keys(dynamicGroup[num])?.includes(item.name) ? <VideoNews keyFrameImageUrl={dynamicGroup[num][item.name]['keyFrameImageUrl']} src={dynamicGroup[num][item.name]['url']} style={{ display: 'block', width: 'auto', margin: 0, height: '100%' }} maskImgStyle={{ position: 'absolute', top: '50%', left: '50%', width: 40, height: 40, transform: 'translate(-50%, -50%)', zIndex: 10 }} /> : <>
                                                            <span>{`推荐尺寸（${creativeTemplateId === 1708 ? 1280 : item.restriction.videoRestriction.minWidth} x ${creativeTemplateId === 1708 ? 720 : item.restriction.videoRestriction.minHeight}）`}</span>
                                                            <span>{`${item.restriction.videoRestriction.fileFormat?.map((str: any) => str?.replace('MEDIA_TYPE_', ''))};< ${item.restriction.videoRestriction.fileSize / 1024}M;时长 ≥ ${item.restriction.videoRestriction.minDuration}s,≤ ${item.restriction.videoRestriction.maxDuration}s,必须带有声音`}</span>
                                                        </>}
                                                    </div>
                                                </div>
                                            </Form.Item>
                                        }
                                        if (item.name === 'image_id' || item.name === 'cover_id') {
                                            return <Form.Item
                                                {...field}
                                                label={<strong>{item.description}</strong>}
                                                rules={[{ required: true, message: '请选择素材!' }]}
                                                name={[field.name, item.name]}
                                                key={key}
                                            >
                                                <Space align="end">
                                                    <div className={`${styles.box} ${styles.image}`} style={{ width: 300, height: 160 }} onClick={() => {
                                                        setSelectCloudData({
                                                            num: 1,
                                                            defaultParams: {
                                                                materialType: 'image',
                                                                sizeQueries: [{ relation: '=', width: item.restriction.imageRestriction.width, height: item.restriction.imageRestriction.height }],
                                                                fileSize: item.restriction.imageRestriction.fileSize * 1024
                                                            }
                                                        })
                                                        setMaterialConfig({
                                                            ...materialConfig,
                                                            type: item.name,
                                                            max: 1,
                                                            index: num,
                                                            adcreativeTemplateId: creativeTemplateId
                                                        })
                                                        setTimeout(() => {
                                                            setSelectVideoVisible(true)
                                                        }, 100)
                                                    }}>
                                                        <p>
                                                            {dynamicGroup?.length > 0 && dynamicGroup[num] && Object.keys(dynamicGroup[num])?.includes(item.name) ? <img src={dynamicGroup[num][item.name]['url']} /> : <>
                                                                <span>{`推荐尺寸（${item.restriction.imageRestriction.width} x ${item.restriction.imageRestriction.height}）`}</span>
                                                                <span>{`${item.restriction.imageRestriction.fileFormat?.map((str: any) => str?.replace('IMAGE_TYPE_', ''))}；小于 ${item.restriction.imageRestriction.fileSize}KB`}</span>
                                                            </>}
                                                        </p>
                                                    </div>
                                                    {videoUploads && Object.keys(videoUploads)?.length > 0 && <div style={{ width: 32 }}>
                                                        {dynamicGroup?.length > 0 && dynamicGroup[num] && ((Object.keys(dynamicGroup[num])?.includes('video_id') && dynamicGroup[num]['video_id']['materialType'] === 0) || (Object.keys(dynamicGroup[num])?.includes('short_video1') && dynamicGroup[num]['short_video1']['materialType'] === 0)) && <VideoFrameSelect onChange={(e) => setFrame(e, num, item.name)} url={dynamicGroup[num]?.['video_id']?.['url'] || dynamicGroup[num]?.['short_video1']?.['url']} />}
                                                    </div>}
                                                </Space>
                                            </Form.Item>
                                        }

                                        if (item.name === 'list') {
                                            let name = ''
                                            let imageData: any = {}
                                            if (key === 'image_list') {
                                                imageData = item.children.image_id
                                                name = 'image_list';
                                            } else if (key === 'element_story') {
                                                imageData = item.children.image
                                                name = 'element_story'
                                            }
                                            return <Form.Item
                                                {...field}
                                                label={<strong>{imageData.description}</strong>}
                                                rules={[
                                                    { required: true, type: 'array', len: minNumber || item.arrayProperty.maxNumber, message: '素材数量不对!' },
                                                    { required: true, message: '请选择素材!' },
                                                ]}
                                                name={[field.name, name]}
                                                key={key}
                                            >
                                                <div className={`${styles.box} ${item.arrayProperty.maxNumber >= 3 ? styles.image_list : styles.imageMater}`} style={item.arrayProperty.maxNumber >= 3 ? { flexFlow: 'row', width: '100%', gap: 2 } : {}} onClick={() => {
                                                    setSelectCloudData({
                                                        num: item.arrayProperty.maxNumber,
                                                        defaultParams: {
                                                            materialType: 'image',
                                                            sizeQueries: [{ relation: '=', width: imageData.restriction.imageRestriction.width, height: imageData.restriction.imageRestriction.height }],
                                                            fileSize: imageData.restriction.imageRestriction.fileSize * 1024
                                                        }
                                                    })
                                                    setMaterialConfig({
                                                        ...materialConfig,
                                                        type: name,
                                                        max: item.arrayProperty.maxNumber,
                                                        index: num,
                                                        adcreativeTemplateId: creativeTemplateId
                                                    })
                                                    setTimeout(() => {
                                                        setSelectVideoVisible(true)
                                                    }, 100)
                                                }}>
                                                    {Array(item.arrayProperty.maxNumber).fill('').map((arr, index1) => {
                                                        return <p key={index1} style={item.arrayProperty.maxNumber >= 3 ? { width: 130, height: 130 } : { justifyContent: 'center' }}>
                                                            {dynamicGroup?.length > 0 && dynamicGroup[num] && Object.keys(dynamicGroup[num])?.includes(name) && dynamicGroup[num][name][index1] ? <img src={dynamicGroup[num][name][index1]['url']} /> : <>
                                                                <span>{`推荐尺寸（${imageData.restriction.imageRestriction.width} x ${imageData.restriction.imageRestriction.height}）`}</span>
                                                                <span>{`${imageData.restriction.imageRestriction.fileFormat?.map((str: any) => str?.replace('IMAGE_TYPE_', ''))}；小于 ${imageData.restriction.imageRestriction.fileSize}KB`}</span>
                                                            </>}
                                                        </p>
                                                    })}
                                                </div>
                                            </Form.Item>
                                        }

                                        return null
                                    })
                                })}
                            </Space> : <Form.Item
                                {...field}
                                label={<strong>创意素材</strong>}
                                rules={[{ required: true, message: '请选择素材!' }]}
                                name={[field.name, 'list']}
                            >
                                <div className={`${styles.box} ${styles.video}`} style={{ width: '100%', height: 'auto', backgroundColor: 'rgb(247, 249, 252)' }}>
                                    {dynamicGroup?.length && dynamicGroup?.[num]?.['list']?.length > 0 ? <div className={styles.boxList}>
                                        <div className={styles.boxList_title}>
                                            <span>上传素材 <span style={{ marginLeft: 5, color: '#999', fontWeight: 'normal' }}>已选：{getComponentCount(dynamicGroup?.[num]?.['list'])}</span></span>
                                            <a onClick={() => {
                                                let newDynamicGroup = dynamicGroup?.map((item: any, i: number) => {
                                                    if (i === num) {
                                                        return { list: [] }
                                                    }
                                                    return item
                                                })
                                                form.setFieldsValue({ dynamicGroup: newDynamicGroup })
                                            }}>清空</a>
                                        </div>
                                        <div className={styles.boxList_body}>
                                            {dynamicGroup?.[num]?.['list']?.map((item: any, index: number) => {
                                                if (Array.isArray(item)) {
                                                    let length = item.length
                                                    return <div className={styles.boxList_body_item} key={index}>
                                                        <div className={styles.tag}>{length}图</div>
                                                        <div className={styles.content}>
                                                            {item.map((l, i) => <img src={l?.url} key={i} style={{ width: length === 6 ? 33.3 : 49.9 }} />)}
                                                        </div>
                                                        <div className={styles.clear} onClick={() => { clearTem(num, index) }}><CloseCircleOutlined /></div>
                                                    </div>
                                                } else if (item?.url?.includes('mp4') || item?.keyFrameImageUrl) {
                                                    return <div className={styles.boxList_body_item} key={index}>
                                                        <div className={styles.content}>
                                                            <VideoNews src={item?.url} keyFrameImageUrl={item?.keyFrameImageUrl} style={{ width: 100, height: 100 }} maskBodyStyle={{ backgroundColor: "rgba(242, 246, 254, 0.1)" }} />
                                                        </div>
                                                        <div className={styles.clear} onClick={() => { clearTem(num, index) }}><CloseCircleOutlined /></div>
                                                    </div>
                                                } else {
                                                    return <div className={styles.boxList_body_item} key={index}>
                                                        <div className={styles.content}><img src={item?.url} /></div>
                                                        <div className={styles.clear} onClick={() => { clearTem(num, index) }}><CloseCircleOutlined /></div>
                                                    </div>
                                                }

                                            })}
                                        </div>
                                    </div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无素材内容，可通过上方添加" />}
                                </div>
                            </Form.Item>}
                        </Card>))}
                    </div>

                    {!(mediaType === 2 && dynamicGroup?.length >= adLength) && <Form.Item style={{ marginBottom: 0, marginTop: 10 }}>
                        <Button type="dashed" style={{ color: '#1890ff' }} onClick={() => add()} block icon={<PlusOutlined />}>添加创意组</Button>
                    </Form.Item>}
                </>)}
            </Form.List>
            <Form.Item className="submit_pull">
                <Space>
                    <Button onClick={onClose}>取消</Button>
                    <Button type="primary" htmlType="submit" className="modalResetCss">
                        确定
                    </Button>
                </Space>
            </Form.Item>
        </Form>

        {/* 选择素材 */}
        {(selectVideoVisible && selectCloudData) && <SelectCloudNew
            {...selectCloudData}
            accountCreateLogs={accountCreateLogs}
            visible={selectVideoVisible}
            isGroup={materialConfig?.isGroup}
            sliderImgContent={materialConfig.index === 99999 ? undefined :
                materialConfig.type === 'element_story' ? (dynamicGroup[materialConfig.index] && Object.keys(dynamicGroup[materialConfig.index])?.includes('element_story')) ? dynamicGroup[materialConfig.index]['element_story']?.map((item: any) => ({ oss_url: item.url, id: item.id, materialType: item?.materialType, material_type: selectCloudData.defaultParams.materialType, })) : undefined :
                    materialConfig.type === 'image_list' ? (dynamicGroup[materialConfig.index] && Object.keys(dynamicGroup[materialConfig.index])?.includes('image_list')) ? dynamicGroup[materialConfig.index]['image_list']?.map((item: any) => ({ oss_url: item.url, id: item.id, materialType: item?.materialType, material_type: selectCloudData.defaultParams.materialType, })) : undefined :
                        (dynamicGroup[materialConfig.index] && Object.keys(dynamicGroup[materialConfig.index])?.includes(materialConfig.type)) ? [{ oss_url: dynamicGroup[materialConfig.index][materialConfig.type]['url'], id: dynamicGroup[materialConfig.index][materialConfig.type]['id'], material_type: selectCloudData.defaultParams.materialType, materialType: dynamicGroup[materialConfig.index][materialConfig.type]?.['materialType'], key_frame_image_url: dynamicGroup[materialConfig.index][materialConfig.type]?.['keyFrameImageUrl'] }] : undefined
            }
            onClose={() => {
                setSelectVideoVisible(false)
                setSelectCloudData(undefined)
            }}
            onChange={(content: any) => {
                if (content.length > 0) {
                    if (deliveryMode === 'DELIVERY_MODE_COMPONENT') { // 组件化创意
                        if (materialConfig.index === 20000) {
                            if (materialConfig.isGroup) {

                            } else {
                                const aContent = content.map((m: any) => {
                                    if (selectCloudData?.defaultParams?.materialType === 'video' && m?.materialType === 1) {
                                        return { id: m?.id, url: m?.oss_url, materialType: m?.materialType || 0, keyFrameImageUrl: m?.key_frame_image_url, accountId: m?.account_id }
                                    }
                                    return { id: m?.id, url: m?.oss_url, materialType: m?.materialType || 0, accountId: m?.account_id }
                                })
                                let newDynamicGroup = dynamicGroup?.map((item: any) => {
                                    let oldList = item?.list || []
                                    if (oldList.length < mCount) {
                                        let diffCount = mCount - oldList.length
                                        let cLength = aContent.length
                                        oldList = oldList.concat(aContent.splice(0, cLength > diffCount ? diffCount : cLength))
                                    }
                                    return { list: oldList }
                                })
                                if (aContent.length) {
                                    let newSc = chunkArray1(aContent, mCount)
                                    let newList: any[] = newSc.map((item: any) => {
                                        return { list: item }
                                    })
                                    newDynamicGroup = (newDynamicGroup || []).concat(newList)
                                }
                                form.setFieldsValue({ dynamicGroup: newDynamicGroup })
                            }
                        } else {
                            let newDynamicGroup = dynamicGroup?.map((item: any, index: number) => {
                                if (materialConfig.index === index) {
                                    let oldList = item?.list || []
                                    if (materialConfig.isGroup) {
                                        oldList = oldList.concat([content.map((m: any) => {
                                            if (selectCloudData?.defaultParams?.materialType === 'video' && m?.materialType === 1) {
                                                return { id: m?.id, url: m?.oss_url, materialType: m?.materialType || 0, keyFrameImageUrl: m?.key_frame_image_url, accountId: m?.account_id }
                                            }
                                            return { id: m?.id, url: m?.oss_url, materialType: m?.materialType || 0, accountId: m?.account_id }
                                        })])
                                        return { list: oldList }
                                    } else {
                                        oldList = oldList.concat(content.map((m: any) => {
                                            if (selectCloudData?.defaultParams?.materialType === 'video' && m?.materialType === 1) {
                                                return { id: m?.id, url: m?.oss_url, materialType: m?.materialType || 0, keyFrameImageUrl: m?.key_frame_image_url, accountId: m?.account_id }
                                            }
                                            return { id: m?.id, url: m?.oss_url, materialType: m?.materialType || 0, accountId: m?.account_id }
                                        }))
                                        return { list: oldList }
                                    }
                                }
                                return item
                            })
                            form.setFieldsValue({ dynamicGroup: newDynamicGroup })
                        }
                    } else { // 自定义创意
                        if (materialConfig.index === 99999) {
                            if (materialConfig.type === 'image_list' || materialConfig.type === 'element_story') {
                                let urls = content?.map((item: any) => ({ id: item?.id, url: item?.oss_url, materialType: item?.materialType || 0, accountId: item?.account_id }))
                                let max = materialConfig.max
                                let materialsNew = dynamicGroup.map((item: any) => {
                                    let newItem = item || {}
                                    // 判断是否有字段，是否设置了值
                                    if (Object.keys(newItem).includes(materialConfig.type) && newItem[materialConfig.type]) {
                                        if (max > newItem[materialConfig.type].length && urls.length > 0) {
                                            let difference = max - newItem[materialConfig.type].length
                                            let material: any[] = []
                                            if (urls.length >= difference) {
                                                material = urls.splice(0, difference)
                                            } else {
                                                material = urls.splice(0, urls.length)
                                            }
                                            newItem[materialConfig.type] = [...newItem[materialConfig.type], ...material]
                                            return newItem
                                        } else {
                                            return newItem
                                        }
                                    } else {
                                        if (urls.length >= max) {
                                            let material = urls.splice(0, max)
                                            return { ...newItem, [materialConfig.type]: material }
                                        } else if (urls.length > 0) {
                                            let material = urls.splice(0, urls.length)
                                            return { ...newItem, [materialConfig.type]: material }
                                        } else {
                                            return newItem
                                        }
                                    }
                                })
                                if (urls.length > 0) {
                                    let data = Array(Math.ceil(urls.length / max)).fill(undefined).map(item => {
                                        if (urls.length >= max) {
                                            let material = urls.splice(0, max)
                                            return { [materialConfig.type]: material }
                                        } else {
                                            let material = urls.splice(0, urls.length)
                                            return { [materialConfig.type]: material }
                                        }
                                    })
                                    materialsNew = [...materialsNew, ...data]
                                }
                                console.log('materialsNew-->', materialsNew)
                                form.setFieldsValue({ dynamicGroup: materialsNew })
                            } else {
                                let newMaterials = content?.map((item: any) => {
                                    if (["short_video1", 'video_id'].includes(materialConfig.type) && mLength === 2) {
                                        return { [materialConfig.type]: { url: item?.oss_url, keyFrameImageUrl: item.key_frame_image_url, id: item?.id, materialType: item?.materialType || 0, accountId: item?.account_id }, cover_id: { url: item?.materialType === 1 ? item?.key_frame_image_url : getVideoImgUrl(item?.oss_url), id: null, materialType: item?.materialType || 0, accountId: item?.account_id } }
                                    }
                                    return { [materialConfig.type]: { url: item?.oss_url, id: item?.id, materialType: item?.materialType || 0, accountId: item?.account_id } }
                                })
                                if (newMaterials.length > 0) {
                                    if (dynamicGroup?.every((item: any) => !item)) { // 没设置过
                                        form.setFieldsValue({ dynamicGroup: newMaterials })
                                    } else { // 设置过
                                        let materialsNew = dynamicGroup.map((item: any) => {
                                            let newItem = item || {}
                                            if (Object.keys(newItem).includes(materialConfig.type) && newItem[materialConfig.type]) {
                                                return item
                                            } else {
                                                if (newMaterials.length > 0) {
                                                    let material = newMaterials.splice(0, 1)
                                                    return { ...newItem, ...material[0] }
                                                } else {
                                                    return item
                                                }
                                            }
                                        })
                                        if (newMaterials.length > 0) {
                                            materialsNew = [...materialsNew, ...newMaterials]
                                        }
                                        form.setFieldsValue({ dynamicGroup: materialsNew })
                                    }
                                }
                            }
                        } else {
                            let newDynamicGroup = dynamicGroup?.map((item: any, index: number) => {
                                if (materialConfig.index === index) {
                                    if (materialConfig.type === 'image_list' || materialConfig.type === 'element_story') {
                                        if (item) {
                                            item[materialConfig.type] = content?.map((item: any) => ({ id: item?.id, url: item?.oss_url, materialType: item?.materialType || 0, accountId: item?.account_id }))
                                            return { ...item }
                                        } else {
                                            return { [materialConfig.type]: content?.map((item: any) => ({ id: item?.id, url: item?.oss_url, materialType: item?.materialType || 0, accountId: item?.account_id })) }
                                        }
                                    } else {
                                        if (item) {
                                            let d: any = { id: content[0]?.id, url: content[0]?.oss_url, materialType: content[0]?.materialType || 0, accountId: content[0]?.account_id }
                                            if (["short_video1", 'video_id'].includes(materialConfig.type) && content[0]?.materialType === 1) {
                                                d.keyFrameImageUrl = content[0]?.key_frame_image_url
                                            }
                                            item[materialConfig.type] = d
                                            return { ...item }
                                        } else {
                                            if (["short_video1", 'video_id'].includes(materialConfig.type) && mLength === 2) {
                                                return { [materialConfig.type]: { id: content[0]?.id, url: content[0]?.oss_url, keyFrameImageUrl: content[0]?.key_frame_image_url, materialType: content[0]?.materialType || 0, accountId: content[0]?.account_id }, cover_id: { id: null, url: content[0]?.materialType === 1 ? content[0]?.key_frame_image_url : getVideoImgUrl(content[0]?.oss_url), materialType: content[0]?.materialType || 0, accountId: content[0]?.account_id } }
                                            }
                                            return { [materialConfig.type]: { id: content[0]?.id, url: content[0]?.oss_url, materialType: content[0]?.materialType || 0, accountId: content[0]?.account_id } }
                                        }
                                    }
                                }
                                return item
                            })
                            form.setFieldsValue({ dynamicGroup: newDynamicGroup })
                        }
                    }
                }
                setSelectVideoVisible(false)
                setSelectCloudData(undefined)
            }}
        />}
    </Modal>
}

export default React.memo(AddMaterial)