import React, { useCallback, useEffect, useMemo, useState } from 'react'
import { Modal, Form, Input, Divider, Select, Radio, Switch, Spin, List, Space, Button, message, Image, Empty } 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 { creativeConfig, overrideCanvasHeadOptionEnum } from './config'
import BrandImage from './brandImage'
import HeadNickJump from './headNickJump'
import moment from 'moment'
interface Props {
    queryForm: Partial<CreateAdProps>,
    title?: string,
    visible: boolean,
    PupFn: (arg: ModalConfig) => void,
    callback: (params: any, material: { label: string, name: string, restriction: any }[], textData: 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
    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 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 [endPageDescShow, setendPageDescnshow] = useState(false)
    const [materialData, setMaterialData] = useState<{ label: string, name: string, restriction: any }[]>([])
    const [textData, setTextData] = useState<any[]>([])
    const [isShowSc, set_isShowSc] = useState(false)//是否展示素材选项
    const [infoSet, set_infoSet] = 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 [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 [videoMaterialConfig, setVideoMaterialConfig] = useState<{
        adcreativeTemplateId?: number,
        type: string,
        cloudSize: { relation: string, width: number, height: number }[],
        list: any[],
        max: number
    }>({
        type: '',//类型
        cloudSize: [],//素材搜索条件
        list: [],//素材
        max: 1,//素材数量
    })//图片素材配置
    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)
    /***************************************/

    // 确定事件
    const handleOk = useCallback(() => {
        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: imgMaterialConfig.list?.map(item => 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)
            newValues['isTemplate'] = template_checked
            // // 开启存为模板开关执行
            callback(newValues, materialData, textData)
        })
    }, [form, imgMaterialConfig, videoMaterialConfig, materialData, textData, 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 = []
                // 过滤掉相同的和即将下线的
                if (!res) {
                    return
                }
                // 
                Object.values(res)?.forEach((arr: any) => {
                    Array.isArray(arr) && arr?.forEach((item: any) => {
                        if (newArr.length > 0) {//假如已存在ID，需要过滤相同
                            if (outAdcreativeTemplateIdFun(item.adcreativeTemplateId) && newArr.every((i: { adcreativeTemplateId: any }) => i.adcreativeTemplateId !== item.adcreativeTemplateId)) {//不重复的添加
                                newArr.push(item)
                            } else {
                                // 找出通用创意
                                newArr = newArr?.map((arr: { adcreativeTemplateId: any }) => {
                                    if (arr.adcreativeTemplateId === item.adcreativeTemplateId) {
                                        return { ...arr, isGeneral: true }
                                    }
                                    return arr
                                })
                            }
                        } else {//不存在ID直接过滤掉即将下线的
                            if (outAdcreativeTemplateIdFun(item.adcreativeTemplateId)) {
                                newArr.push(item)
                            }
                        }
                    })
                })
                /*****暂时排除激励和banner有问题******/
                if (siteSet.some((i: string) => i === 'SITE_SET_MOMENTS')) {
                    newArr = newArr.filter((item: { adcreativeTemplateId: number }) => item.adcreativeTemplateId !== 910 && item.adcreativeTemplateId !== 925)
                }
                set_adcreative_template_list(newArr)
            })
        }
    }, [siteSet, promotedObjectType])
    // 获取创意形式详情
    const getTemplate = useCallback((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 })
                        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
                                let overrideCanvasHeadOption = creativeConfig[id].overrideCanvasHeadOption
                                form.setFieldsValue({ overrideCanvasHeadOption: overrideCanvasHeadOption?.includes('OPTION_CREATIVE_OVERRIDE_CANVAS') ? 'OPTION_CREATIVE_OVERRIDE_CANVAS' : overrideCanvasHeadOption[0] })
                            }
                        }
                        templateChange(res[0], ok)
                        // 处理素材
                        setMaterialData(res[0]?.adcreativeElements?.filter((item: any) => item.required && item.name === 'image_list' || item.name === 'short_video1' || item.name === 'video' || item.name === 'image').map((item: any) => {
                            return {
                                label: item.description === '图片' && res[0]?.adcreativeElements?.some((item: any) => item.name === 'video') ? '视频封面图' : item.description,
                                name: item.name,
                                restriction: item.restriction,
                                arrayProperty: item?.arrayProperty
                            }
                        }))
                        // 处理文案
                        setTextData(res[0]?.adcreativeElements?.filter((item: any) => item.name === 'title' || (item.required && item.name === 'description')).map((item: any) => ({ ...item, pupState })))
                    }
                })
            }
        }
    }, [siteSet, promotedObjectType, pupState])
    // 获取对应落地页按钮
    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)
            console.log('typeChange====>', adcreativeTemplateIdArr[0].adcreativeTemplateId)
            getTemplate(adcreativeTemplateIdArr[0].adcreativeTemplateId)
            form.setFieldsValue({ adcreativeTemplateId: adcreativeTemplateIdArr[0].adcreativeTemplateId })

        }
    }, [adcreative_template_list])

    //每次选中创意设置该展示的界面
    const templateChange = useCallback((adcreative_template, 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 linkNameList = (pageList?.filter((item: { pageType: any; }) => item.pageType === pageType)[0] as any)?.supportLinkNameType?.list
                let linkPageList = (pageList?.filter((item: { pageType: any; }) => item.pageType === pageType)[0] as any)?.supportLinkPageType?.list
                if (linkNameList && !linkPageType) {
                    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 (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)
        }
    }, [pageType, linkPageType])
    // 版位改变清空数据
    useEffect(() => {
        if (imgMaterialConfig.adcreativeTemplateId && adcreativeTemplateId !== imgMaterialConfig.adcreativeTemplateId) {
            setImgMaterialConfig({ ...imgMaterialConfig, adcreativeTemplateId: undefined, list: [] })
        }
        if (videoMaterialConfig.adcreativeTemplateId && adcreativeTemplateId !== videoMaterialConfig.adcreativeTemplateId) {
            setVideoMaterialConfig({ ...videoMaterialConfig, adcreativeTemplateId: undefined, list: [] })
        }
    }, [adcreativeTemplateId, imgMaterialConfig, videoMaterialConfig])
    // 文案助手
    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 p = document.querySelector('.my_endPageDesc')
            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 } = adcreativeElements
            let obj: any = {
                adcreativeName,
                siteSet,
                promotedObjectType,
                adcreativeTemplateId,
            }
            getTemplate(adcreativeTemplateId, true)
            console.log(2222, dataInfo)
            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) {
                setImgMaterialConfig({
                    cloudSize: [],
                    list: imageUrlList?.map((url: any) => ({ url })),
                    max: imageUrlList.length,
                    type: 'image_list',
                    adcreativeTemplateId
                })
                obj = { ...obj, image_list: 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])
    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>
            <Button type='primary' onClick={handleOk}>确定</Button>
        </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="视频">视频</Radio.Button>
                    <Radio.Button value="图片">图片</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}
                        {/* ============================================================落地页============================================================= */}
                        {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 disabled>
                                    {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 label={<strong>行动按钮</strong>} name='actionBtn' valuePropName="checked">
                                <Switch checkedChildren="开启" unCheckedChildren="关闭" />
                            </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>
                                {/* 落地页 */}

                            </>
                        }
                        {/* ============================================================特殊行动按钮============================================================= */}
                        {
                            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>
                        }
                        {
                            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: '请输入正确的结束页文案' }]} 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={imgMaterialConfig.list}
                onChange={(content) => {
                    if (content.length > 0) {
                        form.setFieldsValue({ [imgMaterialConfig.type]: imgMaterialConfig.type })
                    }
                    setImgMaterialConfig({ ...imgMaterialConfig, list: content })
                    set_selectImgVisible(false)
                }} />
        }
        {/* 选择视频素材 */}
        {
            selectVideoVisible && <SelectCloud
                visible={selectVideoVisible}
                onClose={() => set_selectVideoVisible(false)}
                sliderImgContent={videoMaterialConfig.list}
                onChange={(content) => {
                    if (content.length > 0) {
                        form.setFieldsValue({ [videoMaterialConfig.type]: videoMaterialConfig.type })
                    }
                    setVideoMaterialConfig({ ...videoMaterialConfig, list: content })
                    set_selectVideoVisible(false)
                }} />
        }
        {/* 视频封面图弹窗 */}
        {
            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