import React, { useCallback, useEffect, useMemo, useState } from 'react'
import { Modal, Form, Input, Divider, Select, Radio, Switch, Spin, List, Checkbox, Space, Button, message, Image, Empty, Tooltip, Popconfirm } from 'antd'
import styles from './index.less'
import { useAjax } from '@/Hook/useAjax'
import { getText, get_adcreative_template, get_adcreative_template_list, get_tools_video_capture } from '@/services/launchAdq/global'
import { AdcreativeTemplate, AdcreativeTemplateList } from '@/services/launchAdq'
import { mySet } from '@/utils/arrFn'
import SelectCloud from '@/pages/launchSystemNew/components/selectCloud'
import { useModel } from 'umi'
import { ModalConfig } from '../../ad';
import { outAdcreativeTemplateIdFun } from '../../../localAd/adenum'
import { CreateAdProps } from '@/services/launchAdq/createAd'
import { createSysAdcreative } from '@/services/launchAdq/creative'
import { creativeConfig, overrideCanvasHeadOptionEnum } from './config'
import BrandImage from './brandImage'
import HeadNickJump from './headNickJump'
import moment from 'moment'
import { getVideoImgUrl, txtLength } from '@/utils/utils'
import VideoNews from '@/pages/launchSystemNew/components/newsModal/videoNews'
import VideoFrame from '@/pages/launchSystemNew/components/videoFrame'
import { QuestionCircleOutlined } from '@ant-design/icons'
interface Props {
    queryForm: Partial<CreateAdProps>,
    title?: string,
    visible: boolean,
    PupFn: (arg: ModalConfig) => void,
    callback: (params: any) => void,
    confirmLoading?: boolean,
    type?: 'add' | 'look' | 'edit',//新增，查看，编辑
    dataInfo?: any
}

/**创意模板*/
function CreativePup(props: Props) {
    let { visible, confirmLoading, PupFn, callback, type, dataInfo, queryForm } = props
    const { currentUser }: any = useModel('@@initialState', model => ({ currentUser: model.initialState?.currentUser }))
    let [template_checked, settemplate_checked] = useState<boolean>(dataInfo?.isTemplate || false)
    let { promotedObjectType, sysAdgroup } = queryForm
    let { siteSet } = sysAdgroup
    const { init } = useModel('useLaunchAdq.useBdMediaPup')
    let arg = type === 'look' ? { footer: null } : {}
    // 请求
    const getAdcreativeTemplate = useAjax((params) => get_adcreative_template(params))
    const getAdcreativeTemplateList = useAjax((params) => get_adcreative_template_list(params))
    const getTextLsit = useAjax((params) => getText(params))
    const addSysAdgroup = useAjax((params) => createSysAdcreative(params))
    const getVideoCapture = useAjax((params) => get_tools_video_capture(params))
    // 变量
    const [adcreative_template, set_adcreative_template] = useState<AdcreativeTemplate>()
    const [adcreative_template_list, set_adcreative_template_list] = useState<AdcreativeTemplateList[]>([])
    const [selectImgVisible, set_selectImgVisible] = useState(false)
    const [selectVideoVisible, set_selectVideoVisible] = useState(false)
    const [videoImgsVisbile, set_videoImgsVisbile] = useState(false)
    const [descriptionShow, setdescriptionshow] = useState(false)
    const [endPageDescShow, setendPageDescnshow] = useState(false)
    const [isShowSc, set_isShowSc] = useState(false)//是否展示素材选项
    const [infoSet, set_infoSet] = useState(false)//回填设置已完成
    const [isShowXd, setIsShowXd] = useState(false)
    const [videoImgs, set_videoImgs] = useState<{//视频封面图设置
        activeUrl: string,//选中的视频封面图地址
        preview: boolean,//是否开启图片点击预览
        urlList: any[],//生成的视频封面列表
    }>({
        activeUrl: '',
        preview: false,
        urlList: [
            'https://test-adq-media.oss-cn-hangzhou.aliyuncs.com/image/21D8D51AD98C4FF8BF41F1C2D28EA39F.jpg',
            'https://test-adq-media.oss-cn-hangzhou.aliyuncs.com/image/80DBE1AB3EDE4E85ABAE5F1670D9FED0.jpg',
            'https://test-adq-media.oss-cn-hangzhou.aliyuncs.com/image/BCB2DAB86BDB4549BCB8E493C4F29E82.jpg',
            'https://test-adq-media.oss-cn-hangzhou.aliyuncs.com/image/545A4C2A5B874C82A9D1C0C063624AE5.jpg'
        ]
    })
    const [titleShow, settitleshow] = useState(false)
    const [form] = Form.useForm();
    const [pupState, setPupState] = useState({
        kp_show: false,
        xd_show: false,
        sj_show: false,
        bq_show: false,
        sp_show: false
    })
    const [imgMaterialConfig, setImgMaterialConfig] = useState<{
        adcreativeTemplateId?: number,
        type: string,
        cloudSize: { relation: string, width: number, height: number }[],
        list: any[],
        max: number
    }>({
        type: '',//类型
        cloudSize: [],//素材搜索条件
        list: [],//素材
        max: 1,//素材数量
    })//图片素材配置
    const [imgListMaterialConfig, setImgListMaterialConfig] = useState<{
        adcreativeTemplateId?: number,
        type: string,
        cloudSize: { relation: string, width: number, height: number }[],
        list: any[],
        max: number
    }>({
        type: '',//类型
        cloudSize: [],//素材搜索条件
        list: [],//素材
        max: 1,//素材数量
    })//图片素材配置
    const [videoMaterialConfig, setVideoMaterialConfig] = useState<{
        adcreativeTemplateId?: number,
        type: string,
        cloudSize: { relation: string, width: number, height: number }[],
        list: any[],
        max: number
    }>({
        type: '',//类型
        cloudSize: [],//素材搜索条件
        list: [],//素材
        max: 1,//素材数量
    })//图片素材配置
    const [templateStyleS, setTemplateStyleS] = useState<string>('')
    const [imgType, setimgType] = useState<'single' | 'many'>('single')
    const [conversionList, setConversionList] = useState<any>(null)
    let pageType = Form.useWatch('pageType', form)
    let adcreativeTemplateId = Form.useWatch('adcreativeTemplateId', form)
    let actionBtn = Form.useWatch('actionBtn', form)
    // let siteSet = Form.useWatch('siteSet', form)
    let overrideCanvasHeadOption = Form.useWatch('overrideCanvasHeadOption', form)
    let adcreativeElementsType = Form.useWatch('adcreativeElementsType', form)
    let dataShow = Form.useWatch('dataShow', form)
    let conversionDataType = Form.useWatch('conversionDataType', form)
    let titles = Form.useWatch('title', form)
    let description = Form.useWatch('description', form)
    let videoOver = Form.useWatch('videoOver', form)
    let endPageDesc = Form.useWatch('endPageDesc', form)
    let linkPageType = Form.useWatch('linkPageType', form)
    let short_video1 = Form.useWatch('short_video1', form)
    let video = Form.useWatch('video', form)

    // 确定事件
    const handleOk = useCallback((newAd?:boolean) => {
        form.validateFields().then(values => {
            console.log('values=>1', values)
            let newValues = JSON.parse(JSON.stringify(values))
            for (let key in newValues) {
                switch (key) {
                    case 'image'://图素材
                        newValues.adcreativeElements = {
                            ...newValues.adcreativeElements,
                            imageUrl: imgMaterialConfig?.list[0]?.url,
                        }
                        delete newValues[key]
                        break;
                    case 'video'://视频素材
                        newValues.adcreativeElements = {
                            ...newValues.adcreativeElements,
                            videoUrl: videoMaterialConfig?.list[0]?.url,
                        }
                        delete newValues[key]
                        break;
                    case 'image_list'://图素材
                        newValues.adcreativeElements = {
                            ...newValues.adcreativeElements,
                            imageUrlList: imgListMaterialConfig.list?.map(item => item.url),
                            description: newValues.description,
                        }
                        delete newValues[key]
                        break;
                    case 'element_story'://图素材
                        newValues.adcreativeElements = {
                            ...newValues.adcreativeElements,
                            elementStory: imgMaterialConfig.list?.map(item => ({ imageUrl: item.url })),
                            description: newValues.description,
                        }
                        delete newValues[key]
                        break;
                    case 'short_video1'://视频素材
                        newValues.adcreativeElements = {
                            ...newValues.adcreativeElements,
                            shortVideoStruct: {
                                shortVideo1Url: videoMaterialConfig?.list[0]?.url
                            },
                            description: newValues.description,
                        }
                        delete newValues[key]
                        break;
                    case 'description'://文案
                        newValues.adcreativeElements = { ...newValues.adcreativeElements, description: newValues.description }
                        break;
                    case 'title'://文案
                        newValues.adcreativeElements = { ...newValues.adcreativeElements, title: newValues.title }
                        break;
                    case 'endPageType'://视频结束l类型
                        newValues.adcreativeElements = { ...newValues.adcreativeElements, endPage: { ...newValues.adcreativeElements.endPage, endPageType: newValues.endPageType } }
                        delete newValues[key]
                        break;
                    case 'endPageDesc'://视频结束文案
                        newValues.adcreativeElements = { ...newValues.adcreativeElements, endPage: { ...newValues.adcreativeElements.endPage, endPageDesc: newValues.endPageDesc } }
                        delete newValues[key]
                        break;
                    case 'buttonText'://特殊行动按钮
                        newValues.adcreativeElements = { ...newValues.adcreativeElements, buttonText: newValues.buttonText }
                        delete newValues[key]
                        break;
                    case 'brand'://品牌形象
                        newValues.adcreativeElements = {
                            ...newValues.adcreativeElements, brand: {
                                brandName: newValues.brand.split('_')[0],
                                brandImgUrl: newValues.brand.split('_')[1]
                            }
                        }
                        break;
                    case 'profile':
                        newValues.adcreativeElements = {
                            ...newValues.adcreativeElements, brand: {
                                brandName: newValues.profile.split('_')[0],
                                brandImgUrl: newValues.profile.split('_')[1]
                            }
                        }
                        newValues.profile = {
                            headImageUrl: newValues.profile.split('_')[1],
                            profileName: newValues.profile.split('_')[0],
                            description: newValues.profile.split('_')[2]
                        }
                        break
                    case 'pageUrl'://跳转落地页
                        newValues.linkPageSpec = {
                            ...newValues.linkPageSpec,
                            pageUrl: newValues.pageUrl
                        }
                        delete newValues.pageUrl
                        break;
                    case 'miniProgramId':
                        newValues.linkPageSpec = {
                            ...newValues.linkPageSpec,
                            miniProgramSpec: {
                                miniProgramId: newValues.miniProgramId,
                                miniProgramPath: newValues.miniProgramPath
                            }
                        }
                        delete newValues.miniProgramId
                        delete newValues.miniProgramPath
                        break;
                }
            }
            if (!newValues.adcreativeElements) {
                newValues.adcreativeElements = {}
            }
            //假如不存在promotedObjectType
            if (!newValues?.promotedObjectType) {
                newValues['promotedObjectType'] = queryForm.promotedObjectType
            }
            // 假如不存在siteSet
            if (!newValues?.siteSet) {
                newValues['siteSet'] = queryForm.sysAdgroup.siteSet
            }
            delete newValues.description //删除外层文案
            delete newValues.title //删除外层文案
            delete newValues.adcreativeElementsType //删除创意形式
            delete newValues.dataShow //删除数据开关
            delete newValues.actionBtn //删除行动开关
            delete newValues.brand //品牌形象
            // 假如使用了落地页顶部素材替换外部素材
            if (newValues.overrideCanvasHeadOption === 'OPTION_CANVAS_OVERRIDE_CREATIVE') {
                console.log(adcreative_template?.adcreativeElements)
                adcreative_template?.adcreativeElements?.filter(item => item.required && item.name === 'image_list' || item.name === 'short_video1' || item.name === 'video' || item.name === 'image').forEach(item => {
                    switch (item.name) {
                        case 'image'://图素材
                            newValues.adcreativeElements = {
                                ...newValues.adcreativeElements,
                                imageUrl: '',
                            }
                            break;
                        case 'video'://视频素材
                            newValues.adcreativeElements = {
                                ...newValues.adcreativeElements,
                                videoUrl: '',
                            }
                            break;
                        case 'image_list'://图素材
                            newValues.adcreativeElements = {
                                ...newValues.adcreativeElements,
                                imageUrlList: [],
                            }
                            break;
                        case 'short_video1'://视频素材
                            newValues.adcreativeElements = {
                                ...newValues.adcreativeElements,
                                shortVideoStruct: {
                                    shortVideo1Url: ''
                                },
                            }
                            break;
                    }
                })
            }
            console.log('newValues=>2', newValues)
            if(newAd){
                console.log("将模板变成新创意")
                delete newValues.id
                delete newValues.sysAdcreativeId
            }
            newValues['isTemplate'] = template_checked
            // // 开启存为模板开关执行
            callback(newValues)
        })
    }, [form, imgMaterialConfig, imgListMaterialConfig, videoMaterialConfig, queryForm, template_checked, adcreative_template, isShowSc])
    // 获取创意形式列表
    useEffect(() => {
        if (siteSet?.length > 0 && promotedObjectType) {
            getAdcreativeTemplateList.run({
                siteSet,
                promotedObjectType,
                campaignType: 'CAMPAIGN_TYPE_NORMAL',
            }).then(res => {
                let newArr: any = []
                let newData: any[] = []
                // 过滤掉相同的和即将下线的
                if (!res) {
                    return
                }
                let templateStyle = ''
                Object.values(res)?.forEach((arr: any) => {
                    newData.push(arr)
                    Array.isArray(arr) && arr?.forEach((item: any) => {
                        templateStyle += item?.adcreativeTemplateStyle
                        if (newArr.length > 0) {//假如已存在ID，需要过滤相同
                            if (outAdcreativeTemplateIdFun(item.adcreativeTemplateId) && newArr.every((i: { adcreativeTemplateId: any }) => i.adcreativeTemplateId !== item.adcreativeTemplateId)) {//不重复的添加
                                newArr.push(item)
                            }
                        } else {//不存在ID直接过滤掉即将下线的
                            if (outAdcreativeTemplateIdFun(item.adcreativeTemplateId)) {
                                newArr.push(item)
                            }
                        }
                    })
                })
                setTemplateStyleS(templateStyle)
                /*****暂时排除激励和banner有问题******/
                if (siteSet.some((i: string) => i === 'SITE_SET_MOMENTS')) {
                    newArr = newArr.filter((item: { adcreativeTemplateId: number }) => item.adcreativeTemplateId !== 910 && item.adcreativeTemplateId !== 925 && item.adcreativeTemplateId !== 2107 && item.adcreativeTemplateId !== 2109)
                }
                /*****暂时排除出框形态 视频合约广告******/
                if (siteSet.some((i: string) => i === 'SITE_SET_WECHAT')) {
                    newArr = newArr.filter((item: { adcreativeTemplateId: number }) => item.adcreativeTemplateId !== 1945)
                }
                let newArr1: any[] = []
                let newArr2: any[] = []
                newArr?.forEach((arr: { adcreativeTemplateId: any, isGeneral?: boolean }) => {
                    if (newData.every((item: { adcreativeTemplateId: any }[]) => item.find(i => i.adcreativeTemplateId === arr.adcreativeTemplateId))) {
                        newArr1.push({ ...arr, isGeneral: true })
                    } else {
                        newArr2.push(arr)
                    }
                })
                set_adcreative_template_list([...newArr1, ...newArr2])
            })
        }
    }, [siteSet, promotedObjectType])
    // 获取创意形式详情
    const getTemplate = (id: any, ok?: any) => {
        // CAMPAIGN_TYPE_NORMAL
        if (siteSet?.length > 0 && promotedObjectType && id) {
            if (id) {
                getAdcreativeTemplate.run({
                    siteSet,
                    promotedObjectType,
                    adcreativeTemplateId: id
                }).then(res => {
                    if (res?.length > 0) {
                        form.setFieldsValue({ adcreativeName: res[0]?.adcreativeTemplateAppellation + '_' + moment().format('YYYYMMDDhhmmss') + '_' + currentUser.userId })
                        let adcreativeElements = res[0]?.adcreativeElements || []
                        let elementStoryData = adcreativeElements?.find((item: { name: string }) => item.name === 'element_story')
                        if (elementStoryData) {
                            let imgageData = adcreativeElements?.find((item: { name: string }) => item.name === 'image')
                            if (imgageData) {
                                elementStoryData.restriction = imgageData.restriction
                                adcreativeElements.splice(adcreativeElements?.findIndex((item: { name: string }) => item.name === 'image'), 1)
                            }
                        }
                        if (id === 2106) {
                            res[0].adcreativeElements = res[0]?.adcreativeElements?.map((item: any) => {
                                if (item.name === "description") {
                                    return { ...item, name: 'title', title: item['description'] }
                                }
                                return item
                            })
                        }
                        set_adcreative_template(res[0])
                        if (siteSet?.some((name: string) => name === 'SITE_SET_MOMENTS')) {
                            let id = res[0].adcreativeTemplateId
                            set_isShowSc(!!creativeConfig[id])//判定当前创意是否需要展示替换素材选项
                            if (creativeConfig[id] && !ok) {//假如不等于回填元素的ID
                                form.setFieldsValue({ overrideCanvasHeadOption: creativeConfig[id].overrideCanvasHeadOption[0] })
                            }
                        }
                        templateChange(res[0], ok)
                    }
                })
            }
        }
    }
    // 获取对应落地页按钮
    const pageTypeList = useMemo(() => {
        if (adcreativeTemplateId) {
            let arr: any = adcreative_template?.landingPageConfig?.supportPageTypeList
            return arr
        }
        return null

    }, [adcreativeTemplateId, adcreative_template])
    // 获取对应行动按钮数据
    const linkNameList = useMemo(() => {
        if (pageType) {
            let arr = (pageTypeList?.filter((item: { pageType: any; }) => item.pageType === pageType)[0] as any)?.supportLinkNameType?.list
            return arr
        }
        return null
    }, [pageType, pageTypeList])
    // 跳转落地页
    const linkPageList = useMemo(() => {
        if (pageType) {
            let arr = (pageTypeList?.filter((item: { pageType: any; }) => item.pageType === pageType)[0] as any)?.supportLinkPageType?.list
            return arr
        }
        return null
    }, [pageType, pageTypeList])
    const typeChange = useCallback((adcreativeElementsType) => {
        if (adcreativeElementsType && adcreative_template_list?.length > 0) {
            let adcreativeTemplateIdArr = adcreative_template_list?.filter(item => item.adcreativeTemplateStyle === adcreativeElementsType)
            if (adcreativeTemplateIdArr?.length > 0) {
                getTemplate(adcreativeTemplateIdArr[0].adcreativeTemplateId)
                form.setFieldsValue({ adcreativeTemplateId: adcreativeTemplateIdArr[0].adcreativeTemplateId })
            }
        }
    }, [adcreative_template_list])

    //每次选中创意设置该展示的界面
    const templateChange = (adcreative_template: any, ok?: any) => {
        let states = {
            kp_show: false,
            xd_show: true,
            sj_show: false,
            bq_show: false,
            sp_show: false
        }
        let values: any = { pageType: 'PAGE_TYPE_CANVAS_WECHAT', }
        if (adcreative_template) {
            let pageList = adcreative_template?.landingPageConfig?.supportPageTypeList?.filter((i: { description: string | string[] }) => i.description.includes('微信原生推广页'))//当前版本只获取微信原生页，后期改进
            let pageType = pageList?.length ? pageList[0]?.pageType : null
            //数据展示组件
            if (adcreative_template.adcreativeAttributes.some((item: { name: string }) => item.name === 'conversion_data_type' || item.name === 'conversion_target_type')) {
                let arr = adcreative_template.adcreativeAttributes?.filter((item: { name: string; }) => item.name === 'conversion_data_type' || item.name === 'conversion_target_type')
                let newObj: any = {}
                arr.forEach((item: { propertyDetail: { enumDetail: { enumeration: any[] } }; name: string | number }) => {
                    let arr: any[] = mySet(item.propertyDetail.enumDetail.enumeration)
                    newObj[item.name] = arr
                })
                setConversionList(newObj)
                states = { ...states, sj_show: true }
                if (newObj.conversion_data_type) {
                    values = { ...values, conversionDataType: newObj.conversion_data_type[0].value }
                }
                if (newObj.conversion_target_type) {
                    values = { ...values, conversionTargetType: newObj.conversion_target_type[0].value }
                }
            }

            //行动按钮组件存在
            if (states.xd_show) {
                let supportLinkNameTypeData = (pageList?.filter((item: { pageType: any; }) => item.pageType === pageType)[0] as any)?.supportLinkNameType
                let linkNameList = supportLinkNameTypeData?.list
                let linkPageList = (pageList?.filter((item: { pageType: any; }) => item.pageType === pageType)[0] as any)?.supportLinkPageType?.list
                if (linkNameList) {
                    if (!ok) {
                        let linkNameType = linkNameList[0]?.linkNameType
                        let linkPageType = linkPageList?.some((i: { linkPageType: string }) => i.linkPageType === "LINK_PAGE_TYPE_CANVAS_WECHAT") ? "LINK_PAGE_TYPE_CANVAS_WECHAT" : linkPageList[0]?.linkPageType
                        values = { ...values, linkNameType, linkPageType, actionBtn: true }
                    }
                } else {
                    states = { ...states, xd_show: false }
                }
                if (supportLinkNameTypeData?.required) {
                    states = { ...states, xd_show: true }
                    values = { ...values, actionBtn: true }
                    setIsShowXd(true)
                } else {
                    setIsShowXd(false)
                }
            }
            // 特殊行动按钮
            if (adcreative_template.adcreativeElements?.find((item: { name: string }) => item.name === 'button_text') && !ok) {
                values = { ...values, buttonText: adcreative_template?.adcreativeElements?.find((item: { name: string }) => item.name === 'button_text')?.enumProperty?.enumeration[0].value }
            }
            // 视频结束页 end_page
            if (adcreative_template.adcreativeElements.some((item: { name: string }) => item.name === 'end_page')) {
                // let endPageType =adcreative_template?.adcreativeElements?.filter(item=>item.name === 'end_page_type')[0]?.enumProperty?.enumeration
                if (!ok) {
                    values = { ...values, endPageType: 'END_PAGE_AVATAR_NICKNAME_HIGHLIGHT' }
                }
                states = { ...states, sp_show: true }
            }
            setPupState(states)
            form.setFieldsValue(values)
        }
    }
    // 版位改变清空数据
    useEffect(() => {
        if (imgMaterialConfig.adcreativeTemplateId && adcreativeTemplateId !== imgMaterialConfig.adcreativeTemplateId) {
            setImgMaterialConfig({ ...imgMaterialConfig, adcreativeTemplateId: undefined, list: [] })
            setImgListMaterialConfig({ ...imgListMaterialConfig, adcreativeTemplateId: undefined, list: [] })
        }
        if (videoMaterialConfig.adcreativeTemplateId && adcreativeTemplateId !== videoMaterialConfig.adcreativeTemplateId) {
            setVideoMaterialConfig({ ...videoMaterialConfig, adcreativeTemplateId: undefined, list: [] })
        }
    }, [adcreativeTemplateId, imgMaterialConfig, videoMaterialConfig, imgListMaterialConfig])
    // 文案助手
    const textList = useCallback((arg: { maxTextLength: number, keyword?: string }) => {
        let { maxTextLength, keyword } = arg
        getTextLsit.run({ keyword: keyword || titles || description, maxTextLength })
    }, [titles, description])
    // 监听点击取消文案助手弹窗
    useEffect(() => {
        let modal = document.querySelector('.myModal')
        let onBiurdescription = (e: any) => {
            let d = document.querySelector('.my_description')
            let t = document.querySelector('.my_title')
            let p = document.querySelector('.my_endPageDesc')
            if (!d?.contains(e.target)) {
                setdescriptionshow(false)
            }
            if (!t?.contains(e.target)) {
                settitleshow(false)
            }
            if (!p?.contains(e.target)) {
                setendPageDescnshow(false)
            }
        }
        modal?.addEventListener('click', onBiurdescription)
        return () => {
            modal?.removeEventListener('click', onBiurdescription)
        }

    }, [])
    // 数据回填
    useEffect(() => {
        if (!infoSet && dataInfo && adcreative_template_list?.length > 0) {
            let { adcreativeName, adcreativeTemplateId, conversionDataType, conversionTargetType, linkNameType, linkPageType, pageType, promotedObjectType, siteSet, profile, adcreativeElements, overrideCanvasHeadOption, linkPageSpec } = dataInfo
            let { description, imageUrl, title, videoUrl, imageUrlList, endPage, shortVideoStruct, brand, buttonText, elementStory } = adcreativeElements
            let obj: any = {
                adcreativeName,
                siteSet,
                promotedObjectType,
                adcreativeTemplateId,
            }
            getTemplate(adcreativeTemplateId, true)
            if ([720, 721, 618, 1708, 722, 1529].some(n => n === adcreativeTemplateId)) {
                obj = { ...obj, adcreativeElementsType: '视频' }
            } else {
                obj = { ...obj, adcreativeElementsType: '图片' }
            }
            if (conversionDataType) {
                obj = { ...obj, conversionDataType, dataShow: true }
            }
            if (conversionTargetType) {
                obj = { ...obj, conversionTargetType, dataShow: true }
            }
            if (linkNameType) {
                obj = { ...obj, linkNameType, actionBtn: true }
            }
            if (linkPageType) {
                obj = { ...obj, linkPageType, actionBtn: true }
            }
            if (pageType) {
                obj = { ...obj, pageType }
            }
            if (description) {
                obj = { ...obj, description }
            }
            if (title) {
                obj = { ...obj, title }
            }
            if (endPage) {
                obj = { ...obj, videoOver: true, ...endPage }
            }
            if (overrideCanvasHeadOption) {
                obj = { ...obj, overrideCanvasHeadOption }
            }
            if (linkPageSpec?.pageUrl) {
                obj = { ...obj, pageUrl: linkPageSpec?.pageUrl }
            }
            if (linkPageSpec?.miniProgramSpec && linkPageSpec?.miniProgramSpec?.miniProgramPath) {
                obj = { ...obj, miniProgramPath: linkPageSpec?.miniProgramSpec?.miniProgramPath, miniProgramId: linkPageSpec?.miniProgramSpec?.miniProgramId }
            }
            if (brand && brand.brandImgUrl && brand.brandName) {
                obj = { ...obj, brand: brand.brandName + '_' + brand.brandImgUrl }
            }
            if (profile && profile.headImageUrl && profile.profileName && profile.description) {
                obj = { ...obj, profile: profile.profileName + '_' + profile.headImageUrl + '_' + profile.description }
            }
            if (buttonText) {
                obj = { ...obj, buttonText }
            }
            if (videoUrl) {
                setVideoMaterialConfig({
                    cloudSize: [],
                    list: [{ url: videoUrl }],
                    max: 1,
                    type: 'video',
                    adcreativeTemplateId
                })
                obj = { ...obj, video: videoUrl }
            }
            if (imageUrl) {
                setImgMaterialConfig({
                    cloudSize: [],
                    list: [{ url: imageUrl }],
                    max: 1,
                    type: 'image',
                    adcreativeTemplateId
                })
                obj = { ...obj, image: imageUrl }
            }
            if (imageUrlList) {
                setImgListMaterialConfig({
                    cloudSize: [],
                    list: imageUrlList?.map((url: any) => ({ url })),
                    max: imageUrlList.length,
                    type: 'image_list',
                    adcreativeTemplateId
                })
                obj = { ...obj, image_list: imageUrlList }
            }
            if (elementStory) {
                setImgMaterialConfig({
                    cloudSize: [],
                    list: elementStory?.map((item: { imageUrl: string }) => ({ url: item.imageUrl })),
                    max: elementStory.length,
                    type: 'element_story',
                    adcreativeTemplateId
                })
                obj = { ...obj, element_story: imageUrlList }
            }
            if (shortVideoStruct) {
                setVideoMaterialConfig({
                    cloudSize: [],
                    list: [{ url: shortVideoStruct.shortVideo1Url }],
                    max: 1,
                    type: 'short_video1',
                    adcreativeTemplateId
                })
                obj = { ...obj, short_video1: shortVideoStruct.shortVideo1Url }
            }
            console.log('数据回填====>', obj)
            form.setFieldsValue(obj)
            set_infoSet(true)
        }
        // 不是数据回填首次打开界面选中视频
        if (!infoSet && !dataInfo && adcreative_template_list?.length > 0) {
            typeChange('视频')
            set_infoSet(true)
        }
    }, [dataInfo, adcreative_template_list, adcreative_template, infoSet])
    // 生成视频封面图
    const videoToImgs = useCallback(() => {
        if (videoMaterialConfig.list[0]) {
            set_videoImgsVisbile(true)
            // let url = videoMaterialConfig.list[0].url
            // fetch(url).then(res => res.blob()).then(async (blob) => {
            //     let file = new File([blob], 'sp', { type: blob.type })
            //     // let md5 = await getMD5(file)
            //     let formData = new FormData()
            //     formData.append('videoFile', file)
            //     formData.append('number', '12')
            //     getVideoCapture.run(formData).then(res => {
            //         console.log(res)
            //     })
            // })
        } else {
            message.warning('请先选择视频文件！！！')
        }
    }, [videoMaterialConfig.list])
    return <Modal
        visible={visible}
        title={type === 'add' ? '新建创意' : type === 'look' ? '创意详情' : '编辑创意'}
        onCancel={() => { PupFn({ visible: false, dataInfo: null, type: 'add' }) }}
        // onOk={handleOk}
        width={1200}
        confirmLoading={confirmLoading}
        footer={<Space>
            <Button onClick={() => { PupFn({ visible: false, dataInfo: null, type: 'add' }) }}>取消</Button>
            {
                dataInfo?.id ? <Popconfirm
                title='当前创意为模板点击确定后将变为新创意！如无更改需求请直接取消关闭编辑创意窗口！'
                onConfirm={()=>{
                    handleOk(true)
                }}
            >
                <Button type='primary' >确定</Button>
            </Popconfirm>:  <Button type='primary' onClick={()=>handleOk(false)}>确定</Button>
            }
            {<Checkbox checked={template_checked} onChange={(e) => {
                let checked = e.target.checked
                settemplate_checked(checked)
            }}>存为模板<Tooltip title="勾选此选项后提交计划后此创意将被存为模板，使用模板创建无每天20条限制"><QuestionCircleOutlined /></Tooltip></Checkbox>}
        </Space>}
        className='myModal'
        {...arg}
    >
        <Form
            form={form}
            labelCol={{ span: 5 }}
            labelWrap={true}
            className='ad_form_style'
            initialValues={
                {
                    adcreativeElementsType: '视频',
                }
            }
        >
            {/* ============================================================创意形式============================================================= */}
            <Divider orientation='center'>创意形式</Divider>
            {/* ============================================================创意形式============================================================= */}
            <Form.Item label={<strong>创意形式</strong>} name='adcreativeElementsType'>
                <Radio.Group onChange={(e) => {
                    let value = e.target.value
                    typeChange(value)
                }}>
                    <Radio.Button value="视频" disabled={!templateStyleS?.includes('视频')}>视频</Radio.Button>
                    <Radio.Button value="图片" disabled={!templateStyleS?.includes('图片')}>图片</Radio.Button>
                </Radio.Group>
            </Form.Item>

            {
                getAdcreativeTemplateList?.loading ? <Spin tip="Loading..." style={{ width: '100%' }}></Spin> :
                    <>
                        <Form.Item style={{ marginLeft: 177 }} name='adcreativeTemplateId'>
                            <Radio.Group className={styles.adcreative_template} onChange={(e) => {
                                let id = e.target.value
                                getTemplate(id)
                            }}>
                                {adcreative_template_list?.filter(item => item.adcreativeTemplateStyle === adcreativeElementsType && item.supportBidModeList.includes(queryForm?.sysAdgroup?.bidMode))?.map((item: any) => {
                                    return <Radio.Button value={item.adcreativeTemplateId} key={item.adcreativeTemplateId}>
                                        <div className={styles.adcreative_template_item}>
                                            {item.isGeneral && <span style={{ color: '#4080ff', fontSize: 10 }}>所选版位通投</span>}
                                            <img src={item.adcreativeSampleImage} />
                                            <span style={{ fontSize: 12, height: 20, lineHeight: '20px' }}>{item.adcreativeTemplateAppellation}</span>
                                            <span style={{ fontSize: 12, height: 20, lineHeight: '20px' }}>{item.adcreativeTemplateId}</span>
                                        </div>
                                    </Radio.Button>
                                })}
                            </Radio.Group>
                        </Form.Item>
                        {/* ============================================================创意内容============================================================= */}
                        <Divider orientation='center'>创意内容</Divider>
                        {/* =============================================================头像及昵称跳转页===================================================================== */}
                        {queryForm.promotedObjectType === 'PROMOTED_OBJECT_TYPE_LEAD_AD' ? adcreative_template?.adcreativeAttributes?.find(item => item.name === 'profile_id') ? <Form.Item label={<strong>头像及昵称跳转页</strong>} name='profile' rules={[{ required: true, message: '请选择一个头像及昵称跳转页，与广告创意一起展示' }]}>
                            <HeadNickJump />
                        </Form.Item> : <Form.Item label={<strong>品牌形象</strong>} name='brand' rules={[{ required: true, message: '请选择一个头像及昵称跳转页，与广告创意一起展示' }]}>
                            <BrandImage />
                        </Form.Item> : null}
                        {/* ============================================================素材============================================================= */}
                        {/* 优先展示视频或图片,朋友圈常规不勾选使用外部素材替换内部，隐藏此选项，后期自动将落地页顶部素材添加进入 */}
                        {((overrideCanvasHeadOption !== 'OPTION_CANVAS_OVERRIDE_CREATIVE') || siteSet.every((name: string) => name !== 'SITE_SET_MOMENTS')) && <div style={{ display: 'flex', flexFlow: 'column' }}>
                            {adcreative_template?.adcreativeElements?.filter(item => item.required && item.name === 'image_list' || item.name === 'short_video1' || item.name === 'video' || item.name === 'image' || item.name === 'element_story').map(item => {
                                return <Form.Item
                                    label={<strong>{item.description === '图片' && adcreative_template?.adcreativeElements?.some(item => item.name === 'video') ? '视频封面图' : item.description}</strong>}
                                    key={item.name}
                                >
                                    {/* 视频 */}
                                    {(item.name === 'short_video1' || item.name === 'video') && <Form.Item
                                        noStyle
                                        rules={[{ required: true, message: '请选择素材!' }]}
                                        name={item.name}
                                        style={item.description === '图片' && adcreative_template?.adcreativeElements?.some(item => item.name === 'video') ? { order: 2 } : {}}
                                    >
                                        <div className={`${styles.box} ${styles.video}`} onClick={() => {
                                            init({ mediaType: 'VIDEO', cloudSize: adcreativeTemplateId === 1708 ? [[{ relation: '=', width: 1280, height: 720 }]] : [[{ relation: '=', width: item.restriction.videoRestriction.minWidth, height: item.restriction.videoRestriction.minHeight }]], maxSize: item.restriction.videoRestriction.fileSize * 1024 })
                                            setTimeout(() => {
                                                set_selectVideoVisible(true)
                                                setVideoMaterialConfig({
                                                    ...videoMaterialConfig,
                                                    type: item.name,
                                                    max: 1,
                                                    adcreativeTemplateId
                                                })
                                            }, 100)
                                        }}>
                                            <div className={styles.p}>
                                                {videoMaterialConfig?.list[0] ? <VideoNews src={videoMaterialConfig?.list[0].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>{`推荐尺寸（${adcreativeTemplateId === 1708 ? 1280 : item.restriction.videoRestriction.minWidth} x ${adcreativeTemplateId === 1708 ? 720 : item.restriction.videoRestriction.minHeight}）`}</span>
                                                    <span>{`${item.restriction.videoRestriction.fileFormat?.map(str => 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>}
                                    {/* 单图 */}
                                    {item.name === 'image' && <Form.Item
                                        noStyle
                                        rules={[{ required: true, message: '请选择素材!' }]}
                                        name={item.name}
                                        style={item.description === '图片' && adcreative_template?.adcreativeElements?.some(item => item.name === 'video') ? { order: 2 } : {}}
                                    >
                                        <div className={styles.cjBox}>
                                            <div className={`${styles.box} ${styles.image}`} onClick={() => {
                                                init({ mediaType: 'IMG', cloudSize: [[{ relation: '=', width: item.restriction.imageRestriction.width, height: item.restriction.imageRestriction.height }]], maxSize: item.restriction.imageRestriction.fileSize * 1024 })
                                                setimgType('single')
                                                setTimeout(() => {
                                                    set_selectImgVisible(true)
                                                    setImgMaterialConfig({
                                                        ...imgMaterialConfig,
                                                        type: item.name,
                                                        max: 1,
                                                        adcreativeTemplateId
                                                    })
                                                }, 100)
                                            }}>
                                                <p>
                                                    {imgMaterialConfig?.list[0] ? <img src={imgMaterialConfig?.list[0].url} /> : <>
                                                        <span>{`推荐尺寸（${item.restriction.imageRestriction.width} x ${item.restriction.imageRestriction.height}）`}</span>
                                                        <span>{`${item.restriction.imageRestriction.fileFormat?.map(str => str?.replace('IMAGE_TYPE_', ''))}；小于 ${item.restriction.imageRestriction.fileSize}KB`}</span>
                                                    </>}
                                                </p>
                                            </div>
                                            {adcreative_template?.adcreativeElements.some(item => item.name === 'short_video1' || item.name === 'video') && <div style={{ width: 32 }}>
                                                {videoMaterialConfig?.list?.[0]?.url && <VideoFrame
                                                    onChange={(e) => {
                                                        setImgMaterialConfig({ ...imgMaterialConfig, type: 'image', adcreativeTemplateId, list: [{ url: e }] })
                                                        form.setFieldsValue({ image: 'image' })
                                                    }}
                                                    url={videoMaterialConfig?.list[0].url}
                                                />}
                                            </div>}
                                        </div>
                                    </Form.Item>}
                                    {/* 多图 */}
                                    {item.name === 'image_list' && <Form.Item
                                        noStyle
                                        rules={[{ required: true, message: '请选择素材!' }]}
                                        name={item.name}
                                        style={item.description === '图片' && adcreative_template?.adcreativeElements?.some(item => item.name === 'video') ? { order: 2 } : {}}
                                    >
                                        <div className={`${styles.box} ${item.arrayProperty.maxNumber >= 3 ? styles.image_list : styles.image}`} onClick={() => {
                                            init({ mediaType: 'IMG', num: item.arrayProperty.maxNumber, cloudSize: [[{ relation: '=', width: item.restriction.imageRestriction.width, height: item.restriction.imageRestriction.height }]], maxSize: item.restriction.imageRestriction.fileSize * 1024 })
                                            setimgType('many')
                                            setTimeout(() => {
                                                set_selectImgVisible(true)
                                                setImgListMaterialConfig({
                                                    ...imgListMaterialConfig,
                                                    type: item.name,
                                                    max: item.arrayProperty.maxNumber,
                                                    adcreativeTemplateId
                                                })
                                            }, 100)
                                        }}>
                                            {Array(item.arrayProperty.maxNumber).fill('').map((arr, index) => {
                                                return <p key={index}>
                                                    {imgListMaterialConfig?.list[index] ? <img src={imgListMaterialConfig?.list[index].url} /> : <>
                                                        <span>{`推荐尺寸（${item.restriction.imageRestriction.width} x ${item.restriction.imageRestriction.height}）`}</span>
                                                        <span>{`${item.restriction.imageRestriction.fileFormat?.map(str => str?.replace('IMAGE_TYPE_', ''))}；小于 ${item.restriction.imageRestriction.fileSize}KB`}</span>
                                                    </>}
                                                </p>
                                            })}
                                        </div>
                                    </Form.Item>}
                                    {item.name === 'element_story' && <Form.Item
                                        noStyle
                                        rules={[{ required: true, message: '请选择素材!' }]}
                                        name={item.name}
                                        style={item.description === '图片' && adcreative_template?.adcreativeElements?.some(item => item.name === 'video') ? { order: 2 } : {}}
                                    >
                                        <div className={`${styles.box} ${item.arrayProperty.maxNumber >= 3 ? styles.image_list : styles.image}`} onClick={() => {
                                            init({ mediaType: 'IMG', num: item?.arrayProperty?.maxNumber, cloudSize: [[{ relation: '=', width: item?.restriction.imageRestriction?.width, height: item?.restriction.imageRestriction?.height }]], maxSize: item?.restriction?.imageRestriction?.fileSize * 1024 })
                                            setimgType('single')
                                            setTimeout(() => {
                                                set_selectImgVisible(true)
                                                setImgMaterialConfig({
                                                    ...imgMaterialConfig,
                                                    type: item.name,
                                                    max: item.arrayProperty.maxNumber,
                                                    adcreativeTemplateId
                                                })
                                            }, 100)
                                        }}>
                                            {Array(item.arrayProperty.maxNumber).fill('').map((arr, index) => {
                                                return <p key={index}>
                                                    {imgMaterialConfig?.list[index] ? <img style={item?.restriction.imageRestriction?.width > item?.restriction.imageRestriction?.height ? { width: '100%', height: 'auto' } : {}} src={imgMaterialConfig?.list[index].url} /> : <>
                                                        <span>{`推荐尺寸（${item.restriction.imageRestriction.width} x ${item.restriction.imageRestriction.height}）`}</span>
                                                        <span>{`${item.restriction.imageRestriction.fileFormat?.map(str => str?.replace('IMAGE_TYPE_', ''))}；小于 ${item.restriction.imageRestriction.fileSize}KB`}</span>
                                                    </>}
                                                </p>
                                            })}
                                        </div>
                                    </Form.Item>}
                                </Form.Item>
                            })}
                        </div>}

                        {/* 标题 */}
                        {
                            adcreative_template?.adcreativeElements?.filter(item => item.name === 'title').map(item => {
                                return <div key={item.fieldType}>
                                    <Form.Item label={<strong>{item.description}(选填)</strong>} className={'my_title'} >
                                        <Form.Item
                                            name={item.name}
                                            rules={[{
                                                // pattern: RegExp(item.restriction.textRestriction.textPattern?.replace(/\+/ig, `{1,${item.restriction.textRestriction.maxLength}}`)),
                                                required: true,
                                                message: '请输入正确的' + item.description,
                                                validator: (rule, value) => {
                                                    if (!value) {
                                                        return Promise.reject()
                                                    } else if (!value.match(RegExp(item.restriction.textRestriction.textPattern))) {
                                                        return Promise.reject()
                                                    } else if (txtLength(value) > item.restriction.textRestriction.maxLength) {
                                                        return Promise.reject()
                                                    }
                                                    return Promise.resolve()
                                                }
                                            }]}
                                            noStyle
                                        >
                                            <Input
                                                placeholder={'请输入' + item.description}
                                                style={{ width: 500 }}
                                                allowClear
                                                onFocus={() => {
                                                    settitleshow(true)
                                                    textList({ maxTextLength: item.restriction.textRestriction.maxLength })
                                                }}
                                                onChange={(e) => {
                                                    let value = e.target.value
                                                    textList({ maxTextLength: item.restriction.textRestriction.maxLength, keyword: value })
                                                }}
                                            />
                                        </Form.Item>
                                        <span>{`${titles?.length ?? 0}/${item.restriction.textRestriction.maxLength}`}</span>
                                        {titleShow && <List
                                            loading={getTextLsit?.loading}
                                            size="small"
                                            style={{ maxHeight: 300, overflowX: 'auto' }}
                                            bordered
                                            dataSource={getTextLsit?.data?.returnTexts}
                                            renderItem={(item: any) => <List.Item onClick={() => {
                                                form.setFieldsValue({ title: item.text })
                                                settitleshow(false)
                                            }}><span >{item.text}{item.tag && <span className={styles.crt}>{'CTR 高'}</span>}</span></List.Item>}
                                        />}
                                    </Form.Item>
                                </div>
                            })
                        }
                        {/* 过滤了不必传和品牌名称，品牌标识图（外部传）短视频结构（组装使用） */}
                        {adcreative_template?.adcreativeElements?.filter(item => item.required && item.name === 'description').map(item => {
                            let maxNum = (adcreativeTemplateId === 1708 || adcreativeTemplateId === 1707) && actionBtn ? 10 : item.restriction.textRestriction.maxLength
                            return <div key={item.fieldType}>
                                <Form.Item label={<strong>{item.description}</strong>} className={'my_description'}>
                                    <Form.Item name={item.name} noStyle rules={[{
                                        required: true,
                                        // pattern: RegExp(item.restriction.textRestriction.textPattern?.replace(/\+/ig, `{1,${maxNum}}`)), 
                                        message: '请输入正确的' + item.description,
                                        validator: (rule, value) => {
                                            if (!value) {
                                                return Promise.reject()
                                            } else if (!value.match(RegExp(item.restriction.textRestriction.textPattern))) {
                                                return Promise.reject()
                                            } else if (txtLength(value) > maxNum) {
                                                return Promise.reject()
                                            }
                                            return Promise.resolve()
                                        }
                                    }]}>
                                        <Input
                                            placeholder={'请输入' + item.description}
                                            style={{ width: 500 }}
                                            onFocus={() => {
                                                setdescriptionshow(true)
                                                textList({ maxTextLength: maxNum })
                                            }}
                                            onChange={(e) => {
                                                let value = e.target.value
                                                textList({ maxTextLength: maxNum, keyword: value })
                                            }}
                                            allowClear
                                        />
                                    </Form.Item>
                                    <span>{`${description?.length ?? 0}/${maxNum}`}</span>
                                    {descriptionShow && <List
                                        loading={getTextLsit?.loading}
                                        size="small"
                                        style={{ maxHeight: 300, overflowX: 'auto' }}
                                        bordered
                                        dataSource={getTextLsit?.data?.returnTexts}
                                        renderItem={(item: any) => <List.Item onClick={(e: any) => {
                                            form.setFieldsValue({ description: item.text })
                                            setdescriptionshow(false)
                                        }}><span >{item.text}{item.tag && <span className={styles.crt}>{'CTR 高'}</span>}</span></List.Item>}
                                    />}
                                </Form.Item>
                            </div>
                        })}
                        {/* ============================================================落地页============================================================= */}
                        {adcreativeTemplateId ? <Form.Item label={<strong>落地页</strong>} name='pageType' >
                            <Radio.Group>
                                {pageTypeList?.map((item: any) => {
                                    return <Radio.Button value={item.pageType} key={item.pageType} disabled={!item.description.includes('微信原生推广页')}>{item.description.includes('微信原生推广页') ? '微信原生推广页' : item.description}</Radio.Button>
                                })}
                            </Radio.Group>
                        </Form.Item> : <div style={{ minHeight: 400, display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                            <Empty description="请先选择创意形式" />
                        </div>}
                        {pageType === 'PAGE_TYPE_CANVAS_WECHAT' && isShowSc && <Form.Item label={<strong>素材选项</strong>} name='overrideCanvasHeadOption'>
                            <Radio.Group >
                                {adcreativeTemplateId && creativeConfig[adcreativeTemplateId]?.overrideCanvasHeadOption?.map((item: string | number) => {
                                    return <Radio value={item} key={item}>{overrideCanvasHeadOptionEnum[item]}</Radio>
                                })}
                            </Radio.Group>
                        </Form.Item>}
                        {/* ============================================================普通行动按钮============================================================= */}
                        {pupState.xd_show && <Form.Item hidden={isShowXd} label={<strong>行动按钮</strong>} name='actionBtn' valuePropName="checked">
                            <Switch checkedChildren="开启" unCheckedChildren="关闭" disabled={isShowXd} />
                        </Form.Item>}
                        {actionBtn && <>
                            <Form.Item name='linkNameType' label={<strong>按钮文案</strong>}>
                                <Select style={{ width: 200 }} showSearch filterOption={(input, option) =>
                                    (option!.children as unknown as string).toLowerCase().includes(input.toLowerCase())
                                } allowClear>
                                    {linkNameList?.map((item: any) => {
                                        return <Select.Option value={item.linkNameType} key={item.linkNameType}>{item.description}</Select.Option>
                                    })}
                                </Select>
                            </Form.Item>
                            <Form.Item label={<strong>跳转落地页</strong>}>
                                <Form.Item name='linkPageType' noStyle>
                                    <Radio.Group style={{ display: 'flex' }}>
                                        {linkPageList?.map((item: { linkPageType: string; description: string; }, index: number) => {
                                            return <Radio.Button value={item.linkPageType} key={item.linkPageType} >{item.description}</Radio.Button>
                                        })}
                                    </Radio.Group>
                                </Form.Item>
                                {/* 自定义落地页地址 */}
                                {linkPageType === "LINK_PAGE_TYPE_DEFAULT" && <Form.Item name='pageUrl' rules={[{ required: true, message: '请输入自定义落地页地址' }]} style={{ marginTop: 10, marginBottom: 0 }}>
                                    <Input placeholder='请输入自定义落地页地址' style={{ width: 300 }} />
                                </Form.Item>}
                                {/* 小程序 */}
                                {
                                    linkPageType === "LINK_PAGE_TYPE_MINI_PROGRAM_WECHAT" && <Form.Item noStyle >
                                        <Form.Item rules={[{ required: true, message: '请输入小程序原始ID' }]} name='miniProgramId' style={{ marginTop: 10, marginBottom: 0 }} >
                                            <Input placeholder='请输入小程序原始ID' style={{ width: 300 }} />
                                        </Form.Item>
                                        <Form.Item rules={[{ required: true, message: '请输入小程序链接' }]} name='miniProgramPath' style={{ marginTop: 10, marginBottom: 0 }}>
                                            <Input placeholder='请输入小程序链接' style={{ width: 300 }} />
                                        </Form.Item>
                                    </Form.Item>
                                }
                            </Form.Item>
                            {/* 落地页 */}

                        </>}
                        {/* ============================================================特殊行动按钮============================================================= */}
                        {!pupState.xd_show && adcreative_template?.adcreativeElements?.find(item => item.name === 'button_text') && <Form.Item label={<strong>行动按钮</strong>} >
                            <Form.Item valuePropName="checked" noStyle >
                                <Switch checkedChildren="开启" unCheckedChildren="关闭" checked={true} disabled defaultChecked={true} />
                            </Form.Item>
                        </Form.Item>}
                        {!pupState.xd_show && adcreative_template?.adcreativeElements?.find(item => item.name === 'button_text') && <Form.Item name='buttonText' label={<strong>按钮文案</strong>} rules={[{ required: true, message: '请选择按钮文案！' }]}>
                            <Select style={{ width: 200 }} showSearch filterOption={(input, option) =>
                                (option!.children as unknown as string).toLowerCase().includes(input.toLowerCase())
                            } allowClear>
                                {
                                    adcreative_template?.adcreativeElements?.find(item => item.name === 'button_text')?.enumProperty?.enumeration?.map((item: any) => {
                                        return <Select.Option value={item.value} key={item.value}>{item.value}</Select.Option>
                                    })
                                }
                            </Select>
                        </Form.Item>}
                        {/* ============================================================数据展示============================================================= */}
                        {pupState.sj_show && <Form.Item label={<strong>数据展示</strong>} name='dataShow' valuePropName="checked">
                            <Switch checkedChildren="开启" unCheckedChildren="关闭" />
                        </Form.Item>}
                        {dataShow && <>
                            <Form.Item name='conversionDataType' label={<strong>数据类型</strong>}>
                                <Radio.Group>
                                    {
                                        conversionList?.conversion_data_type?.map((item: { value: string; description: string; }, index: number) => {
                                            return <Radio.Button value={item.value} key={item.value}>{item.description}</Radio.Button>
                                        })
                                    }
                                </Radio.Group>
                            </Form.Item>
                            {conversionList?.conversion_target_type && conversionDataType === 'CONVERSION_DATA_ADMETRIC' && <Form.Item name='conversionTargetType' label={<strong>转化行为</strong>}>
                                <Radio.Group>
                                    {
                                        conversionList?.conversion_target_type?.map((item: { value: string; description: string; }, index: number) => {
                                            return <Radio.Button value={item.value} key={item.value}>{item.description}</Radio.Button>
                                        })
                                    }
                                </Radio.Group>
                            </Form.Item>}
                        </>}
                        {/* ============================================================视频结束页============================================================= */}
                        {pupState.sp_show && <Form.Item label={<strong>视频结束页</strong>} name='videoOver' valuePropName="checked">
                            <Switch checkedChildren="开启" unCheckedChildren="关闭" />
                        </Form.Item>}
                        {videoOver && <>
                            <Form.Item name='endPageType' label={<strong>视频结束页类型</strong>} >
                                <Radio.Group>
                                    {adcreative_template?.adcreativeElements?.filter(item => item.name === 'end_page_type')[0]?.enumProperty?.enumeration?.map((item) => {
                                        return <Radio.Button value={item.value} key={item.value}>{item.description}</Radio.Button>
                                    })}
                                </Radio.Group>
                            </Form.Item>
                            <div className={'my_endPageDesc'} >
                                <Form.Item label={<strong>结束文案</strong>}>
                                    <Form.Item name='endPageDesc' rules={[{
                                        required: true,
                                        // pattern: RegExp("^[^\\<\\>\\&'\\\"\\/\\x08\\x09\\x0A\\x0D\\\\]{1,12}$"),
                                        message: '请输入正确的结束页文案',
                                        validator: (rule, value) => {
                                            if (!value) {
                                                return Promise.reject()
                                            } else if (!value.match(RegExp("^[^\\<\\>\\&'\\\"\\/\\x08\\x09\\x0A\\x0D\\\\]+$"))) {
                                                return Promise.reject()
                                            } else if (txtLength(value) > 12) {
                                                return Promise.reject()
                                            }
                                            return Promise.resolve()
                                        }
                                    }]} noStyle>
                                        <Input
                                            placeholder='请输入结束页文案'
                                            style={{ width: 300 }}
                                            onFocus={() => {
                                                setendPageDescnshow(true)
                                                textList({ maxTextLength: 12 })
                                            }}
                                            onChange={(e) => {
                                                let value = e.target.value
                                                textList({ maxTextLength: 12, keyword: value })
                                            }}
                                            allowClear
                                        />
                                    </Form.Item>
                                    <span>{endPageDesc?.length || 0}/12</span>
                                    {endPageDescShow && <List
                                        loading={getTextLsit?.loading}
                                        size="small"
                                        style={{ maxHeight: 300, maxWidth: 300, overflowX: 'auto' }}
                                        bordered
                                        dataSource={getTextLsit?.data?.returnTexts}
                                        renderItem={(item: any) => <List.Item onClick={(e: any) => {
                                            form.setFieldsValue({ endPageDesc: item.text })
                                            setendPageDescnshow(false)
                                        }}><span >{item.text}{item.tag && <span className={styles.crt}>{'CTR 高'}</span>}</span></List.Item>}
                                    />}
                                </Form.Item>
                            </div>
                        </>}
                    </>
            }
            {/* ============================================================基本信息============================================================= */}
            <Divider orientation='center'>基本信息</Divider>
            {/* ============================================================创意名称============================================================= */}
            <Form.Item label={<strong>创意名称</strong>} name='adcreativeName' rules={[{ required: true, message: '请输入广告名称!' }]}>
                <Input placeholder='创意名称' style={{ width: 300 }} />
            </Form.Item>
        </Form>
        {/* 选择图片素材 */}
        {selectImgVisible && <SelectCloud
            visible={selectImgVisible}
            onClose={() => {
                set_selectImgVisible(false)
            }}
            sliderImgContent={imgType === 'many' ? imgListMaterialConfig.list : imgMaterialConfig.list}
            onChange={(content) => {
                if (imgType === 'many') {
                    setImgListMaterialConfig({ ...imgListMaterialConfig, list: content })
                    if (content.length > 0) {
                        form.setFieldsValue({ [imgListMaterialConfig.type]: imgListMaterialConfig.type })
                    }
                } else {
                    setImgMaterialConfig({ ...imgMaterialConfig, list: content })
                    if (content.length > 0) {
                        form.setFieldsValue({ [imgMaterialConfig.type]: imgMaterialConfig.type })
                    }
                }
                set_selectImgVisible(false)
            }}
        />}
        {/* 选择视频素材 */}
        {selectVideoVisible && <SelectCloud
            visible={selectVideoVisible}
            onClose={() => set_selectVideoVisible(false)}
            sliderImgContent={videoMaterialConfig.list}
            onChange={(content: any) => {
                if (content.length > 0) {
                    form.setFieldsValue({ [videoMaterialConfig.type]: videoMaterialConfig.type })
                }
                setVideoMaterialConfig({ ...videoMaterialConfig, list: content })
                set_selectVideoVisible(false)
                if (adcreative_template?.adcreativeElements.some(item => item.name === 'image') && content.length > 0) {
                    setImgMaterialConfig({ ...imgMaterialConfig, type: 'image', adcreativeTemplateId, list: [{ url: getVideoImgUrl(content[0]?.url) }] })
                    form.setFieldsValue({ image: 'image' })
                }
            }}
        />}
        {/* 视频封面图弹窗 */}
        {videoImgsVisbile && <Modal
            visible={videoImgsVisbile}
            title={<div>生成封面图 <Switch checkedChildren="开启预览" unCheckedChildren="关闭预览" checked={videoImgs.preview} onChange={(checked) => { set_videoImgs({ ...videoImgs, preview: checked }) }} /></div>}
            onOk={() => {
                if (videoImgs.activeUrl) {
                    setImgMaterialConfig({ ...imgMaterialConfig, list: [{ url: videoImgs.activeUrl }] })
                    set_videoImgsVisbile(false)
                } else {
                    message.error('请选择图片，获取使用取消按钮关闭弹窗！')
                }
            }}
            onCancel={() => { set_videoImgsVisbile(false) }}
            confirmLoading={getVideoCapture.loading}
            width={600}
        >

            <Radio.Group className={styles.videoImgs} onChange={(e) => {
                let url = e.target.value
                set_videoImgs({ ...videoImgs, activeUrl: url })
            }}>
                {
                    videoImgs?.urlList?.map((item: any, index: number) => {
                        return <Radio.Button value={item} key={index}>
                            <Image src={item} preview={videoImgs.preview} />
                        </Radio.Button>
                    })
                }
            </Radio.Group>
        </Modal>}
    </Modal >
}
export default CreativePup