import { Button, Card, Empty, Modal, Popconfirm, Radio, Space, Spin, Table, Tabs, Tag, Tooltip, message, notification } from "antd"
import React, { useEffect, useState } from "react"
import style from './index.less'
import '../index.less'
import { CheckOutlined, SearchOutlined } from "@ant-design/icons"
import Ad from "./Ad"
import Target from "./Target"
import { useAjax } from "@/Hook/useAjax"
import { useModel } from "umi"
import GoodsModal from "../../components/GoodsModal"
import DataSourceModal from "../../components/DataSourceModal"
import moment from "moment"
import Dynamic from "./Dynamic"
import Material from "./Material"
import MaterialText from "./MaterialText"
import PageList from "./PageList"
import { cartesianProduct, distributeArray, processData, randomString, splitArrayIntoRandomChunks, groupArr } from "@/utils/utils"
import columns from "./tableConfig"
import SubmitModal from "./submitModal"
import { createAdgroupTaskApi, createAdgroupTaskV2Api, getSelectTaskDetailApi } from "@/services/adqV3"
import WechatAccount from "../../components/WechatAccount"
import Title from "antd/lib/typography/Title"
import { getCreativeDetailsApi } from "@/services/adqV3/global"
import ConversionSelect from "../../components/ConversionSelect"
import VideoChannel from "../../components/VideoChannel"
import Save from "./Save"
import { useLocalStorageState } from "ahooks"
import SelectAccount from "./SelectAccount"
import PositionPackage from "../../components/PositionPackage"
import Audience from "../../components/Audience"

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

/**
 * 创建广告
 * @returns 
 */
const Create: React.FC = () => {

    /*******************************************/
    const { initialState } = useModel('@@initialState');
    const { initTargeting } = useModel('useLaunchV3.useTargeting')
    const [addelivery, setAddelivery] = useState<PULLIN.AddeliveryProps>({ adgroups: {}, targeting: [], dynamic: {}, dynamicMaterialDTos: {}, dynamicCreativesTextDTOS: {}, mediaType: 0 })
    const { marketingAssetOuterSpec, marketingCarrierType, marketingGoal, marketingSubGoal, siteSet, automaticSiteEnabled, sceneSpec, isConversion } = addelivery.adgroups
    const { deliveryMode, creativeTemplateId, dynamicCreativeSwitch, creativeComponents } = addelivery.dynamic
    const [accountCreateLogs, setAccountCreateLogs] = useState<PULLIN.AccountCreateLogsProps[]>([])  // 账户
    const [goodsVisible, setGoodsVisible] = useState<boolean>(false) // 选择小说弹窗控制
    const [wechatVisible, setWechatVisible] = useState<boolean>(false) // 选择微信公众号弹窗控制
    const [channelsProfileVisible, setChannelsProfileVisible] = useState<boolean>(false) // 选择微信公众号弹窗控制
    const [sourceVisible, setSourceVisible] = useState<boolean>(false) // 选择数据源弹窗控制
    const [conversionVisible, setConversionVisible] = useState<boolean>(false) // 选择转化归因控制
    const [positionPackageVisible, setPositionPackageVisible] = useState<boolean>(false) // 选择优量汇流量包
    const [audienceVisible, setAudienceVisible] = useState<boolean>(false) // 选择定向人群宝
    const [materialData, setMaterialData] = useState<any>({}) // 素材数据
    const [textData, setTextData] = useState<any>({})
    const [tableData, setTableData] = useState<any>({})
    const [activeKey, setActiveKey] = useState<string>()
    const [subVisible, setSubVisible] = useState<boolean>(false) // 选择设置名称弹窗控制
    const [adCount, setAdCount] = useState<number>(0)
    const [adLength, setAdLength] = useState<number>(0)
    const [dynamicCount, setDynamicCount] = useState<number>(0)
    const [creativeTemplateAppellation, setCreativeTemplateAppellation] = useState<string>()
    const [creativeTemplateStyle, setCreativeTemplateStyle] = useState<string>()
    const [putInTypeList, setPutInTypeList] = useState<{ label: string, value: string }[]>([])
    const [putInType, setPutInType] = useLocalStorageState<'NOVEL' | 'GAME'>('PUTINTYPE');
    const [copyTask, setCopyTask] = useState<{ copyTaskId?: number, uuid?: string }>({})
    const [ownerAccountId, setOwnerAccountId] = useState<number>()
    const [isDqSubmit, setIsDqSubmit] = useState<boolean>(false) // 是否提交过
    const [targetRules, setTargetRules] = useState<PULLIN.TargetingRulesProps>()

    const createAdgroupTask = useAjax((params) => createAdgroupTaskApi(params))
    const createAdgroupTaskV2 = useAjax((params) => createAdgroupTaskV2Api(params))
    const getSelectTaskDetail = useAjax((params) => getSelectTaskDetailApi(params))
    const getCreativeDetails = useAjax((params) => getCreativeDetailsApi(params))
    /*******************************************/

    // 判断游戏还是小说短剧
    useEffect(() => {
        let newputInTypeList: { label: string, value: string }[] = []
        newputInTypeList.push({ label: '小说/短剧投放', value: 'NOVEL' })
        newputInTypeList.push({ label: '游戏投放', value: 'GAME' })
        setPutInTypeList(newputInTypeList);
        newputInTypeList.length > 0 && setPutInType(type => (type && newputInTypeList.some(item => item.value === type) ? type : newputInTypeList[0].value) as 'NOVEL' | 'GAME');
    }, [initialState?.menu])

    useEffect(() => {
        // 刷新页面清除数据
        setIsDqSubmit(false)
        initTargeting()
    }, [])

    useEffect(() => {
        if (creativeTemplateId) {
            let params: any = {
                marketingGoal,
                marketingTargetType: marketingAssetOuterSpec.marketingTargetType,
                marketingCarrierType,
                deliveryMode,
                creativeTemplateId,
                wechatSceneSpecPosition: sceneSpec?.wechatPosition,
                dynamicCreativeType: (deliveryMode === 'DELIVERY_MODE_COMPONENT' && !dynamicCreativeSwitch) ? 'DYNAMIC_CREATIVE_TYPE_PROGRAM' : 'DYNAMIC_CREATIVE_TYPE_COMMON'
            }
            if (automaticSiteEnabled) {
                params.automaticSiteEnabled = automaticSiteEnabled
            } else {
                params.siteSet = siteSet
            }
            params.taskType = putInType
            if (putInType === 'GAME') {
                params.marketingSubGoal = marketingSubGoal
            }
            getCreativeDetails.run(params).then(res => {
                if (res?.adcreativeTemplateStructAdpermits?.length > 0) {
                    let adcreativeTemplateStructAdpermits = res?.adcreativeTemplateStructAdpermits[0]
                    setCreativeTemplateAppellation(adcreativeTemplateStructAdpermits.creativeTemplateAppellation)
                    setCreativeTemplateStyle(adcreativeTemplateStructAdpermits.creativeTemplateStyle)

                    let creativeComponents = adcreativeTemplateStructAdpermits?.creativeComponents || []
                    let result = processData(creativeComponents);

                    let newMaterialData: any = {};
                    let newTextData: any = {};

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

                    setMaterialData(newMaterialData)
                    setTextData(newTextData)
                }
            })
        }
    }, [creativeTemplateId, deliveryMode, dynamicCreativeSwitch, marketingGoal, marketingAssetOuterSpec, marketingCarrierType, siteSet, sceneSpec?.wechatPosition, automaticSiteEnabled, putInType])


    // 获取广告总数
    useEffect(() => {
        if (accountCreateLogs?.length > 0 && marketingAssetOuterSpec?.marketingTargetType && addelivery?.targeting?.length) {
            let adLength = 0
            accountCreateLogs.forEach(item => {
                let productList: any[] = []
                if (['MARKETING_TARGET_TYPE_FICTION', 'MARKETING_TARGET_TYPE_SHORT_DRAMA'].includes(marketingAssetOuterSpec?.marketingTargetType)) { // 小说
                    productList = item?.productList || []
                } else if (['MARKETING_TARGET_TYPE_WECHAT_OFFICIAL_ACCOUNT'].includes(marketingAssetOuterSpec?.marketingTargetType)) { // 公众号
                    productList = item?.wechatChannelList || []
                } else {
                    productList = [{}]
                }
                adLength += productList.length * addelivery.targeting.length
            })
            setAdLength(adLength)
        }
    }, [accountCreateLogs, marketingAssetOuterSpec, addelivery?.targeting])

    /** 存为预设 */
    const severBd = () => {
        if (putInType) {
            localStorage.setItem(putInType === 'GAME' ? 'ADQADV3_GAME' : 'ADQADV3', JSON.stringify({
                addelivery,
                accountCreateLogs,
                materialData,
                textData,
                putInType
            }))
            message.success('存储成功')
        }
    }

    /** 清除 */
    const delBdPlan = ({ isRemoveItem = true }: { isRemoveItem?: boolean }) => {
        if (isRemoveItem) {
            localStorage.removeItem(putInType === 'GAME' ? 'ADQADV3_GAME' : 'ADQADV3')
        }
        setAccountCreateLogs([])
        setMaterialData({})
        setTextData({})
        setAddelivery({
            adgroups: {},
            targeting: [],
            dynamic: {},
            dynamicMaterialDTos: {},
            dynamicCreativesTextDTOS: {},
            mediaType: 0
        })
        setCopyTask({})
        setTableData({})
        setIsDqSubmit(false)
    }

    /**数据回填 */
    useEffect(() => {
        if (putInTypeList?.length > 0) {
            let taskId = sessionStorage.getItem('TASKID3.0')
            let adqAdData = localStorage.getItem(putInType === 'GAME' ? 'ADQADV3_GAME' : 'ADQADV3')
            if (taskId) {
                getSelectTaskDetail.run(taskId).then(res => {
                    if (res) {
                        const { adgroupDTO, accountIdParamVOMap, targetings, dynamicCreativesDTO: { mediaType, ...dynamic }, dynamicCreativesTextDTO, dynamicMaterialDTOS, taskType = 'NOVEL', id, uuid } = res
                        setCopyTask({ copyTaskId: id, uuid })
                        if (putInTypeList.some(item => item.value === taskType)) {
                            setPutInType(() => taskType)
                            let beginDate = adgroupDTO.beginDate
                            let endDate = adgroupDTO.endDate
                            adgroupDTO.bidAllocationMode = adgroupDTO?.bidAllocationMode || 1
                            if (adgroupDTO?.deepConversionSpec) {
                                adgroupDTO.depthConversionEnabled = true
                                if (adgroupDTO?.deepConversionSpec?.deepConversionType === 'DEEP_CONVERSION_WORTH' && !adgroupDTO?.deepConversionSpec?.deepConversionWorthSpec?.roiAllocationMode) {
                                    adgroupDTO.deepConversionSpec = {
                                        ...adgroupDTO.deepConversionSpec,
                                        deepConversionWorthSpec: {
                                            ...adgroupDTO.deepConversionSpec.deepConversionWorthSpec,
                                            roiAllocationMode: 1
                                        }
                                    }
                                }
                            } else {
                                adgroupDTO.depthConversionEnabled = false
                            }
                            if (beginDate && moment(beginDate) < moment()) {
                                beginDate = moment().format('YYYY-MM-DD')
                                endDate = moment().add(7, 'day').format('YYYY-MM-DD')
                                message.warning('请注意，检测投放开始日期小于今天，已自动改成今天，如需修改，请重新设置')
                            }
                            let dynamicGroup: any[] = []
                            // if (dynamic.deliveryMode === 'DELIVERY_MODE_CUSTOMIZE' || (dynamic.deliveryMode === 'DELIVERY_MODE_COMPONENT' && dynamic?.dynamicCreativeType === 'DYNAMIC_CREATIVE_TYPE_COMMON')) {
                            if (dynamic.deliveryMode === 'DELIVERY_MODE_CUSTOMIZE') {
                                dynamicGroup = dynamicMaterialDTOS?.map((item: any[]) => {
                                    let { type, valueJson } = item[0]
                                    let value = JSON.parse(valueJson).value
                                    if (type === 'image') {
                                        return { image_id: { id: value.imageId, url: value.imageUrl, materialType: value.materialType, accountId: value?.accountId } }
                                    } else if (type === 'image_list' || type === 'element_story') {
                                        return { [type]: value.list.map((l: { imageUrl: any; imageId: any; materialType: any, accountId: any }) => ({ url: l.imageUrl, id: l.imageId, materialType: l.materialType, accountId: l?.accountId })) }
                                    } else if (type === 'short_video' || type === 'video') {
                                        let field = type === 'video' ? 'video_id' : 'short_video1'
                                        let videoData: any = {}
                                        videoData[field] = { materialType: value.materialType, url: value.videoUrl, id: value.videoId, keyFrameImageUrl: value?.keyFrameImageUrl, accountId: value?.accountId }
                                        if (value.imageUrl) {
                                            videoData['cover_id'] = { materialType: value.materialCoverType, url: value.imageUrl, id: value.iamgeId, accountId: value?.accountId }
                                        }
                                        return videoData
                                    } else {
                                        return {}
                                    }
                                })
                            } else { // 组件化创意
                                dynamicGroup = dynamicMaterialDTOS?.map((item: any[]) => {
                                    return {
                                        list: item?.map((i: any) => {
                                            const { type, valueJson } = i
                                            const { value, componentId, componentValue } = JSON.parse(valueJson)
                                            if (componentId) {
                                                return componentValue
                                            } else if (type === 'image') {
                                                return { id: value.imageId, url: value.imageUrl, materialType: value.materialType, accountId: value?.accountId }
                                            } else if (type === 'image_list') {
                                                return value.list.map((l: { imageUrl: any; imageId: any; materialType: any, accountId: any }) => ({ url: l.imageUrl, id: l.imageId, materialType: l.materialType, accountId: l?.accountId }))
                                            } else if (type === 'video') {
                                                return { materialType: value.materialType, url: value.videoUrl, id: value.videoId, keyFrameImageUrl: value?.keyFrameImageUrl, accountId: value?.accountId }
                                            } else {
                                                return {}
                                            }
                                        })
                                    }
                                })
                            }

                            let isConversion = false
                            setAccountCreateLogs(Object.keys(accountIdParamVOMap || {}).map(accountId => {
                                const { productDTOS, wechatOfficialAccountsVO, pageList, landingPageVOS, userActionSetsList, excludeUnionPositionPackages, unionPositionPackages, conversionInfo, wechatChannelVO, wechatAppletList, customAudience, excludedCustomAudience } = accountIdParamVOMap[accountId]
                                let data: PULLIN.AccountCreateLogsProps = {
                                    accountId: Number(accountId),
                                    productList: productDTOS
                                }
                                if (wechatOfficialAccountsVO) {
                                    data.wechatChannelList = [wechatOfficialAccountsVO]
                                }
                                if (pageList || landingPageVOS || wechatAppletList) {
                                    data.pageList = pageList || landingPageVOS || wechatAppletList?.map((item: { appletName: any; id: any }) => ({ ...item, pageName: item.appletName, pageId: item.id }))
                                }
                                if (userActionSetsList) {
                                    data.userActionSetsList = userActionSetsList
                                }
                                if (excludeUnionPositionPackages) {
                                    data.excludeUnionPositionPackage = excludeUnionPositionPackages
                                }
                                if (unionPositionPackages) {
                                    data.unionPositionPackage = unionPositionPackages
                                }
                                if (conversionInfo) {
                                    isConversion = true
                                    data.newConversionList = [conversionInfo]
                                }
                                if (wechatChannelVO) {
                                    data.videoChannelList = [wechatChannelVO]
                                }
                                if (customAudience) {
                                    data.customAudience = customAudience
                                }
                                if (excludedCustomAudience) {
                                    data.excludedCustomAudience = excludedCustomAudience
                                }
                                return data
                            }))

                            if (dynamic.deliveryMode === 'DELIVERY_MODE_COMPONENT' && dynamic?.dynamicCreativeType === 'DYNAMIC_CREATIVE_TYPE_COMMON') {
                                dynamic.dynamicCreativeSwitch = true
                            }

                            setAddelivery({
                                adgroups: { ...adgroupDTO, isConversion, adgroupName: adgroupDTO.adgroupName + '_副本' + randomString(true, 3, 5), endDate, beginDate, deliveryMethod: adgroupDTO?.deliveryMethod || 'NORMAL' },
                                targeting: targetings.map((item: any) => {
                                    const { targetingName, ...targeting } = item
                                    return { targetingName, targeting }
                                }),
                                dynamic,
                                dynamicMaterialDTos: dynamicGroup.length > 0 ? { dynamicGroup } : {},
                                dynamicCreativesTextDTOS: dynamicCreativesTextDTO,
                                mediaType: mediaType || 0
                            })
                        } else {
                            message.error(`没有${taskType === 'NOVEL' ? '小说/短剧' : taskType === 'GAME' ? '游戏' : taskType}投放权限`)
                        }
                        sessionStorage.removeItem('TASKID3.0')
                    }
                })
            } else if (adqAdData) {
                const { addelivery, accountCreateLogs, materialData, textData } = JSON.parse(adqAdData)
                if (addelivery?.adgroups && Object.keys(addelivery.adgroups).length) {
                    if (addelivery?.adgroups?.beginDate && moment(addelivery?.adgroups?.beginDate) < moment()) {
                        addelivery.adgroups.beginDate = moment().format('YYYY-MM-DD')
                        message.warning('请注意，检测投放开始日期小于今天，已自动改成今天，如需修改，请重新设置')
                    }
                    if (addelivery?.adgroups?.endDate && moment(addelivery?.adgroups?.endDate) < moment()) {
                        addelivery.adgroups.endDate = moment().format('YYYY-MM-DD')
                        message.warning('请注意，检测投放结束日期小于今天，已自动改成今天，如需修改，请重新设置')
                    }
                    addelivery.adgroups.bidAllocationMode = addelivery.adgroups?.bidAllocationMode || 1
                    if (addelivery?.adgroups?.deepConversionSpec) {
                        if (addelivery?.adgroups?.deepConversionSpec?.deepConversionType === 'DEEP_CONVERSION_WORTH' && !addelivery?.adgroups?.deepConversionSpec?.deepConversionWorthSpec?.roiAllocationMode) {
                            addelivery.adgroups.deepConversionSpec = {
                                ...addelivery.adgroups.deepConversionSpec,
                                deepConversionWorthSpec: {
                                    ...addelivery.adgroups.deepConversionSpec.deepConversionWorthSpec,
                                    roiAllocationMode: 1
                                }
                            }
                        }
                    }
                }
                if (addelivery?.adgroups && Object.keys(addelivery?.adgroups)?.length && !addelivery?.adgroups?.deliveryMethod) {
                    addelivery.adgroups.deliveryMethod = 'NORMAL'
                }
                setAddelivery({ ...addelivery })
                setAccountCreateLogs(accountCreateLogs)
                setMaterialData(materialData)
                setTextData(textData)
            }
        }
    }, [putInType, putInTypeList])

    // 预览
    const preview = () => {
        if (accountCreateLogs?.length === 0) {
            message.error('请先选择媒体账户')
            return
        }
        const { adgroups, targeting, dynamic, dynamicMaterialDTos, dynamicCreativesTextDTOS, mediaType } = addelivery
        if (["OPTIMIZATIONGOAL_FOLLOW", "OPTIMIZATIONGOAL_PAGE_SCAN_CODE"].includes(adgroups?.optimizationGoal)) {
            if (!adgroups?.depthConversionEnabled) {
                message.error('应公司要求，”关注和加企微“请开启深度转化优化')
                return
            }
            if (adgroups?.deepConversionSpec?.deepConversionWorthSpec?.expectedRoi < 0.03) {
                notification.warning({
                    message: '请注意',
                    description: `当前ROI出价小于0.03，当前${adgroups?.deepConversionSpec?.deepConversionWorthSpec?.expectedRoi}`
                })
            }
        }
        if (!(adgroups && Object.keys(adgroups).length)) {
            message.error('请先配置广告信息')
            return
        }
        if (!(targeting?.length)) {
            message.error('请先添加定向')
            return
        }
        if (!(dynamic && Object.keys(dynamic).length)) {
            message.error('请先配置创意')
            return
        }
        if ((materialData && Object.keys(materialData).length) && !(dynamicMaterialDTos && Object.keys(dynamicMaterialDTos).length)) {
            message.error('请先配置创意素材')
            return
        }
        if ((textData && Object.keys(textData).length) && !(dynamicCreativesTextDTOS && Object.keys(dynamicCreativesTextDTOS).length)) {
            message.error('请先配置创意文案')
            return
        }
        if (['MARKETING_TARGET_TYPE_FICTION', 'MARKETING_TARGET_TYPE_SHORT_DRAMA'].includes(marketingAssetOuterSpec?.marketingTargetType) && !accountCreateLogs?.some(item => item?.productList?.length)) {
            message.error(marketingAssetOuterSpec?.marketingTargetType === 'MARKETING_TARGET_TYPE_FICTION' ? '请先选择小说' : '请先选择短剧')
            return
        }
        if ((['MARKETING_TARGET_TYPE_WECHAT_OFFICIAL_ACCOUNT'].includes(marketingAssetOuterSpec?.marketingTargetType) || marketingCarrierType === 'MARKETING_CARRIER_TYPE_WECHAT_OFFICIAL_ACCOUNT' || dynamic?.creativeComponents?.brand?.[0]?.value?.jumpInfo?.pageType === 'PAGE_TYPE_WECHAT_OFFICIAL_ACCOUNT_DETAIL') && !accountCreateLogs?.some(item => item?.wechatChannelList?.length)) {
            message.error('请先选择公众号')
            return
        }
        if (creativeComponents?.brand?.[0]?.value?.jumpInfo?.pageType === 'PAGE_TYPE_WECHAT_CHANNELS_PROFILE' && !accountCreateLogs?.some(item => item?.videoChannelList?.length)) {
            message.error('请先选择视频号')
            return
        }
        if (isConversion && !accountCreateLogs?.some(item => item?.newConversionList?.length)) {
            message.error('请先选择转化归因')
            return
        }

        if (!accountCreateLogs?.some(item => item?.pageList?.length) && !['PAGE_TYPE_WECHAT_MINI_GAME'].includes(dynamic?.creativeComponents?.mainJumpInfo?.[0]?.value?.pageType)) {
            message.error('请先选择落地页')
            return
        }

        let newTableData: any = {}
        let newAdCount = 0, newdynamicCount = 0
        const textType = dynamicCreativesTextDTOS.type
        const textDto = dynamicCreativesTextDTOS?.dynamicCreativesTextDetailDTOList || []
        const textDtoLenth = textDto.length
        const dynamicGroupLength = dynamicMaterialDTos?.dynamicGroup?.length || 0
        let newDynamicGroup: any = []
        if (![910].includes(dynamic.creativeTemplateId)) {
            newDynamicGroup = dynamicMaterialDTos?.dynamicGroup || []
            if (newDynamicGroup.length > 0 && [0, 1, 2, 3, 4].includes(textType)) {
                if (textType === 0) {
                    newDynamicGroup = newDynamicGroup.map((item: any) => ({ ...item, textDto: textDto?.[0] }))
                } else if (textType === 1) {
                    newDynamicGroup = newDynamicGroup.map((item: any, index: number) => ({ ...item, textDto: textDto?.[index] }))
                } else if (textType === 2) {
                    newDynamicGroup = newDynamicGroup.map((item: any, index: number) => ({ ...item, textDto: textDto?.[index % textDtoLenth] }))
                } else if ((textType === 3 && mediaType === 0) || (textType === 4 && mediaType === 1) || (textType === 4 && mediaType === 3)) {
                    newDynamicGroup = cartesianProduct(newDynamicGroup, textDto || [{}]).map((item) => {
                        const [dynamicGroup, textDtoData] = item
                        return {
                            ...dynamicGroup as any,
                            textDto: textDtoData
                        }
                    })
                }
            }
        }
        // 创意组平均分配到广告逻辑
        let averageAdDynamicList: any[] = []
        if ((mediaType === 1 || mediaType === 2 || mediaType === 3) && newDynamicGroup.length) {
            let adLength = 0
            accountCreateLogs.forEach(item => {
                let productList: any[] = []
                if (['MARKETING_TARGET_TYPE_FICTION', 'MARKETING_TARGET_TYPE_SHORT_DRAMA'].includes(marketingAssetOuterSpec?.marketingTargetType)) { // 小说 短剧
                    productList = item?.productList || []
                } else if (['MARKETING_TARGET_TYPE_WECHAT_OFFICIAL_ACCOUNT'].includes(marketingAssetOuterSpec?.marketingTargetType)) { // 公众号
                    productList = item?.wechatChannelList || []
                } else {
                    productList = [{}]
                }
                adLength += productList.length * targeting.length
            })
            if (mediaType === 1) {
                if (textType === 4) {
                    if (adLength > newDynamicGroup.length) {
                        message.error(`创意组分配规则选择“平均分配到广告”时，创意组总数必须大于等于广告总数。当前创意组数量：${newDynamicGroup.length}，广告数量：${adLength}`)
                        return
                    }
                    averageAdDynamicList = splitArrayIntoRandomChunks(newDynamicGroup, adLength)
                } else {
                    if (adLength > dynamicGroupLength) {
                        message.error(`创意组分配规则选择“平均分配到广告”时，创意组总数必须大于等于广告总数。当前创意组数量：${dynamicGroupLength}，广告数量：${adLength}`)
                        return
                    }
                    averageAdDynamicList = distributeArray(newDynamicGroup, adLength)
                }
            } else if (mediaType === 2) {
                if (adLength < dynamicGroupLength) {
                    message.error(`创意组分配规则选择“顺序分配到广告”时，创意组总数必须小于等于广告总数。当前创意组数量：${dynamicGroupLength}，广告数量：${adLength}`)
                    return
                }
            } else if (mediaType === 3) {
                const dynamicDataLength = textType === 4 ? newDynamicGroup.length : dynamicGroupLength
                if (accountCreateLogs.some(item => {
                    let productList: any[] = []
                    if (['MARKETING_TARGET_TYPE_FICTION', 'MARKETING_TARGET_TYPE_SHORT_DRAMA'].includes(marketingAssetOuterSpec?.marketingTargetType)) { // 小说 短剧
                        productList = item?.productList || []
                    } else if (['MARKETING_TARGET_TYPE_WECHAT_OFFICIAL_ACCOUNT'].includes(marketingAssetOuterSpec?.marketingTargetType)) { // 公众号
                        productList = item?.wechatChannelList || []
                    } else {
                        productList = [{}]
                    }
                    const adLength = productList.length * targeting.length
                    if (adLength > dynamicDataLength) {
                        message.error(`创意组分配规则选择“账号下平均分配到广告”时，创意组总数必须大于等于每个账号广告总数。当前创意组数量：${dynamicDataLength}，当前账号（${item.accountId}）下广告数量：${adLength}`)
                        return true
                    }
                    return false
                })) {
                    return
                }
            }
        }
        if (textType === 1) {
            if (dynamicGroupLength !== textDtoLenth) {
                message.error(`当前创意文案是“创意组一一对应”模式，创意组总数（${dynamicGroupLength}）要等于创意文案总数（${textDtoLenth}）`)
                return
            }
            if (!dynamicCreativesTextDTOS.dynamicCreativesTextDetailDTOList.every((item: {}) => item && Object.keys(item).length)) {
                message.error('创意文案配置错误，内容空')
                return
            }
        } else if (textType === 5) {
            if (dynamicGroupLength * accountCreateLogs.length !== textDtoLenth) {
                message.error(`创意文案配置错误，内容数量和所有创意数量对不上，所有创意数量：${dynamicGroupLength * accountCreateLogs.length}，文案数量：${textDtoLenth}`)
                return
            }
        }
        const mainJumpInfoLength = dynamic?.creativeComponents?.mainJumpInfo?.length || 1
        // 落地页平均分配判断数量
        if ([910].includes(dynamic.creativeTemplateId) && dynamic?.landingPageType === 1) {
            const targetingLength = targeting.length
            if (accountCreateLogs.some(item => {
                const productListLength = item?.productList?.length || 1
                const total = targetingLength * productListLength
                const pageLength = item.pageList.length
                if (mainJumpInfoLength > 1) {
                    if (!(total * mainJumpInfoLength <= pageLength && pageLength % mainJumpInfoLength === 0)) {
                        message.error(`当前${item.accountId}下的广告总数是：${total}，落地页组数是：${mainJumpInfoLength}，平均分配需要落地页总数（${pageLength}）要大于${total * mainJumpInfoLength}并且要是${mainJumpInfoLength}倍数`)
                        return true
                    }
                } else {
                    if (total > pageLength) {
                        message.error(`当前${item.accountId}下的广告总数（${total}）大于落地页总数（${pageLength}），平均分配需要落地页总数大于广告总数`)
                        return true
                    }
                }
                return false
            })) {
                return
            }
        }
        let accountIndex = 0, accountIndex1 = 0, accountIndex2 = 0
        accountCreateLogs.forEach(item => {
            let productList: any[] = [{}]
            if (['MARKETING_TARGET_TYPE_FICTION', 'MARKETING_TARGET_TYPE_SHORT_DRAMA'].includes(marketingAssetOuterSpec?.marketingTargetType)) { // 小说
                productList = item?.productList || []
            } else if (['MARKETING_TARGET_TYPE_WECHAT_OFFICIAL_ACCOUNT'].includes(marketingAssetOuterSpec?.marketingTargetType)) { // 公众号
                productList = item?.wechatChannelList || []
            }
            if (mediaType === 3) {
                const adLength = productList.length * targeting.length
                if (textType === 4) {
                    averageAdDynamicList = splitArrayIntoRandomChunks(newDynamicGroup, adLength)
                } else {
                    averageAdDynamicList = distributeArray(newDynamicGroup, adLength)
                }
            }

            const data = cartesianProduct(productList, targeting).map((newD, dindex) => {
                const [productDto, targetDto, index] = newD
                const suffix = '_' + item.accountId + '_' + index
                const averageAdDynamic = (mediaType === 3 ? averageAdDynamicList?.[dindex] : averageAdDynamicList?.[accountIndex]) || []
                const dat: any = {
                    id: item.accountId + '_' + index,
                    accountId: item.accountId,                    // 账户
                    userActionSetsList: item.userActionSetsList,  // 数据源
                    conversionList: item.newConversionList,       // 转化归因
                    pageListDto: item.pageList,                   // 落地页
                    productDto,                                   // 商品
                    targetDto: {                                  // 定向
                        ...targetDto,
                        targetingName: targetDto.targetingName + suffix
                    },
                    adgroupsDto: {                                // 广告信息
                        ...adgroups,
                        adgroupName: adgroups.adgroupName + suffix
                    },
                    dynamicDto: dynamic,                          // 创意信息
                    averageAdDynamic,
                    rowSpan: ((mediaType === 1 || mediaType === 3) && textType !== 4) ? averageAdDynamic.length : ([910].includes(dynamic.creativeTemplateId) ? item.pageList?.length / mainJumpInfoLength : (textType === 3 ? textDtoLenth * dynamicGroupLength : dynamicGroupLength)) || 1
                }
                if (marketingCarrierType === 'MARKETING_CARRIER_TYPE_WECHAT_OFFICIAL_ACCOUNT') { // 营销载体
                    dat.marketingCarrierDto = item?.wechatChannelList
                }
                accountIndex += 1
                return dat
            })

            newAdCount += data.length
            let newData: any[] = []
            // 激励
            if ([910].includes(dynamic.creativeTemplateId)) {
                if (dynamic?.landingPageType === 1) {
                    const averageAdPageList: any[] = groupArr(item.pageList, productList.length * targeting.length, mainJumpInfoLength)
                    data.forEach((item, aIndex) => {
                        const aPageList: any[] = averageAdPageList[aIndex]
                        aPageList.forEach((page, index) => {
                            newData.push({
                                ...item,
                                id: item.id + '_' + index,
                                pageListDto: page,
                                dynamicDto: {
                                    ...item.dynamicDto,
                                    dynamicCreativeName: item.dynamicDto.dynamicCreativeName + index
                                },
                                rowSpan: index === 0 ? aPageList.length : 0,
                                adLength: data.length,
                                isRowSpan: true
                            })
                        })

                    })
                } else {
                    newData = cartesianProduct(data, distributeArray(item.pageList, item.pageList.length / mainJumpInfoLength)).map((item, index) => {
                        const [d1, pageList, num] = item
                        return {
                            ...d1,
                            id: d1.id + '_' + index,
                            pageListDto: pageList,
                            dynamicDto: {
                                ...d1.dynamicDto,
                                dynamicCreativeName: d1.dynamicDto.dynamicCreativeName + num
                            }
                        }
                    })
                }
            } else {
                if (mediaType === 1 || mediaType === 3) {
                    data.forEach(item => {
                        const { averageAdDynamic, ...ad } = item
                        if (textType === 3) {
                            const rowSpan = textDtoLenth * averageAdDynamic.length
                            cartesianProduct(textDto, averageAdDynamic).forEach((taad: any, index) => {
                                const [textValue, aad] = taad
                                newData.push({
                                    ...ad,
                                    id: ad.id + '_' + index,
                                    dynamicGroup: aad,
                                    textDto: textValue,
                                    rowSpan: index === 0 ? rowSpan : 0,
                                    adLength: data.length,
                                    isRowSpan: true
                                })
                            })
                        } else if (textType === 4) {
                            averageAdDynamic.forEach((aad: any, index: number) => {
                                newData.push({
                                    ...ad,
                                    id: ad.id + '_' + index,
                                    dynamicGroup: aad,
                                    textDto: aad?.textDto,
                                    adLength: data.length,
                                    rowSpan: index === 0 ? averageAdDynamic.length : 0,
                                    isRowSpan: true
                                })
                            })
                        } else {
                            averageAdDynamic.forEach((aad: any, index: number) => {
                                newData.push({
                                    ...ad,
                                    id: ad.id + '_' + index,
                                    dynamicGroup: aad,
                                    textDto: textType === 2 ? textDto?.[index % textDtoLenth] : textType === 5 ? textDto?.[accountIndex2] : aad?.textDto,
                                    adLength: data.length,
                                    ...(mediaType === 3 ? {
                                        rowSpan: index === 0 ? averageAdDynamic.length : 0,
                                        isRowSpan: true
                                    } : {})
                                })
                                accountIndex2 += 1
                            })
                        }
                    })
                } else if (mediaType === 2) {
                    data.forEach((item) => {
                        const { averageAdDynamic, ...ad } = item
                        if (textType === 3) {
                            cartesianProduct(textDto, [newDynamicGroup[accountIndex1 % newDynamicGroup.length]]).forEach((taad: any, i) => {
                                const [textValue, aad, index] = taad
                                newData.push({
                                    ...ad,
                                    id: ad.id + '_' + index,
                                    dynamicGroup: aad,
                                    textDto: textValue,
                                    rowSpan: i === 0 ? textDto.length : 0,
                                    adLength: data.length,
                                    isRowSpan: true
                                })
                            })
                        } else {
                            const { textDto: nowTextDto, ...dynamicGroup } = newDynamicGroup[accountIndex1 % newDynamicGroup.length]
                            newData.push({
                                ...ad,
                                dynamicGroup,
                                textDto: textType === 2 ? textDto?.[0] : nowTextDto,
                                rowSpan: 1,
                                adLength: data.length
                            })
                        }
                        accountIndex1 += 1
                    })
                } else { // 全账号复用创意组 所有广告一样的创意组
                    newData = cartesianProduct(data, newDynamicGroup.length > 0 ? newDynamicGroup : [{}]).map((item, index) => {
                        let [d1, group] = item
                        return {
                            ...d1,
                            id: d1.id + '_' + index,
                            dynamicGroup: group,
                            textDto: (group as any)?.textDto,
                            adLength: data.length
                        }
                    })
                }
            }
            newdynamicCount = newdynamicCount + newData.length
            newTableData[item.accountId] = newData
        })
        setAdCount(newAdCount)
        setDynamicCount(newdynamicCount)
        setActiveKey(accountCreateLogs?.[0].accountId?.toString())
        console.log('newTableData-->', newTableData)
        setTableData(newTableData)
    }

    // 提交
    const onSubmit = (values: any) => {
        const { adgroups, targeting, dynamic, dynamicMaterialDTos, dynamicCreativesTextDTOS, mediaType } = JSON.parse(JSON.stringify(addelivery)) as PULLIN.AddeliveryProps

        let dynamicMaterialDTOS = []
        // if (dynamic.deliveryMode === 'DELIVERY_MODE_CUSTOMIZE' || dynamic?.dynamicCreativeSwitch) {
        if (dynamic.deliveryMode === 'DELIVERY_MODE_CUSTOMIZE') {
            if ((materialData && Object.keys(materialData).length && dynamicMaterialDTos && Object.keys(dynamicMaterialDTos).length)) {
                const mType = Object.keys(materialData)[0];
                dynamicMaterialDTOS = dynamicMaterialDTos.dynamicGroup?.map((item: any) => {
                    if (mType === 'image') {
                        return [{
                            type: mType,
                            valueJson: JSON.stringify({
                                value: {
                                    imageUrl: item?.image_id?.url,
                                    imageId: item?.image_id?.id,
                                    materialType: item?.image_id?.materialType,
                                    accountId: item?.image_id?.accountId
                                }
                            })
                        }]
                    } else if (mType === 'image_list' || mType === 'element_story') {
                        let key = 'image_list'
                        if (mType === 'element_story') {
                            key = 'element_story'
                        }
                        const list = item?.[key]?.map((l: any) => {
                            return {
                                imageUrl: l?.url,
                                imageId: l?.id,
                                materialType: l?.materialType,
                                accountId: l?.accountId
                            }
                        })
                        return [{
                            type: mType,
                            valueJson: JSON.stringify({
                                value: {
                                    list
                                }
                            })
                        }]
                    } else if (['short_video', 'video'].includes(mType)) {
                        const value: any = {
                            materialType: item?.video_id?.materialType || item?.short_video1?.materialType || 0,
                            videoUrl: item?.video_id?.url || item?.short_video1?.url,
                            videoId: item?.video_id?.id || item?.short_video1?.id,
                            keyFrameImageUrl: item?.video_id?.keyFrameImageUrl || item?.short_video1?.keyFrameImageUrl,
                            accountId: item?.video_id?.accountId || item?.short_video1?.accountId,
                        }
                        if (item?.cover_id?.url) {
                            value.imageUrl = item?.cover_id?.url
                            value.imageId = item?.cover_id?.id
                            value.materialCoverType = item?.cover_id?.materialType
                            value.accountId = item?.cover_id?.accountId
                        }
                        return [{
                            type: mType,
                            valueJson: JSON.stringify({
                                value
                            })
                        }]
                    }
                    return [{
                        type: mType,
                        valueJson: ''
                    }]
                })
            }
        } else {
            if (dynamicMaterialDTos && Object.keys(dynamicMaterialDTos).length) {
                dynamicMaterialDTOS = dynamicMaterialDTos.dynamicGroup?.map((item: { list: any[] }) => {
                    return item.list.map(l => {
                        if (l.materialType === 4) {
                            return {
                                type: l?.componentSubType?.includes('IMAGE_LIST') ? 'image_list' : l?.keyFrameImageUrl ? 'video' : 'image',
                                valueJson: JSON.stringify({
                                    componentId: l.id,
                                    componentValue: l
                                })
                            }
                        }
                        if (Array.isArray(l)) {
                            return {
                                type: 'image_list',
                                valueJson: JSON.stringify({
                                    value: {
                                        list: l?.map((i: any) => {
                                            return {
                                                imageUrl: i?.url,
                                                imageId: i?.id,
                                                materialType: i?.materialType,
                                                accountId: i?.accountId
                                            }
                                        })
                                    }
                                })
                            }
                        } else if (l?.url?.includes('mp4') || l?.keyFrameImageUrl) {
                            return {
                                type: 'video',
                                valueJson: JSON.stringify({
                                    value: {
                                        materialType: l?.materialType,
                                        videoUrl: l?.url,
                                        videoId: l?.id,
                                        keyFrameImageUrl: l?.keyFrameImageUrl,
                                        accountId: l?.accountId
                                    }
                                })
                            }
                        } else {
                            return {
                                type: 'image',
                                valueJson: JSON.stringify({
                                    value: {
                                        imageUrl: l?.url,
                                        imageId: l?.id,
                                        materialType: l?.materialType,
                                        accountId: l?.accountId
                                    }
                                })
                            }
                        }
                    })
                })
            }
        }
        const accountIdParamDTOMap: any = {}
        accountCreateLogs.forEach(item => {
            const { pageList, productList, userActionSetsList, unionPositionPackage, excludeUnionPositionPackage, accountId, wechatChannelList, newConversionList, videoChannelList, customAudience, excludedCustomAudience } = item

            const userActionSetsListDto = userActionSetsList?.map((item: any) => ({ id: item?.userActionSetId, type: item?.type })) // dataSourceId

            const map: any = {
                userActionSetsList: userActionSetsListDto,
                unionPositionPackage: unionPositionPackage?.map(item => item.unionPackageId),
                excludeUnionPositionPackage: excludeUnionPositionPackage?.map(item => item.unionPackageId),
            }
            if (!['PAGE_TYPE_WECHAT_MINI_GAME'].includes(dynamic?.creativeComponents?.mainJumpInfo?.[0]?.value?.pageType)) {
                const pageMap: { [x: string]: any } = {}
                map.pageList = pageList?.map((item: { pageId: any, pageName?: string }) => {
                    pageMap[item.pageId] = item?.pageName
                    return item.pageId
                })
                if (Object.keys(pageMap).length) {
                    map.pageMap = pageMap
                }
            }
            if (productList && ['MARKETING_TARGET_TYPE_FICTION', 'MARKETING_TARGET_TYPE_SHORT_DRAMA'].includes(marketingAssetOuterSpec?.marketingTargetType)) {
                map.productDTOS = productList?.map(item => {
                    return { productId: item.marketingAssetId }
                })
            }
            if (wechatChannelList && (['MARKETING_TARGET_TYPE_WECHAT_OFFICIAL_ACCOUNT'].includes(marketingAssetOuterSpec?.marketingTargetType) || marketingCarrierType === 'MARKETING_CARRIER_TYPE_WECHAT_OFFICIAL_ACCOUNT' || dynamic?.creativeComponents?.brand?.[0]?.value?.jumpInfo?.pageType === 'PAGE_TYPE_WECHAT_OFFICIAL_ACCOUNT_DETAIL')) {
                map.wechatChannelId = wechatChannelList?.[0]?.wechatOfficialAccountId
            }
            if (newConversionList && isConversion) {
                map.conversionId = newConversionList?.[0]?.conversionId
            }
            if (videoChannelList && creativeComponents?.brand?.[0]?.value?.jumpInfo?.pageType === 'PAGE_TYPE_WECHAT_CHANNELS_PROFILE') {
                map.videoChannelId = videoChannelList?.[0]?.wechatChannelsAccountId
            }
            if (customAudience?.length) {
                map.customAudience = customAudience
            }
            if (excludedCustomAudience?.length) {
                map.excludedCustomAudience = excludedCustomAudience
            }

            accountIdParamDTOMap[accountId] = map
        })
        dynamic.dynamicCreativeType = 'DYNAMIC_CREATIVE_TYPE_COMMON'
        if (dynamic.deliveryMode === 'DELIVERY_MODE_COMPONENT') {
            dynamic.dynamicCreativeType = dynamic?.dynamicCreativeSwitch ? 'DYNAMIC_CREATIVE_TYPE_COMMON' : 'DYNAMIC_CREATIVE_TYPE_PROGRAM'
        }
        const dynamicCreativesDTO = { ...dynamic, mediaType }
        if (dynamic.deliveryMode === 'DELIVERY_MODE_COMPONENT' && !dynamic?.dynamicCreativeSwitch) {
            dynamicCreativesDTO.creativeTemplateId = 711
        }
        delete adgroups?.isConversion  // 前端控制新链路字段
        const params = {
            ...values,
            adgroupDTO: adgroups,
            targetings: targeting.map(item => ({ targetingName: item.targetingName, ...item?.targeting || {} })),
            dynamicCreativesDTO,
            dynamicCreativesTextDTOS,
            dynamicMaterialDTOS,
            accountIdParamDTOMap,
            taskType: putInType,
            ...copyTask
        }
        if (values?.submitRule !== 0) {
            createAdgroupTaskV2.run(params).then(res => {
                if (res) {
                    Modal.success({
                        content: '任务提交成功',
                        bodyStyle: { fontWeight: 700 },
                        okText: '跳转任务列表',
                        closable: true,
                        onOk: () => {
                            sessionStorage.setItem('CAMPV3', values?.taskName)
                            window.location.href = '/#/launchSystemV3/tencentAdPutIn/taskList'
                        },
                        onCancel: () => {
                            setSubVisible(false)
                        }
                    })
                }
            })
        } else {
            delete params?.submitRule
            createAdgroupTask.run(params).then(res => {
                if (res) {
                    Modal.success({
                        content: '任务提交成功',
                        bodyStyle: { fontWeight: 700 },
                        okText: '跳转任务列表',
                        closable: true,
                        onOk: () => {
                            sessionStorage.setItem('CAMPV3', values?.taskName)
                            window.location.href = '/#/launchSystemV3/tencentAdPutIn/taskList'
                        },
                        onCancel: () => {
                            setSubVisible(false)
                            setIsDqSubmit(true)
                        }
                    })
                }
            })
        }
    }

    const clearData = () => {
        setTableData({})
    }

    return <Space direction="vertical" style={{ width: '100%' }}>
        <Spin spinning={createAdgroupTask.loading || getSelectTaskDetail.loading || getCreativeDetails.loading}>
            <Card
                size="small"
                title={<Space size={18}>
                    <div className={style.cardTitle}>配置区</div>
                    {putInTypeList.length >= 1 && <Radio.Group
                        buttonStyle="solid"
                        value={putInType}
                        onChange={(e) => {
                            setPutInType(e.target.value)
                            delBdPlan({ isRemoveItem: false })
                        }}
                        options={putInTypeList}
                        optionType='button'
                        size="small"
                    />}
                </Space>}
                className={style.createAd}
            >
                <Space wrap>
                    <SelectAccount
                        setAccountCreateLogs={setAccountCreateLogs}
                        accountCreateLogs={accountCreateLogs}
                        setOwnerAccountId={setOwnerAccountId}
                        ownerAccountId={ownerAccountId}
                        putInType={putInType}
                        onChange={(e, isClear) => {
                            setIsDqSubmit(false)
                            clearData()
                            setAccountCreateLogs(e?.map((item: any) => ({ accountId: item.accountId })) || []);
                            if (isClear) {
                                const newAddelivery = JSON.parse(JSON.stringify(addelivery))
                                newAddelivery.dynamicMaterialDTos = {}
                                newAddelivery.dynamicCreativesTextDTOS = {}
                                setAddelivery(newAddelivery)
                            } else if (addelivery?.dynamicCreativesTextDTOS?.type === 5) {
                                const newAddelivery = JSON.parse(JSON.stringify(addelivery))
                                newAddelivery.dynamicCreativesTextDTOS = {}
                                setAddelivery(newAddelivery)
                            }
                        }}
                        dynamicGroup={addelivery?.dynamicMaterialDTos?.dynamicGroup}
                        deliveryMode={deliveryMode}
                        mType={Object.keys(materialData)[0]}
                    />

                    {accountCreateLogs?.length > 0 && <>
                        {['MARKETING_TARGET_TYPE_FICTION', 'MARKETING_TARGET_TYPE_SHORT_DRAMA'].includes(marketingAssetOuterSpec?.marketingTargetType) && <Button type="primary" danger={!accountCreateLogs?.some(item => item?.productList?.length)} onClick={() => { setGoodsVisible(true) }}>{accountCreateLogs?.some(item => item?.productList?.length) ? <>重新选择{marketingAssetOuterSpec?.marketingTargetType === 'MARKETING_TARGET_TYPE_FICTION' ? '小说' : '短剧'} <CheckOutlined style={{ color: '#FFFFFF' }} /></> : `请选择${marketingAssetOuterSpec?.marketingTargetType === 'MARKETING_TARGET_TYPE_FICTION' ? '小说' : '短剧'}`}</Button>}
                        {(marketingAssetOuterSpec?.marketingTargetType === 'MARKETING_TARGET_TYPE_WECHAT_OFFICIAL_ACCOUNT' || marketingCarrierType === 'MARKETING_CARRIER_TYPE_WECHAT_OFFICIAL_ACCOUNT' || creativeComponents?.brand?.[0]?.value?.jumpInfo?.pageType === 'PAGE_TYPE_WECHAT_OFFICIAL_ACCOUNT_DETAIL') && <Button type="primary" danger={!accountCreateLogs?.some(item => item?.wechatChannelList?.length)} onClick={() => { setWechatVisible(true) }}>{accountCreateLogs?.some(item => item?.wechatChannelList?.length) ? <>重新选择公众号 <CheckOutlined style={{ color: '#FFFFFF' }} /></> : '请选择公众号'}</Button>}
                        {creativeComponents?.brand?.[0]?.value?.jumpInfo?.pageType === 'PAGE_TYPE_WECHAT_CHANNELS_PROFILE' && <Button type="primary" danger={!accountCreateLogs?.some(item => item?.videoChannelList?.length)} onClick={() => { setChannelsProfileVisible(true) }}>{accountCreateLogs?.some(item => item?.videoChannelList?.length) ? <>重新选择视频号 <CheckOutlined style={{ color: '#FFFFFF' }} /></> : '请选择视频号'}</Button>}
                        {!isConversion ?
                            <Button onClick={() => { setSourceVisible(true) }}>精准匹配归因（选填）{accountCreateLogs?.some(item => item?.userActionSetsList?.length) && <CheckOutlined style={{ color: accountCreateLogs?.every(item => item?.userActionSetsList?.length) ? '#1890ff' : '#52C41A' }} />}</Button>
                            :
                            <Button type="primary" danger={!accountCreateLogs?.some(item => item?.newConversionList?.length)} onClick={() => { setConversionVisible(true) }}>{accountCreateLogs?.some(item => item?.newConversionList?.length) ? <>重新选择转化归因<CheckOutlined style={{ color: '#FFF' }} /></> : '请选择转化归因'}</Button>
                        }
                        {((siteSet?.includes('SITE_SET_MOBILE_UNION') || automaticSiteEnabled) && addelivery?.adgroups?.deliveryMethod !== 'SMART') && <Button onClick={() => { setPositionPackageVisible(true) }}>优量汇流量包（选填）{accountCreateLogs?.some(item => item?.unionPositionPackage?.length || item?.excludeUnionPositionPackage?.length) && <CheckOutlined style={{ color: accountCreateLogs?.every(item => item?.unionPositionPackage?.length && item?.excludeUnionPositionPackage?.length) ? '#1890ff' : '#52C41A' }} />}</Button>}
                        {((targetRules?.rules && targetRules?.rules?.length > 0) ? targetRules?.rules?.includes('excludedCustomAudience') : true) && <Button onClick={() => { setAudienceVisible(true) }}>自定义人群包（选填）{accountCreateLogs?.some(item => item?.customAudience?.length || item?.excludedCustomAudience?.length) && <CheckOutlined style={{ color: accountCreateLogs?.every(item => item?.customAudience?.length && item?.excludedCustomAudience?.length) ? '#1890ff' : '#52C41A' }} />}</Button>}
                    </>}
                </Space>

                <div className={style.settingsBody}>
                    <div className={style.settingsBody_content}>
                        <DispatchAddelivery.Provider
                            value={{
                                addelivery,
                                setAddelivery,
                                accountCreateLogs,
                                setAccountCreateLogs,
                                materialData,
                                setMaterialData,
                                textData,
                                setTextData,
                                clearData,
                                putInType,
                                adLength,
                                isDqSubmit,
                                setIsDqSubmit,
                                targetRules,
                                setTargetRules
                            }}>
                            <div className={style.settingsBody_content_right}>
                                {/* 广告信息 */}
                                <Ad />
                                {/* 定向 */}
                                <Target />
                                {/* 创意 */}
                                <Dynamic
                                    creativeTemplateAppellation={creativeTemplateAppellation}
                                    creativeTemplateStyle={creativeTemplateStyle}
                                />
                                {/* 创意素材 */}
                                <Material />
                            </div>
                            <div className={style.settingsBody_content_left}>
                                {/* 创意文案 */}
                                <MaterialText />
                                {/* 落地页 */}
                                <PageList />
                            </div>
                        </DispatchAddelivery.Provider>
                    </div>
                </div>
                <Space className={style.bts} wrap>
                    <Save addelivery={addelivery} putInType={putInType} />
                    <Button type='primary' onClick={severBd}>存为预设</Button>
                    <Popconfirm
                        title="确定清空?"
                        onConfirm={() => delBdPlan({})}
                    >
                        <Button>清空配置/预设</Button>
                    </Popconfirm>
                    <Button type='primary' onClick={preview}><SearchOutlined />预览广告</Button>
                </Space>

                {/* 选择小说 */}
                {goodsVisible && <GoodsModal
                    marketingTargetType={marketingAssetOuterSpec?.marketingTargetType}
                    visible={goodsVisible}
                    data={accountCreateLogs}
                    onClose={() => setGoodsVisible(false)}
                    onChange={(e) => {
                        setIsDqSubmit(false)
                        setAccountCreateLogs(e);
                        setGoodsVisible(false);
                        clearData()
                    }}
                />}
                {/* 选择数据源 */}
                {sourceVisible && <DataSourceModal
                    visible={sourceVisible}
                    data={accountCreateLogs}
                    onClose={() => setSourceVisible(false)}
                    onChange={(e) => {
                        setIsDqSubmit(false)
                        setAccountCreateLogs(e);
                        setSourceVisible(false);
                        clearData()
                    }}
                />}
                {/* 选择公众号 */}
                {wechatVisible && <WechatAccount
                    visible={wechatVisible}
                    data={accountCreateLogs}
                    onClose={() => setWechatVisible(false)}
                    onChange={(e) => {
                        setIsDqSubmit(false)
                        setAccountCreateLogs(e);
                        setWechatVisible(false);
                        clearData()
                    }}
                />}
                {/* 选择视频号 */}
                {channelsProfileVisible && <VideoChannel
                    visible={channelsProfileVisible}
                    data={accountCreateLogs}
                    onClose={() => setChannelsProfileVisible(false)}
                    onChange={(e) => {
                        setIsDqSubmit(false)
                        setAccountCreateLogs(e);
                        setChannelsProfileVisible(false);
                        clearData()
                    }}
                />}
                {/* 转化归因 */}
                {conversionVisible && <ConversionSelect
                    adgroups={addelivery.adgroups}
                    putInType={putInType}
                    visible={conversionVisible}
                    data={accountCreateLogs}
                    onClose={() => setConversionVisible(false)}
                    onChange={(e) => {
                        setIsDqSubmit(false)
                        setAccountCreateLogs(e);
                        setConversionVisible(false);
                        clearData()
                    }}
                />}
                {/* 优量汇流量包 */}
                {positionPackageVisible && <PositionPackage
                    visible={positionPackageVisible}
                    data={accountCreateLogs}
                    onClose={() => setPositionPackageVisible(false)}
                    onChange={(e) => {
                        setIsDqSubmit(false)
                        setAccountCreateLogs(e);
                        setPositionPackageVisible(false);
                        clearData()
                    }}
                />}
                {/* 自定义人群包 */}
                {audienceVisible && <Audience
                    visible={audienceVisible}
                    data={accountCreateLogs}
                    onClose={() => setAudienceVisible(false)}
                    onChange={(e) => {
                        setIsDqSubmit(false)
                        setAccountCreateLogs(e);
                        setAudienceVisible(false);
                        clearData()
                    }}
                />}
            </Card>
        </Spin>

        <Card
            className={style.createAd}
        >
            {activeKey && tableData && Object.keys(tableData)?.length > 0 ? <div className={style.cardBody}>
                <Tabs
                    onChange={(e) => { setActiveKey(e) }}
                    type="card"
                    activeKey={activeKey}
                    tabBarExtraContent={<Space>
                        <span>广告总数：{adCount}</span>
                        <span>创意总数：{dynamicCount}</span>
                        <Tooltip title="注意，当前有提交过！" open={isDqSubmit ? undefined : false}>
                            <Button type='primary' danger={isDqSubmit} onClick={() => {
                                setSubVisible(true)
                            }}>提交创建</Button>
                        </Tooltip>
                    </Space>}
                    items={accountCreateLogs.map(item => ({ label: item.accountId, key: item.accountId?.toString() })) as any[]}
                />
                {addelivery?.dynamicCreativesTextDTOS?.type === 4 && <Title level={5} style={{ color: 'red', fontSize: 12 }}>因为选择的是“创意组和文案叉乘打乱后分配”模式，会随机打乱，当前预览广告下创意内容会与实际建出来的创意有偏差，请以建出来的为准</Title>}
                <div className={style.content} style={{ marginTop: 20 }}>
                    <Table
                        columns={columns()}
                        dataSource={tableData[activeKey]}
                        size="small"
                        bordered
                        scroll={{ x: 1200, y: 600 }}
                        rowKey={'id'}
                        pagination={{
                            defaultPageSize: 50,
                            total: tableData[activeKey]?.length || 0,
                            showTotal: (total) => <Tag color="cyan">当前共{total}个创意，{tableData[activeKey]?.[0]?.adLength}个广告</Tag>,
                        }}
                    />
                </div>
            </div> : <div style={{ minHeight: 400, display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                <Empty description="请先完成模块配置后，再预览广告计划" />
            </div>}
        </Card>

        {/* 提交任务 */}
        {subVisible && <SubmitModal
            ajax={createAdgroupTask}
            visible={subVisible}
            onChange={(e) => {
                onSubmit(e)
            }}
            onClose={() => {
                setSubVisible(false)
            }}
        />}
    </Space>
}

export default Create