import { Button, Card, Form, Modal, Radio, Space, Spin, Switch, Typography, message } from "antd"
import React, { useContext, useEffect, useState } from "react"
import '../../index.less'
import { getCreativeDetailsApi, getCreativeTemplateListApi } from "@/services/adqV3/global";
import { useAjax } from "@/Hook/useAjax";
import { DELIVERY_MODE_ENUM, pageSpecFieldConVert } from "../../const";
import New2Radio from "@/pages/launchSystemV3/components/New2Radio";
import New1Radio from "@/pages/launchSystemV3/components/New1Radio";
import { outAdcreativeTemplateIdFun } from "@/pages/launchSystemNew/launchManage/localAd/adenum";
import { DispatchAddelivery } from "..";
import { processData, randomString } from "@/utils/utils";
import CreativeTemplateContent from "./creativeTemplateContent";
import CreativeConversionAssistant from "./creativeConversionAssistant";
import CreativeTemplateSetup from "./creativeTemplateSetup";
const { Text } = Typography;

export const DispatchDynamic = React.createContext<PULLIN.DynamicReactContent | null>(null);

interface Props {
    putInType?: 'NOVEL' | 'GAME'
    value?: any,
    visible?: boolean
    creativeTemplateStyle?: string,
    onClose?: () => void
    onChange?: (value: any) => void
}

/**
 * 创意新建
 * @param param0 
 * @returns 
 */
const NewDynamic: React.FC<Props> = ({ putInType, value: newValue, visible, onClose, onChange, creativeTemplateStyle: oldCreativeTemplateStyle }) => {

    /**********************************/
    const { addelivery, setMaterialData, setTextData } = useContext(DispatchAddelivery)!;
    const { adgroups } = addelivery
    const [form] = Form.useForm();
    const creativeTemplateStyle = Form.useWatch('creativeTemplateStyle', form);
    const deliveryMode = Form.useWatch('deliveryMode', form);
    const dynamicCreativeSwitch = Form.useWatch('dynamicCreativeSwitch', form);

    const [marketingGoalTypeList, setMarketingGoalTypeList] = useState<PULLIN.DataType[]>([])
    const [adcreativeTemplateList, setAdcreativeTemplateList] = useState<PULLIN.AdcreativeTemplateList[]>([])
    const [creativeComponents, setCreativeComponents] = useState<any>({})
    const [isUpdate, setIsUpdate] = useState<boolean>(false)
    const { marketingGoal, marketingAssetOuterSpec, marketingCarrierType, siteSet, sceneSpec, automaticSiteEnabled, marketingSubGoal, deliveryMethod } = adgroups

    const [newMaterialData, setNewMaterialData] = useState<any>({}) // 素材数据
    const [newTextData, setNewTextData] = useState<any>({})
    const [value, setValue] = useState<any>(newValue)
    const [isJustEntered, setIsJustEntered] = useState<boolean>(true)

    const getCreativeTemplateList = useAjax((params) => getCreativeTemplateListApi(params))
    const getCreativeDetails = useAjax((params) => getCreativeDetailsApi(params))
    /**********************************/

    useEffect(() => {
        if (deliveryMode === 'DELIVERY_MODE_CUSTOMIZE' || dynamicCreativeSwitch) { // 自定义创意
            let params: any = {
                marketingGoal,
                marketingTargetType: marketingAssetOuterSpec.marketingTargetType,
                marketingCarrierType,
                siteSet,
                wechatSceneSpecPosition: sceneSpec?.wechatPosition || [],
                taskType: putInType
            }
            if (putInType === 'GAME') {
                params.marketingSubGoal = marketingSubGoal
            }
            getCreativeTemplateList.run(params).then((res: any) => {
                let newArr: any = []
                let newData: any[] = []
                // 过滤掉相同的和即将下线的
                if (!res) {
                    return
                }
                if (automaticSiteEnabled) {
                    delete res?.SITE_SET_WECHAT
                }
                let creativeTemplateStyle = ''
                Object.values(res)?.forEach(arr => {
                    newData.push(arr)
                    if (Array.isArray(arr)) {
                        arr?.forEach((item: any) => {
                            let adcreativeTemplateListStructAdpermit = item?.adcreativeTemplateListStructAdpermit
                            if (adcreativeTemplateListStructAdpermit) {
                                creativeTemplateStyle += adcreativeTemplateListStructAdpermit?.creativeTemplateStyle
                                let creativeTemplateId = adcreativeTemplateListStructAdpermit.creativeTemplateId
                                if (newArr.length > 0) {//假如已存在ID，需要过滤相同
                                    if (outAdcreativeTemplateIdFun(creativeTemplateId) && newArr.every((i: { creativeTemplateId: any }) => i.creativeTemplateId !== creativeTemplateId)) {//不重复的添加
                                        newArr.push(adcreativeTemplateListStructAdpermit)
                                    }
                                } else {//不存在ID直接过滤掉即将下线的
                                    if (outAdcreativeTemplateIdFun(creativeTemplateId)) {
                                        newArr.push(adcreativeTemplateListStructAdpermit)
                                    }
                                }
                            }
                        })
                    }
                })

                /*****暂时排除激励和banner有问题******/
                if (!siteSet || siteSet.some((i: string) => i === 'SITE_SET_MOMENTS')) {
                    newArr = newArr.filter((item: { creativeTemplateId: number }) => ![2107, 2109].includes(item.creativeTemplateId))
                }
                /*****暂时排除出框形态 视频合约广告******/
                if (!siteSet || siteSet.some((i: string) => i === 'SITE_SET_WECHAT')) {
                    newArr = newArr.filter((item: { creativeTemplateId: number }) => item.creativeTemplateId !== 1945)
                }
                newArr = newArr.filter((item: { creativeTemplateId: number }) => ![713, 727, 951, 965].includes(item.creativeTemplateId))

                let newArr1: any[] = []
                let newArr2: any[] = []
                newArr?.forEach((arr: { creativeTemplateId: any, creativeTemplateAppellation: string, creativeSampleImage: string, isGeneral?: boolean }) => {
                    let arr2 = { label: arr.creativeTemplateAppellation, value: arr.creativeTemplateId, img: arr.creativeSampleImage, ...arr }
                    if (newData.every((item: any[]) => item.find(i => i?.adcreativeTemplateListStructAdpermit?.creativeTemplateId === arr.creativeTemplateId))) {
                        newArr1.push({ ...arr2, isGeneral: true })
                    } else {
                        newArr2.push(arr2)
                    }
                })

                setAdcreativeTemplateList([...newArr1, ...newArr2])
                let goalTypeData: PULLIN.DataType[] = []
                if (creativeTemplateStyle.includes('视频')) {
                    goalTypeData.push({ label: '视频', value: 'video' })
                }
                if (creativeTemplateStyle.includes('图片') || creativeTemplateStyle.includes('其他')) {
                    goalTypeData.push({ label: '图片', value: 'image' })
                }
                setMarketingGoalTypeList(goalTypeData)

                if (value && Object.keys(value).length > 0) {
                    getTemplate(value.creativeTemplateId)
                    form.setFieldsValue({ creativeTemplateStyle: oldCreativeTemplateStyle === '视频' ? 'video' : 'image' })
                } else {
                    form.setFieldsValue({ creativeTemplateStyle: creativeTemplateStyle.includes('视频') ? 'video' : 'image' })
                }
            })
        } else if (deliveryMode === 'DELIVERY_MODE_COMPONENT') {  // 组件化创意
            getTemplate()
        }
    }, [deliveryMode, dynamicCreativeSwitch, marketingGoal, marketingAssetOuterSpec, marketingCarrierType, siteSet, sceneSpec?.wechatPosition, value, automaticSiteEnabled, putInType])

    useEffect(() => {
        if (!(value && Object.keys(value).length > 0) && adcreativeTemplateList?.length > 0 && marketingGoalTypeList?.length > 0) {
            typeChange(marketingGoalTypeList.some(item => item.value === 'video') ? '视频' : '图片')
        }
    }, [value, adcreativeTemplateList, marketingGoalTypeList])

    const typeChange = (creativeTemplateStyle: string, isAntTemplateId?: boolean) => {
        if (creativeTemplateStyle && adcreativeTemplateList?.length > 0) {
            let adcreativeTemplateIdArr = adcreativeTemplateList?.filter(item => item.creativeTemplateStyle === creativeTemplateStyle)
            if (adcreativeTemplateIdArr?.length > 0) {
                let creativeTemplateId = adcreativeTemplateIdArr[0].creativeTemplateId
                getTemplate(creativeTemplateId, isAntTemplateId)
                form.setFieldsValue({ creativeTemplateId })
            }
        }
    }

    // 获取创意形式详情
    const getTemplate = (id?: any, isAntTemplateId?: boolean) => {
        // CAMPAIGN_TYPE_NORMAL
        if (marketingAssetOuterSpec?.marketingTargetType && deliveryMode) {
            let params: any = {
                marketingGoal,
                marketingTargetType: marketingAssetOuterSpec.marketingTargetType,
                marketingCarrierType,
                deliveryMode,
                creativeTemplateId: id,
                wechatSceneSpecPosition: sceneSpec?.wechatPosition,
                dynamicCreativeType: (deliveryMode === 'DELIVERY_MODE_COMPONENT' && !dynamicCreativeSwitch) ? 'DYNAMIC_CREATIVE_TYPE_PROGRAM' : 'DYNAMIC_CREATIVE_TYPE_COMMON'
            }
            if (automaticSiteEnabled) {
                params.automaticSiteEnabled = automaticSiteEnabled
            } else {
                params.siteSet = siteSet
                // if (siteSet?.length > 0) {
                //     params.siteSet = (siteSet as any).filter((item: string) => item !== 'SITE_SET_SEARCH_SCENE')
                // }
            }
            params.taskType = putInType
            if (putInType === 'GAME') {
                params.marketingSubGoal = marketingSubGoal
            }
            // params.useNewVersion = true
            getCreativeDetails.run(params).then(res => {
                if (res?.adcreativeTemplateStructAdpermits?.length > 0) {
                    let adcreativeTemplateStructAdpermits = res?.adcreativeTemplateStructAdpermits[0]
                    templateChange(adcreativeTemplateStructAdpermits, isAntTemplateId)
                } else {
                    message.error({
                        content: '当前所选营销目的，广告版位下不支持该创意形式。或者无此创意形式权限，请联系相关人员开通白名单',
                        duration: 10
                    })
                    setCreativeComponents({})
                }
            })
        }
    }

    //每次选中创意设置该展示的界面
    const templateChange = (adcreativeTemplateStructAdpermits: any, isAntTemplateId?: boolean) => {
        let creativeComponents = adcreativeTemplateStructAdpermits?.creativeComponents || []
        let creativeTemplateId = adcreativeTemplateStructAdpermits?.creativeTemplateId
        let creativeTemplateAppellation = adcreativeTemplateStructAdpermits?.creativeTemplateAppellation
        let result = processData(creativeComponents);
        const noBarrage = [713, 714, 722, 618, 1529, 2109, 972, 2107]
        const siteSetBarrage = [
            "SITE_SET_KANDIAN",
            "SITE_SET_MOBILE_UNION",
            "SITE_SET_QQ_MUSIC_GAME",
            "SITE_SET_SEARCH_SCENE",
            "SITE_SET_TENCENT_NEWS",
            "SITE_SET_TENCENT_VIDEO"
        ]
        if (!result.barrage && (
            automaticSiteEnabled ?
                deliveryMode === 'DELIVERY_MODE_COMPONENT' ?
                    creativeTemplateId ? !noBarrage.includes(creativeTemplateId) : true :
                    !noBarrage.includes(creativeTemplateId) :
                siteSet.some((item: string) => siteSetBarrage.includes(item)) ?
                    !noBarrage.includes(creativeTemplateId) :
                    false
        )) {
            result.barrage = { required: false }
        }
        console.log('result-->', result);
        setCreativeComponents(result)

        let newMaterialData: { [x: string]: any } = {};
        let newTextData: { [x: string]: any } = {};

        Object.keys(result).forEach(key => {
            let data = result[key]
            if ((key === 'image_list' || key === 'short_video' || key === 'video' || key === 'image' || key === 'element_story') && data.required) {
                newMaterialData[key] = data
            } else if (key === 'title' || (data.required && key === 'description')) {
                newTextData[key] = data
            }
        })

        setNewMaterialData(newMaterialData)
        setNewTextData(newTextData)
        if (!(value && Object.keys(value).length > 0) || isAntTemplateId) {
            let values: any = {
                dynamicCreativeName: creativeTemplateAppellation ? '自定义创意' + '_' + creativeTemplateAppellation + '_' + localStorage.getItem('userId') + '_' + randomString(true, 3, 5) : '动态创意' + '_' + localStorage.getItem('userId') + '_' + randomString(true, 3, 5),
                pageSpec: marketingAssetOuterSpec?.marketingTargetType === 'MARKETING_TARGET_TYPE_WECHAT_MINI_GAME' ? [{
                    pageType: "PAGE_TYPE_WECHAT_MINI_GAME"
                }] : [{
                    pageType: 'PAGE_TYPE_OFFICIAL',
                    // overrideCanvasHeadOption: 'OPTION_CREATIVE_OVERRIDE_CANVAS'
                }],
                brand: undefined
            }
            Object.keys(result).forEach(key => {
                switch (key) {
                    case 'brand':
                        let brand = result[key]
                        let page_type = brand.children.page_type
                        let typeList = ["PAGE_TYPE_WECHAT_OFFICIAL_ACCOUNT_DETAIL", "PAGE_TYPE_H5_PROFILE", "PAGE_TYPE_NOT_USED", "PAGE_TYPE_WECHAT_CHANNELS_PROFILE"]
                        let enumeration = (page_type.enumProperty.enumeration as { value: string, description: string }[]).filter((item: { value: string; }) => typeList.includes(item.value))
                        values.jumpInfo = {
                            pageType: enumeration[0]?.value
                        }
                        break
                    case 'text_link':// 朋友圈文字链
                        let textLink = result[key]
                        let linkNameType = textLink?.children?.link_name_type
                        let linkNameEnumeration = (linkNameType?.enumProperty?.enumeration as { value: string, description: string }[]).map(item => ({ label: item.description, value: item.value }))
                        values.textLink = {
                            value: {
                                linkNameType: linkNameEnumeration?.[0]?.value,
                                jumpInfo: {
                                    // pageType: marketingAssetOuterSpec?.marketingTargetType === 'MARKETING_TARGET_TYPE_WECHAT_MINI_GAME' ? "PAGE_TYPE_WECHAT_MINI_GAME" : 'PAGE_TYPE_WECHAT_CANVAS'
                                    pageType: marketingAssetOuterSpec?.marketingTargetType === 'MARKETING_TARGET_TYPE_WECHAT_MINI_GAME' ? "PAGE_TYPE_WECHAT_MINI_GAME" : 'PAGE_TYPE_OFFICIAL'
                                }
                            }
                        }
                        values.textLinkShow = true
                        break
                    case 'action_button':
                        let actionButton = result[key]
                        let buttonText = actionButton.children.button_text
                        let butttonTextEnumeration = (buttonText.enumProperty.enumeration as { value: string }[]).map(item => ({ label: item.value, value: item.value }))
                        values.actionButton = {
                            value: {
                                buttonText: butttonTextEnumeration?.[0]?.value,
                                jumpInfo: {
                                    pageType: marketingAssetOuterSpec?.marketingTargetType === 'MARKETING_TARGET_TYPE_WECHAT_MINI_GAME' ? "PAGE_TYPE_WECHAT_MINI_GAME" : 'PAGE_TYPE_OFFICIAL'
                                }
                            }
                        }
                        values.actionButtonShow = true
                        break
                    case 'floating_zone':
                        let floatingZone = result[key]
                        if (floatingZone?.required) {
                            let floatingZoneData: any = {
                                value: {
                                    floatingZoneSwitch: false,
                                    floatingZoneType: 'FLOATING_ZONE_TYPE_IMAGE_TEXT',
                                    floatingZoneButtonText: '了解更多'
                                }
                            }
                            if (floatingZone?.children?.floating_zone_image_id && floatingZone?.children?.floating_zone_button_text) {
                                floatingZoneData.value.floatingZoneButtonText = floatingZone.children.floating_zone_button_text?.enumProperty?.enumeration[0]?.value
                            }
                            floatingZoneData.value.floatingZoneSwitch = true
                            values.floatingZone = floatingZoneData
                        }
                        break
                }
            })
            if ([1707, 1708].includes(creativeTemplateId)) {
                delete values?.actionButtonShow
                values.cardType = ['not']
            }
            form.setFieldsValue(values)
            setTimeout(() => { setIsUpdate(true) }, 50)
        }
    }

    const handleOk = (values: any) => {
        const {
            creativeTemplateStyle,
            brand,
            jumpInfo,
            pageSpec,
            textLinkShow,
            textLink,
            actionButtonShow,
            cardType,
            actionButton,
            showDataShow,
            showData,
            floatingZone,
            creativeLabelDTOS,
            creativeBarrageDTOS,
            creativeFirstReplyDTO,
            ...surplusValues
        } = values

        let dynamicValues: any = {
            ...surplusValues,
        }

        let creativeComponents: any = {}

        let actionButtonJumpInfo = {
            pageType: undefined
        }
        if (pageSpec?.length > 0) {
            let { pageType } = pageSpec?.[0]
            actionButtonJumpInfo.pageType = pageType
            creativeComponents.mainJumpInfo = pageSpec.map((item: { pageType: string, overrideCanvasHeadOption: string, }) => {
                let pageSpec: { [x: string]: any } = {}
                if (item.pageType === "PAGE_TYPE_WECHAT_CANVAS") { // 原生推广页
                    pageSpec = {
                        [pageSpecFieldConVert[item.pageType as keyof typeof pageSpecFieldConVert]]: {
                            pageId: null,
                            overrideCanvasHeadOption: item.overrideCanvasHeadOption
                        }
                    }
                } else if (item.pageType === "PAGE_TYPE_OFFICIAL") {  // 官方落地页
                    pageSpec = {
                        [pageSpecFieldConVert[item.pageType as keyof typeof pageSpecFieldConVert]]: {
                            pageId: null
                        }
                    }
                } else if (item.pageType === "PAGE_TYPE_WECHAT_MINI_PROGRAM") { // 微信小程序
                    pageSpec = {
                        [pageSpecFieldConVert[item.pageType as keyof typeof pageSpecFieldConVert]]: {
                            miniProgramId: null,
                            miniProgramPath: null
                        }
                    }
                }
                return {
                    value: {
                        pageType: item.pageType,
                        pageSpec
                    }
                }
            })
        }

        // 品牌形象
        if (jumpInfo) {
            let pageType = jumpInfo.pageType
            let value: { [x: string]: any } = {
                jumpInfo
            }
            if (['PAGE_TYPE_H5_PROFILE'].includes(pageType)) {
                value['profileId'] = brand
            } else if (["PAGE_TYPE_NOT_USED"].includes(pageType)) {
                let [brandName, brandImageId] = brand.split('_')
                value['brandName'] = brandName
                value['brandImageId'] = brandImageId
            } else {
                value['brandName'] = null
                value['brandImageId'] = null
            }

            let pageSpecData: any = {}

            if (pageType === 'PAGE_TYPE_H5_PROFILE') {
                pageSpecData[pageSpecFieldConVert[pageType as keyof typeof pageSpecFieldConVert]] = {
                    pageId: null
                }
            } else if (pageType === 'PAGE_TYPE_H5') {
                pageSpecData[pageSpecFieldConVert[pageType as keyof typeof pageSpecFieldConVert]] = {
                    pageUrl: null,
                    mpaH5WildcardUrl: null
                }
            } else if (pageType === 'PAGE_TYPE_WECHAT_OFFICIAL_ACCOUNT_DETAIL') {
                pageSpecData[pageSpecFieldConVert[pageType as keyof typeof pageSpecFieldConVert]] = {
                    appId: null
                }
            }
            value.jumpInfo = {
                ...value.jumpInfo,
                pageSpec: pageSpecData
            }
            let length = pageSpec.length
            creativeComponents.brand = Array(length).fill('').map(() => ({ value }))
        }
        // 朋友圈文字链
        if (textLinkShow) {
            creativeComponents.textLink = [textLink]
        }

        // 行动按钮
        if (actionButton && Object.keys(actionButton).length > 0) {
            let newActionButton = [actionButton]
            if (!actionButton.value?.jumpInfo) {
                newActionButton = [{
                    ...actionButton,
                    value: {
                        ...actionButton.value,
                        jumpInfo: actionButtonJumpInfo
                    }
                }]
            }
            creativeComponents.actionButton = newActionButton
        }

        // 标签
        if (creativeLabelDTOS?.length) {
            creativeComponents.creativeLabelDTOS = creativeLabelDTOS
        }

        // 弹幕
        if (creativeBarrageDTOS?.length) {
            creativeComponents.creativeBarrageDTOS = creativeBarrageDTOS
        }

        // 首评
        if (creativeFirstReplyDTO?.text) {
            creativeComponents.creativeFirstReplyDTO = creativeFirstReplyDTO
        }

        // 数据外显
        if (showDataShow) {
            creativeComponents.showData = [showData]
        }
        if (floatingZone?.value?.floatingZoneSwitch) {
            let value = floatingZone.value
            let { image, ...val } = value
            if (val.floatingZoneType === "FLOATING_ZONE_TYPE_SINGLE_IMAGE") {
                delete image?.floatingZoneImageId
                delete image?.floatingZoneImageUrl
                delete image?.floatingZoneImageMaterialType
            } else {
                delete image?.floatingZoneSingleImageId
                delete image?.floatingZoneSingleImageUrl
                delete image?.floatingZoneSingleImageMaterialType
            }
            creativeComponents.floatingZoneComponent = {
                ...val,
                ...image
            }
        }
        dynamicValues.creativeComponents = creativeComponents
        setMaterialData(newMaterialData)
        setTextData(newTextData)
        onChange?.(dynamicValues)
    }

    useEffect(() => {
        // 只允许进入一次 锁住
        if (!isJustEntered) {
            return
        }
        setIsJustEntered(() => false)
        // if (value && Object.keys(value).length > 0 && adcreativeTemplateList?.length > 0 && ((value.deliveryMode === 'DELIVERY_MODE_CUSTOMIZE' && oldCreativeTemplateStyle) || value.deliveryMode === 'DELIVERY_MODE_COMPONENT')) {
        if (value && Object.keys(value).length > 0 && ((value.deliveryMode === 'DELIVERY_MODE_CUSTOMIZE' && oldCreativeTemplateStyle) || value.deliveryMode === 'DELIVERY_MODE_COMPONENT')) {
            const {
                creativeComponents: {
                    brand,
                    textLink,
                    actionButton,
                    showData,
                    mainJumpInfo,
                    floatingZoneComponent,
                    creativeLabelDTOS,
                    creativeBarrageDTOS,
                    creativeFirstReplyDTO
                },
                ...surplusValues
            } = JSON.parse(JSON.stringify(value))
            let dynamicValues: any = {
                ...surplusValues,
                creativeLabelDTOS,
                creativeBarrageDTOS,
                creativeFirstReplyDTO
            }
            // if (value.deliveryMode === 'DELIVERY_MODE_CUSTOMIZE') {
            //     getTemplate(value.creativeTemplateId)
            //     dynamicValues.creativeTemplateStyle = oldCreativeTemplateStyle === '视频' ? 'video' : 'image'
            // }
            // else getTemplate()
            // 卡片广告
            let isCardDynamic = dynamicValues?.creativeTemplateId && [1707, 1708].includes(dynamicValues.creativeTemplateId)
            let cardType: string[] = []

            // 529 闪屏视频 没有品牌 要单独处理
            if (brand && brand?.length > 0) {
                let { jumpInfo, brandName, brandImageId, profileId } = brand[0].value
                if (jumpInfo) {
                    let { pageType } = jumpInfo
                    dynamicValues.jumpInfo = { pageType }
                }
                if (brandName && brandImageId) {
                    dynamicValues.brand = brandName + '_' + brandImageId
                } else if (profileId) {
                    dynamicValues.brand = profileId
                }
            }

            if (mainJumpInfo && mainJumpInfo?.length > 0) {
                dynamicValues.pageSpec = mainJumpInfo.map((item: any) => {
                    let { pageSpec, pageType } = item.value
                    let key = Object.keys(pageSpec)[0]
                    let pageSpecValue = pageSpec[key]
                    return { ...pageSpecValue, pageType }
                })
            }

            // 文字链
            if (textLink && textLink?.length > 0) {
                dynamicValues = {
                    ...dynamicValues,
                    textLinkShow: true,
                    textLink: textLink[0]
                }
            }

            // 行动按钮
            if (actionButton && actionButton?.length > 0) {
                dynamicValues = {
                    ...dynamicValues,
                    actionButtonShow: true,
                    actionButton: actionButton[0]
                }
                if (isCardDynamic) {
                    cardType.push('action_button')
                    delete dynamicValues.actionButtonShow
                }
            }

            // 数据外显
            if (showData && showData?.length > 0) {
                dynamicValues = {
                    ...dynamicValues,
                    showDataShow: true,
                    showData: showData[0]
                }
            }

            if (floatingZoneComponent && Object.keys(floatingZoneComponent).length) {
                const {
                    floatingZoneImageId,
                    floatingZoneImageUrl,
                    floatingZoneImageMaterialType,
                    floatingZoneSingleImageId,
                    floatingZoneSingleImageUrl,
                    floatingZoneSingleImageMaterialType,
                    ...val
                } = floatingZoneComponent
                dynamicValues = {
                    ...dynamicValues,
                    floatingZone: {
                        value: {
                            image: {
                                floatingZoneImageId,
                                floatingZoneImageUrl,
                                floatingZoneImageMaterialType,
                                floatingZoneSingleImageId,
                                floatingZoneSingleImageUrl,
                                floatingZoneSingleImageMaterialType,
                            },
                            ...val
                        }
                    }
                }
            }

            if (cardType.length === 0 && isCardDynamic) {
                cardType = ['not']
            }
            dynamicValues.cardType = cardType
            form.setFieldsValue({ ...dynamicValues })
        } else {
            form.setFieldsValue({
                deliveryMode: 'DELIVERY_MODE_COMPONENT',
                configuredStatus: 'AD_STATUS_NORMAL'
            })
        }
    }, [value, oldCreativeTemplateStyle])

    return <Modal
        title={<strong style={{ fontSize: 20 }}>创意基本信息</strong>}
        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="newDynamic"
            labelAlign='left'
            layout="vertical"
            colon={false}
            style={{ backgroundColor: '#f1f4fc', maxHeight: 650, overflow: 'hidden', overflowY: 'auto', padding: '0 10px 10px', borderRadius: '0 0 8px 8px' }}
            scrollToFirstError={{
                behavior: 'smooth',
                block: 'center'
            }}
            onFinishFailed={({ errorFields }) => {
                message.error(errorFields?.[0]?.errors?.[0])
            }}
            onFinish={handleOk}
            initialValues={{
                // deliveryMode: 'DELIVERY_MODE_CUSTOMIZE',
                // configuredStatus: 'AD_STATUS_NORMAL'
            }}
        >
            <Spin spinning={getCreativeTemplateList.loading || getCreativeDetails.loading}>
                <DispatchDynamic.Provider value={{ form, adgroups, value, creativeComponents, setCreativeComponents, isUpdate, setIsUpdate }}>
                    <Space direction="vertical" style={{ width: '100%' }}>
                        {/* 创意形式 */}
                        <Card
                            title={<strong style={{ fontSize: 18 }}>创意形式</strong>}
                            className="cardResetCss"
                            extra={deliveryMode === 'DELIVERY_MODE_COMPONENT' ? <Space>
                                <Form.Item name="dynamicCreativeSwitch" valuePropName="checked" className="formItemResetCss" style={{ marginBottom: 0 }}>
                                    <Switch size="small" onChange={(checked) => {
                                        if (checked) {
                                            setTimeout(() => { setIsUpdate(true) }, 50)
                                            setValue(undefined)
                                        }
                                    }} />
                                </Form.Item>
                                <div style={{ paddingTop: 2 }}><Text style={{ fontSize: 12 }}>指定创意形式</Text></div>
                            </Space> : null}
                        >
                            <Form.Item name="deliveryMode" label={<strong>投放模式</strong>} rules={[{ required: true, message: '请选择投放模式!' }]}>
                                <Radio.Group onChange={() => {
                                    setTimeout(() => { setIsUpdate(true) }, 50)
                                    setValue(undefined)
                                }}>
                                    {Object.keys(DELIVERY_MODE_ENUM).map(key => <Radio value={key} disabled={deliveryMethod === 'SMART' ? key === 'DELIVERY_MODE_CUSTOMIZE' : false} key={key}>{DELIVERY_MODE_ENUM[key as keyof typeof DELIVERY_MODE_ENUM]}</Radio>)}
                                </Radio.Group>
                            </Form.Item>
                            {(deliveryMode === 'DELIVERY_MODE_CUSTOMIZE' || dynamicCreativeSwitch) && <>
                                <Form.Item name="creativeTemplateStyle" label={<strong>创意形式类型</strong>} rules={[{ required: true, message: '请选择营销目的!' }]}>
                                    <New1Radio data={marketingGoalTypeList} onChange={(e) => { typeChange(e === 'video' ? '视频' : '图片', true); }} />
                                </Form.Item>
                                <Form.Item name="creativeTemplateId" label={<strong>创意形式</strong>} rules={[{ required: true, message: '请选择营销目的!' }]}>
                                    <New2Radio
                                        data={adcreativeTemplateList.filter(item => creativeTemplateStyle === 'video' ? item.creativeTemplateStyle === '视频' : (item.creativeTemplateStyle === '图片' || item.creativeTemplateStyle === '其他'))}
                                        onChange={(id) => { getTemplate(id, true); }}
                                    />
                                </Form.Item>
                            </>}
                        </Card>

                        {Object.keys(creativeComponents).length > 0 && <>
                            {/* 创意内容 */}
                            <CreativeTemplateContent automaticSiteEnabled={automaticSiteEnabled} putInType={putInType} />
                            {/* 营销组件 */}
                            <CreativeConversionAssistant automaticSiteEnabled={automaticSiteEnabled} putInType={putInType} />
                            {/* 创意设置 */}
                            <CreativeTemplateSetup />
                        </>}
                    </Space>
                </DispatchDynamic.Provider>
            </Spin>
            <Form.Item className="submit_pull">
                <Space>
                    <Button onClick={onClose}>取消</Button>
                    <Button type="primary" htmlType="submit" className="modalResetCss">
                        确定
                    </Button>
                </Space>
            </Form.Item>
        </Form>
    </Modal>
}

export default React.memo(NewDynamic)