import { Button, DatePicker, Input, Modal, Radio, Image, message, Popconfirm, Space } from "antd";
import React, { useCallback, useEffect, useState } from "react";
import { BcForm } from '../createPlan/components/AdBasicConfig'
import style from '../createPlan/components/AdBasicConfig/index.less'
import style1 from './index.less'
import ClerkAide from "../createPlan/components/AdOriginality/components/ClerkAide";
import SelectPage from '../../../components/selectPage'
import moment from "moment";
import { DeleteOutlined, DownOutlined, PlusOutlined, UpOutlined } from "@ant-design/icons";
import { useModel } from "umi";
import AdLogin from '../../../components/adLogin'
import SelectImg from '../../../components/selectImg'
import { setCopyPlanApi } from '@/services/operating/adAuthorize'

/** 批量复制 */
interface Props {
    visible: boolean,
    defaultValue: any,
    ajax?: any,
    onChange?: () => void,
    onClose?: () => void,
    clearSelect?: (d: any) => void
}
type ShortVideoProps = {
    media_id: string,
    thumb_height: number,
    thumb_width: number,
    video_duration: number,
    video_url: string
}
type OriDataProps = {
    desc?: string,     // 文案信息
    imageUrl?: string, // 广告位图片
    shortVideo?: ShortVideoProps,  // 广告位视频
    headDescType?: number, // 信息栏类型
    description?: string, // 信息栏文案
    title?: string, // 图文标题
    cardInfoDesc?: string[], // 广告文案
    pageData: any[],  // 落地页信息
    out_material_use_canvas_top?: number, // 是否使用头部信息
    isCanvasTop?: boolean,  // 是否不能使用头部图片
    isOpen: boolean   // 是否展开
}
function BatchPageCopy(props: Props) {
    const { visible, defaultValue, onClose, ajax, clearSelect } = props
    const { planInfo, mpAccountInfo, id: planCreateLogId } = Array.isArray(defaultValue) ? defaultValue[0] : defaultValue
    const { setCopyPlan } = useModel('useLaunch.useAdAuthorize')

    // 数据开始
    const [posType, setPosType] = useState<number>(999)
    const [productType, setProductType] = useState<string>("PRODUCTTYPE_WECHAT")
    const [clerkAideVisible, setClerkAideVisible] = useState<boolean>(false)
    const [pageShow, setPageShow] = useState<boolean>(false) // 选择落地弹窗
    const [date_module, setDate_module] = useState<string>('1')  // 投放日期
    const [begin_time, setBegin_time] = useState<number>(0) // 开始时间
    const [end_time, setEnd_time] = useState<number>(0) // 结束时间
    const [oriData, setOriData] = useState<OriDataProps[]>([])  // 创意数据
    const [clickNum, setClickNum] = useState<number>(-1)  // 点击了第几个创意按钮
    const [accout, setAccout] = useState<{ accountId?: number, accountType?: 'mp' | 'adq' }>({})  // 选择落地页 过滤条件
    const [authData, setAuthData] = useState<{ base64: string, code: string }>({ base64: '', code: '' })
    const [selectImgVisible, setSelectImgVisible] = useState<boolean>(false)   // 选择图片弹窗
    const [sliderImgContent, setSliderImgContent] = useState<{ content: string }[]>([])  // 保存回填数据
    const [loading, setLoading] = useState<boolean>(false)
    const [crtSize, setCrtSize] = useState<number>(1480)  // 1707
    const [fieldType, setFieldType] = useState<'one' | 'two'>('one') // 文案字段
    const [imgSize, setImgSize] = useState<{
        aspectRatio?: string, //宽高比
        minWidth?: string,   //最小宽度
        maxWidth?: string,   //最大宽度
        minHeight?: string,  //最小高度
        maxHeight?: string,  //最大高度
        minMediaSize?: number, // 最小媒体大小
        maxMediaSize?: number, // 最大媒体大小
        minVideoLength?: number, // 最小视频时长
        maxVideoLength?: number, // 最大视频时长
        minVideoBitRate?: number, // 最小视频比特率
        maxVideoBitRate?: number, // 最大视频比特率
        type?: 1 | 2,  // 内容类型 1 图片 2 视频
    }>({ minWidth: '960', maxWidth: '960', minHeight: '540', maxHeight: '540', minMediaSize: 0, maxMediaSize: 81920, type: 1 })   // 要选择的素材信息
    // 数据结束

    const getIsCanvasTop = (data: any): boolean => {
        if (data && typeof data === 'object' && data?.topCanvasType === 41) {
            let pageContext = data?.pageContextList[0]?.pageContextList
            if (pageContext) {
                pageContext = JSON.parse(pageContext)
                let { adLocation, viewType } = pageContext[0]
                if (adLocation === 'sns' && viewType === '1') {
                    return false
                } else {
                    return true
                }
            } else {
                return true
            }
        } else {
            return true
        }
    }

    // 回填数据
    useEffect(() => {
        if (typeof defaultValue === 'object' && Object.keys(defaultValue).length > 0) {
            let { firstContext, secondContext, sharePageInfo } = planInfo
            setPosType(() => planInfo?.posType)
            setProductType(() => planInfo?.putTarget)
            if (mpAccountInfo) {
                setAccout({ accountType: 'mp', accountId: mpAccountInfo?.id })
            }
            if (firstContext) {
                let a = JSON.parse(firstContext)
                let campaign = a?.campaign
                let { begin_time, end_time } = campaign
                setBegin_time(begin_time)
                if (end_time) {
                    setEnd_time(end_time)
                } else {
                    setDate_module('2')
                }
            }
            if (secondContext) {
                let a = JSON.parse(secondContext)
                let material = a?.materials[0]
                setCrtSize(() => material?.crt_size || 1480)
                if (planInfo?.posType === 999) { // 朋友圈
                    let crt_info = material?.crt_info
                    setImgSize({ minWidth: '800', maxWidth: '800', minHeight: '450', maxHeight: '450', minMediaSize: 0, maxMediaSize: 307200, type: 1 })
                    if (material?.crt_size === 1707) { // 卡片式
                        let isCanvasTop = getIsCanvasTop(sharePageInfo)
                        setOriData([{ desc: material?.desc, title: material?.title, imageUrl: crt_info?.image_url, out_material_use_canvas_top: material?.out_material_use_canvas_top, isCanvasTop, pageData: sharePageInfo ? [sharePageInfo] : [], isOpen: true }])
                    } else if (material?.crt_size === 1480) { // 常规
                        setOriData([{ desc: material?.desc, pageData: sharePageInfo ? [sharePageInfo] : [], isOpen: true }])
                    }
                } else if (planInfo?.posType === 0) { // 底部  大图
                    let crt_info = material?.crt_info
                    if (material?.crt_size === 538) {
                        setOriData([{ pageData: sharePageInfo ? [sharePageInfo] : [], shortVideo: crt_info?.short_video, headDescType: crt_info?.card_info?.head_desc_type, description: crt_info?.card_info?.description, isOpen: true }])
                        setImgSize(() => ({ minWidth: '960', maxWidth: '960', minHeight: '540', maxHeight: '540', minMediaSize: 0, maxMediaSize: 99614720, minVideoLength: 6, maxVideoLength: 30, type: 2 }))
                    } else {
                        setOriData([{ pageData: sharePageInfo ? [sharePageInfo] : [], imageUrl: crt_info?.image_url, headDescType: crt_info?.card_info?.head_desc_type, description: crt_info?.card_info?.description, isOpen: true }])
                    }
                } else if (planInfo?.posType === 101) { // 大图
                    let crt_info = material?.crt_info
                    setOriData([{ pageData: sharePageInfo ? [sharePageInfo] : [], imageUrl: crt_info?.image_url, headDescType: crt_info?.card_info?.head_desc_type, description: crt_info?.card_info?.description, title: material?.title, cardInfoDesc: crt_info?.card_info?.desc, isOpen: true }])
                } else if (planInfo?.posType === 8) {
                    setOriData([{ pageData: sharePageInfo ? [sharePageInfo] : [], isOpen: true }])
                }
            }
        }
    }, [defaultValue])

    const hideHandle = () => {
        onClose && onClose()
    }

    // 确认提交
    const handleOk = useCallback(() => {
        if (!planCreateLogId) {
            return
        }
        if (oriData?.some((item: { pageData: any }) => item.pageData?.length === 0)) {
            message.error('请选择原生推广页')
            return
        }
        if (posType === 999) {
            if (crtSize === 1707) {
                if (oriData?.some((item: { title?: string }) => !item?.title)) {
                    message.error('请完善外层文案标题')
                    return
                }
                if (oriData?.some((item: { imageUrl?: string, out_material_use_canvas_top?: number }) => item?.out_material_use_canvas_top === 0 ? !item?.imageUrl : false)) {
                    message.error('请完善外层图片')
                    return
                }
            }
            if (oriData?.some((item: { desc?: string }) => !item?.desc)) {
                message.error('请完善外层文案')
                return
            }
        }
        if (date_module === '1') {
            if (!begin_time || !end_time) {
                message.error('请选择开始与结束日期')
                return
            }
        } else {
            if (!begin_time) {
                message.error('请选择开始日期')
                return
            }
        }
        if (posType === 0 || posType === 101) {
            if (crtSize === 538) {
                if (!oriData?.every((item: { shortVideo?: ShortVideoProps }) => item?.shortVideo?.video_url)) {
                    message.error('请选择广告位视频')
                    return
                }
            } else {
                if (!oriData?.every((item: { imageUrl?: string }) => item?.imageUrl)) {
                    message.error('请选择广告位图片')
                    return
                }
            }
            if (!oriData?.every((item: { headDescType?: number, description?: string }) => {
                if (item?.headDescType === 2) {
                    if (item?.description) {
                        return true
                    } else {
                        return false
                    }
                } else {
                    return true
                }
            })) {
                message.error('请输入信息栏文案')
                return
            }
            if (posType === 101) {
                if (!oriData?.every((item: { title?: string }) => item?.title)) {
                    message.error('请输入图文标题')
                    return
                }
                if (!oriData?.every((item: { cardInfoDesc?: string[] }) => {
                    if (item?.cardInfoDesc) {
                        if (!item?.cardInfoDesc[0] || !item?.cardInfoDesc[1]) {
                            return false
                        } else {
                            return true
                        }
                    } else {
                        return false
                    }
                })) {
                    message.error('请输入广告文案')
                    return
                }
            }
        }
        setLoading(true)
        if (Array.isArray(defaultValue)) {//叉乘
            let ajaxArr: any = []
            defaultValue?.forEach((item, index) => {
                let { planName, putLocation, putTarget, firstContext, secondContext } = item?.planInfo
                let first = JSON.parse(firstContext)
                let second = JSON.parse(secondContext)
                first = {
                    ...first,
                    campaign: {
                        ...first.campaign,
                        begin_time,   // 开始时间
                        end_time      // 结束时间
                    },
                    target_groups: [{
                        ...first.target_groups[0],
                        ad_groups: [{
                            ...first.target_groups[0].ad_groups[0],
                            ad_group: {
                                ...first.target_groups[0].ad_groups[0].ad_group,
                                begin_time,   // 开始时间
                                end_time      // 结束时间
                            }
                        }]
                    }]
                }
                let planDtos = oriData?.map((item: OriDataProps) => {
                    if (posType === 999) {
                        if (crtSize === 1707) {
                            second = {
                                ...second,
                                materials: [{ ...second.materials[0], desc: item.desc, title: item.title, out_material_use_canvas_top: item.out_material_use_canvas_top, crt_info: item.out_material_use_canvas_top === 1 ? '' : { image_url: item.imageUrl } }]
                            }
                            return {
                                posType,
                                content: item.desc,
                                title: item.title,
                                imageUrl: item.imageUrl,
                                putLocation,
                                planName,
                                putTarget,
                                pageId: item.pageData[0]?.id,
                                firstContext: JSON.stringify(first),
                                secondContext: JSON.stringify(second)
                            }
                        } else { // 常规广告
                            second = {
                                ...second,
                                materials: [{ ...second.materials[0], desc: item.desc }]
                            }
                            return {
                                posType,
                                content: item.desc,
                                planName,
                                putLocation,
                                putTarget,
                                pageId: item.pageData[0]?.id,
                                firstContext: JSON.stringify(first),
                                secondContext: JSON.stringify(second)
                            }
                        }
                    } else if (posType === 8) {
                        return {
                            posType,
                            planName,
                            putLocation,
                            putTarget,
                            pageId: item.pageData[0]?.id,
                            firstContext: JSON.stringify(first),
                            secondContext: JSON.stringify(second)
                        }
                    } else if (posType === 0) {
                        let cardInfo: any = second.materials[0].crt_info.card_info
                        cardInfo.head_desc_type = item.headDescType
                        cardInfo.description = item.description
                        if (item.headDescType === 1) {
                            let { description, ...newInfo } = cardInfo
                            cardInfo = newInfo
                        }
                        second = {
                            ...second,
                            materials: [{
                                ...second.materials[0], crt_info: crtSize === 538 ? {
                                    ...second.materials[0].crt_info,
                                    short_video: { ...item.shortVideo },
                                    card_info: {
                                        ...cardInfo
                                    }
                                } : {
                                    ...second.materials[0].crt_info,
                                    image_url: item.imageUrl,
                                    card_info: {
                                        ...cardInfo
                                    }
                                }
                            }]
                        }
                        if (crtSize === 538) {
                            return {
                                posType,
                                shortVideo: JSON.stringify(item.shortVideo),
                                headDescType: item.headDescType,
                                description: item.description,
                                planName,
                                putLocation,
                                putTarget,
                                pageId: item.pageData[0]?.id,
                                firstContext: JSON.stringify(first),
                                secondContext: JSON.stringify(second)
                            }
                        } else {
                            return {
                                posType,
                                imageUrl: item.imageUrl,
                                headDescType: item.headDescType,
                                description: item.description,
                                planName,
                                putLocation,
                                putTarget,
                                pageId: item.pageData[0]?.id,
                                firstContext: JSON.stringify(first),
                                secondContext: JSON.stringify(second)
                            }
                        }
                        
                    } else {
                        let cardInfo: any = second.materials[0].crt_info.card_info
                        let descData: string[] = []
                        let cardInfoDesc: any = item.cardInfoDesc
                        descData[0] = cardInfoDesc[0]
                        descData[1] = cardInfoDesc[1]
                        if (cardInfoDesc[2]) {
                            descData[2] = cardInfoDesc[2]
                        }
                        cardInfo.head_desc_type = item.headDescType
                        cardInfo.description = item.description
                        cardInfo.desc = descData
                        if (item.headDescType === 1) {
                            let { description, ...newInfo } = cardInfo
                            cardInfo = newInfo
                        }
                        second = {
                            ...second,
                            materials: [{
                                ...second.materials[0], title: item.title, crt_info: {
                                    ...second.materials[0].crt_info,
                                    image_url: item.imageUrl,
                                    card_info: {
                                        ...cardInfo
                                    }
                                }
                            }]
                        }
                        return {
                            posType,
                            imageUrl: item.imageUrl,
                            headDescType: item.headDescType,
                            description: item.description,
                            title: item.title,
                            descList: descData,
                            planName,
                            putLocation,
                            putTarget,
                            pageId: item.pageData[0]?.id,
                            firstContext: JSON.stringify(first),
                            secondContext: JSON.stringify(second)
                        }
                    }
                })
                ajaxArr.push(setCopyPlanApi({ planCreateLogId: item.id, begin_time, end_time, taskName: "批量更换落地页-" + index + moment().unix(), copy_count: planDtos?.length, planDtos }))
            })
            Promise.all(ajaxArr).then((res: any) => {
                setLoading(false)
                console.log(res);
                if (res[res.length - 1]?.code === 200) {
                    // window.location.href = '/#/launchSystem/launchManage/taskList'
                    ajax && ajax?.refresh()
                    hideHandle && hideHandle()
                    clearSelect && clearSelect([])
                } else if (res[res.length - 1]?.code === 1003 && res[res.length - 1]?.data?.base64) {
                    setAuthData(res?.data)
                }
            })
        } else {
            let { planName, putLocation, putTarget, firstContext, secondContext } = planInfo
            let first = JSON.parse(firstContext)
            let second = JSON.parse(secondContext)
            first = {
                ...first,
                campaign: {
                    ...first.campaign,
                    begin_time,   // 开始时间
                    end_time      // 结束时间
                },
                target_groups: [{
                    ...first.target_groups[0],
                    ad_groups: [{
                        ...first.target_groups[0].ad_groups[0],
                        ad_group: {
                            ...first.target_groups[0].ad_groups[0].ad_group,
                            begin_time,   // 开始时间
                            end_time      // 结束时间
                        }
                    }]
                }]
            }
            let planDtos = oriData?.map((item: OriDataProps) => {
                if (posType === 999) {
                    if (crtSize === 1707) {
                        second = {
                            ...second,
                            materials: [{ ...second.materials[0], desc: item.desc, title: item.title, out_material_use_canvas_top: item.out_material_use_canvas_top, crt_info: item.out_material_use_canvas_top === 1 ? '' : { image_url: item.imageUrl } }]
                        }
                        return {
                            posType,
                            content: item.desc,
                            title: item.title,
                            imageUrl: item.imageUrl,
                            putLocation,
                            planName,
                            putTarget,
                            pageId: item.pageData[0]?.id,
                            firstContext: JSON.stringify(first),
                            secondContext: JSON.stringify(second)
                        }
                    } else { // 常规广告
                        second = {
                            ...second,
                            materials: [{ ...second.materials[0], desc: item.desc }]
                        }
                        return {
                            posType,
                            content: item.desc,
                            planName,
                            putLocation,
                            putTarget,
                            pageId: item.pageData[0]?.id,
                            firstContext: JSON.stringify(first),
                            secondContext: JSON.stringify(second)
                        }
                    }
                } else if (posType === 8) {
                    return {
                        posType,
                        planName,
                        putLocation,
                        putTarget,
                        pageId: item.pageData[0]?.id,
                        firstContext: JSON.stringify(first),
                        secondContext: JSON.stringify(second)
                    }
                } else if (posType === 0) {
                    let cardInfo: any = second.materials[0].crt_info.card_info
                    cardInfo.head_desc_type = item.headDescType
                    cardInfo.description = item.description
                    if (item.headDescType === 1) {
                        let { description, ...newInfo } = cardInfo
                        cardInfo = newInfo
                    }
                    second = {
                        ...second,
                        materials: [{
                            ...second.materials[0], crt_info: crtSize === 538 ? {
                                ...second.materials[0].crt_info,
                                short_video: { ...item.shortVideo },
                                card_info: {
                                    ...cardInfo
                                }
                            } : {
                                ...second.materials[0].crt_info,
                                image_url: item.imageUrl,
                                card_info: {
                                    ...cardInfo
                                }
                            }
                        }]
                    }
                    if (crtSize === 538) {
                        return {
                            posType,
                            shortVideo: JSON.stringify(item.shortVideo),
                            headDescType: item.headDescType,
                            description: item.description,
                            planName,
                            putLocation,
                            putTarget,
                            pageId: item.pageData[0]?.id,
                            firstContext: JSON.stringify(first),
                            secondContext: JSON.stringify(second)
                        }
                    } else {
                        return {
                            posType,
                            imageUrl: item.imageUrl,
                            headDescType: item.headDescType,
                            description: item.description,
                            planName,
                            putLocation,
                            putTarget,
                            pageId: item.pageData[0]?.id,
                            firstContext: JSON.stringify(first),
                            secondContext: JSON.stringify(second)
                        }
                    }
                } else {
                    let cardInfo: any = second.materials[0].crt_info.card_info
                    let descData: string[] = []
                    let cardInfoDesc: any = item.cardInfoDesc
                    descData[0] = cardInfoDesc[0]
                    descData[1] = cardInfoDesc[1]
                    if (cardInfoDesc[2]) {
                        descData[2] = cardInfoDesc[2]
                    }
                    cardInfo.head_desc_type = item.headDescType
                    cardInfo.description = item.description
                    cardInfo.desc = descData
                    if (item.headDescType === 1) {
                        let { description, ...newInfo } = cardInfo
                        cardInfo = newInfo
                    }
                    second = {
                        ...second,
                        materials: [{
                            ...second.materials[0], title: item.title, crt_info: {
                                ...second.materials[0].crt_info,
                                image_url: item.imageUrl,
                                card_info: {
                                    ...cardInfo
                                }
                            }
                        }]
                    }
                    return {
                        posType,
                        imageUrl: item.imageUrl,
                        headDescType: item.headDescType,
                        description: item.description,
                        title: item.title,
                        descList: descData,
                        planName,
                        putLocation,
                        putTarget,
                        pageId: item.pageData[0]?.id,
                        firstContext: JSON.stringify(first),
                        secondContext: JSON.stringify(second)
                    }
                }
            })
            setCopyPlanApi({ planCreateLogId, begin_time, end_time, taskName: "批量更换落地页-" + moment().unix(), copy_count: planDtos?.length, planDtos }).then(res => {
                setLoading(false)
                if (res.code === 200) {
                    // window.location.href = '/#/launchSystem/launchManage/taskList'
                    ajax && ajax?.refresh()
                    hideHandle && hideHandle()
                    clearSelect && clearSelect([])
                } else if (res?.code === 1003 && res?.data?.base64) {
                    setAuthData(res?.data)
                }
            })
        }
    }, [oriData, begin_time, end_time, date_module, planInfo, authData, defaultValue, posType, loading, crtSize])

    // 不可选择日期
    function disabledDate(current: any) {
        return current && current < moment().subtract(1, 'day') || current > (moment().add(1, 'year').startOf('day'))
    }

    // 判断投放日期类型改变结束时间
    useEffect(() => {
        if (date_module === '2') {
            setEnd_time(0)
        }
    }, [date_module])

    // 结束日期不可选择日期
    const disabledEndDate = useCallback((current: any) => {
        if (begin_time) {
            return current && current < moment(begin_time * 1000) || current < moment().subtract(1, 'day') || current > (moment().add(1, 'year').startOf('day'))
        } else {
            return current && current < moment().subtract(1, 'day') || current > (moment().add(1, 'year').startOf('day'))
        }
    }, [begin_time])

    // 计算desc字数
    const descNum = (desc: string | undefined): number => {
        if (desc) {
            let length = desc?.length
            let text = desc?.replace(/[\x00-\xff]/g, '')
            return text?.length + Number(((length - text?.length) / 2).toFixed())
        } else {
            return 0
        }
    }
    // 新增创意
    const addOri = useCallback(() => {
        let newOriData = [...oriData]
        if (posType === 999) { // 朋友圈
            if (crtSize === 1707) {
                newOriData.push({ desc: "", title: "", imageUrl: '', out_material_use_canvas_top: 0, isCanvasTop: false, pageData: [], isOpen: true })
            } else if (crtSize === 1480) {
                newOriData.push({ desc: "", pageData: [], isOpen: true })
            }
        } else if (posType === 0) {  // 底部
            if (crtSize === 538) {
                newOriData.push({ shortVideo: { media_id: '', thumb_height: 540, thumb_width: 960, video_duration: 0, video_url: '' }, headDescType: 1, description: '', pageData: [], isOpen: true })
            } else {
                newOriData.push({ imageUrl: "", headDescType: 1, description: '', pageData: [], isOpen: true })
            }
        } else if (posType === 101) {
            newOriData.push({ imageUrl: "", headDescType: 1, description: '', pageData: [], title: '', cardInfoDesc: [], isOpen: true })
        } else if (posType === 8) {
            newOriData.push({ pageData: [], isOpen: true })
        }
        setOriData(newOriData)
    }, [oriData, posType, crtSize])

    // 删除创意
    const delOri = useCallback((index: number) => {
        oriData?.splice(index, 1)
        setOriData([...oriData])
    }, [oriData])

    /** 弹窗返回设置图片 */
    const setImg = useCallback((value: any[]) => {
        if (clickNum !== -1 && value?.length > 0) {
            let data = oriData[clickNum]
            if (crtSize === 538) {  // 底部视频
                data = { ...data, shortVideo: { video_url: value[0].content, thumb_width: 960, thumb_height: 540, video_duration: value[0].videoLength, media_id: value[0].mediaSize } }
            } else { // 其它图片
                data = { ...data, imageUrl: value[0].content }
            }
            oriData[clickNum] = { ...data }
            setOriData([...oriData])
        }
    }, [oriData, clickNum, crtSize])

    /** 选择图片 */
    const selectImg = useCallback((imageUrl: string | undefined, index: number) => {
        if (imageUrl) {
            setSliderImgContent([{ content: imageUrl }])
        }
        setClickNum(index)
        setSelectImgVisible(true)
    }, [selectImgVisible, clickNum, sliderImgContent])
    /** 设置参数 */
    const setParams = useCallback((params: string, value: any, index: number, i?: number) => {
        let data: any = oriData[index]
        if (params === "cardInfoDesc" && (i === 0 || i)) {
            data[params][i] = value
        } else {
            if (params === 'headDescType' && value === 1) {
                data.description = ''
            }
            data[params] = value
        }
        oriData[index] = { ...data }
        setOriData([...oriData])
    }, [oriData])

    // 设置落地页
    const setPageData = (data: any[]) => {
        let dataOri = oriData[clickNum]
        if (crtSize === 1707) { // 1480
            let isCanvasTop = getIsCanvasTop(data[0])
            let out_material_use_canvas_top = dataOri?.out_material_use_canvas_top
            if (isCanvasTop) {
                if (out_material_use_canvas_top === 1) {
                    dataOri = { ...dataOri, pageData: data, isCanvasTop, out_material_use_canvas_top: 0 }
                } else {
                    dataOri = { ...dataOri, pageData: data, isCanvasTop }
                }
            } else {
                dataOri = { ...dataOri, pageData: data, isCanvasTop }
            }
        } else {
            dataOri = { ...dataOri, pageData: data }
        }
        oriData[clickNum] = { ...dataOri }
        setOriData([...oriData])
    }
    return <Modal
        bodyStyle={{ height: 600, overflowY: 'auto' }}
        title="批量更换落地页"
        visible={visible}
        onCancel={hideHandle}
        onOk={handleOk}
        confirmLoading={setCopyPlan.loading || loading}
        width={1000}
        className={style1.batchCopy}
        maskClosable={false}
    >
        {/* 授权登录 */}
        <AdLogin onClose={() => { setAuthData({ base64: '', code: '' }) }} value={authData} onChange={() => { setAuthData({ base64: '', code: '' }); message.success('再次点击按钮提交') }} />
        {/* 选择文案 */}
        {clerkAideVisible && <ClerkAide
            fieldType={fieldType}
            visible={clerkAideVisible}
            hideModel={() => { setClerkAideVisible(false) }}
            onChange={(value1, value2) => {
                if (fieldType === 'one') {
                    if (clickNum !== -1) {
                        let data = oriData[clickNum]
                        data = { ...data, desc: value1 }
                        oriData[clickNum] = { ...data }
                        setOriData([...oriData])
                    }
                } else {
                    if (clickNum !== -1) {
                        let data = oriData[clickNum]
                        data = { ...data, title: value1, desc: value2 }
                        oriData[clickNum] = { ...data }
                        setOriData([...oriData])
                    }
                }

            }}
        />}
        {/* 选择落地页 */}
        {pageShow && clickNum !== -1 && <SelectPage
            account={accout}
            show={pageShow}
            localtion={posType}
            productType={productType}
            crtSize={Array.isArray(defaultValue) ? JSON.parse(defaultValue[0]?.planInfo?.secondContext)?.materials[0]?.crt_size : JSON.parse(defaultValue?.planInfo?.secondContext)?.materials[0]?.crt_size}
            onClose={() => { setPageShow(false) }}
            onChange={(data: any[]) => {
                setPageShow(false);
                if (clickNum !== -1) {
                    let dataOri = oriData[clickNum]
                    if (dataOri?.pageData?.length === 0) {
                        setPageData(data)
                    } else if (dataOri?.pageData[0]?.id === data[0]?.id) {

                    } else {
                        setPageData(data)
                    }
                }
            }}
            pageData={oriData[clickNum]?.pageData}
        ></SelectPage>}

        {/* 选择图片 视频 */}
        {selectImgVisible && <SelectImg visible={selectImgVisible} hideModel={() => { setSelectImgVisible(false) }} num={1} onChange={setImg} listParams={imgSize} sliderImgContent={sliderImgContent}></SelectImg>}

        {
            Array.isArray(defaultValue) && <strong style={{ color: 'red', marginBottom: '15px', display: 'block' }}>注：叉乘一定要确保所有账号都存在对应的推广页，否则会出错失败<br/>本次操作所有选择的计划都会执行一次创意的配置，即选中10条计划，每条计划都会建一条创意1的配置计划，当有新增创意2时，10条计划各自再创建一次创意2的配置，依次类推！！！</strong>
        }
        <div className={style1.info}>
            <div className={style1.items}>
                <div className={style1.item}>
                    <label className={style1.label}>投放计划名称:</label>
                    <span>{planInfo?.planName}</span>
                </div>
                <div className={style1.item}>
                    <label className={style1.label}>投放号:</label>
                    <span>{mpAccountInfo?.channel?.accountName}——{mpAccountInfo?.uname}</span>
                </div>
            </div>
            <div className={style1.items}>
                <div className={style1.item}>
                    <label className={style1.label}>投放位置:</label>
                    <span>{planInfo?.putLocation}</span>
                </div>
                <div className={style1.item}>
                    <label className={style1.label}>推广目标:</label>
                    <span>{planInfo?.putTarget}</span>
                </div>
            </div>
        </div>

        <div className={style1.title}>排期修改</div>
        <BcForm name="投放日期" tips={date_module === '1' ? '竞价购买的朋友圈信息流广告投放时间，可选范围6小时~60天' : ''}>
            <Radio.Group value={date_module} className={style.radio} onChange={(e) => { setDate_module(e.target.value) }}>
                <Radio.Button value="1">选择开始与结束日期</Radio.Button>
                <Radio.Button value="2">长期投放</Radio.Button>
            </Radio.Group>
        </BcForm>
        <BcForm name={date_module === '1' ? '开始与结束日期' : '开始日期'} >
            <div style={{ display: 'flex', justifyContent: 'flex-start', alignItems: 'center' }}>
                <DatePicker
                    className={style.picker}
                    disabledDate={disabledDate}
                    value={begin_time ? moment(begin_time * 1000) : null}
                    onChange={(e: moment.Moment | null) => {
                        setBegin_time(e ? moment(e).startOf('day').unix() : 0)
                    }}
                    placeholder="开始日期"
                />
                {date_module === '1' && <>
                    <span style={{ margin: '0 10px' }}>-</span>
                    <DatePicker
                        className={style.picker}
                        disabledDate={disabledEndDate}
                        value={end_time ? moment(end_time as number * 1000) : null}
                        onChange={(e: moment.Moment | null) => {
                            setEnd_time(e ? moment(e).endOf('day').unix() : 0)
                        }}
                        placeholder="结束日期"
                    />
                </>}
            </div>
        </BcForm>
        <div className={style1.title}>创意基本信息</div>
        {oriData?.length > 0 && oriData?.map((item: OriDataProps, index: number) => {
            return <div className={style1.originality} key={index}>
                <div className={style1.head}>
                    <div>创意{index + 1}</div>
                    <div>
                        {oriData?.length > 1 && <Popconfirm placement="top" title="是否放弃该创意" onConfirm={() => { delOri(index) }} okText="Yes" cancelText="No">
                            <Button type="link" size='small' className={style1.clear} style={{ color: 'red' }}><DeleteOutlined /></Button>
                        </Popconfirm>}
                        <Button
                            type="link"
                            size='small'
                            style={{ color: '#000' }}
                            onClick={() => {
                                let data = oriData[index]
                                data = { ...data, isOpen: !data.isOpen }
                                oriData[index] = { ...data }
                                setOriData([...oriData])
                            }}
                        >
                            {item?.isOpen ? <UpOutlined /> : <DownOutlined />}
                        </Button>
                    </div>
                </div>
                {item?.isOpen && <>
                    <div style={{ height: 20 }}></div>

                    {posType === 999 ? <>
                        {crtSize === 1480 ? <>
                            <BcForm name="外层文案" flex='flex-start'>
                                <div className={style.flexStart}>
                                    <div>
                                        <Input.TextArea
                                            value={item.desc}
                                            onChange={(e) => {
                                                let data = oriData[index]
                                                data = { ...data, desc: e.target.value }
                                                oriData[index] = { ...data }
                                                setOriData([...oriData])
                                            }}
                                            className={style.textArea}
                                            style={{ width: 300 }}
                                            placeholder="请输入文案(可直接编辑，或点击文案助手选择合适文案)"
                                            autoSize={{ minRows: 2, maxRows: 4 }}
                                        />
                                        <div className={style.maxLength}>
                                            <div style={{ color: 'rgb(242, 77, 77)', fontSize: 12 }}>{descNum(item?.desc) > 40 && '广告文案不得超过40字，请缩短输入内容'}</div>
                                            <div>{descNum(item?.desc)}/40</div>
                                        </div>
                                    </div>
                                    <Button onClick={() => { setFieldType('one'); setClerkAideVisible(true); setClickNum(index) }}>文案助手</Button>
                                </div>
                            </BcForm>
                        </> : crtSize === 1707 ? <>
                            <BcForm name="原生推广页">
                                <div className={style.flexStart} style={{ alignItems: 'center' }}>
                                    {item.pageData.length > 0 && <div>{item.pageData[0]?.name}</div>}
                                    <Button onClick={() => { setPageShow(true); setClickNum(index) }}>选择原生推广页</Button>
                                </div>
                            </BcForm>
                            {item.pageData.length > 0 && <>
                                <BcForm name="原生推广页顶部素材预览" flex='flex-start'>
                                    <div className={style.flexStart}>
                                        {item?.pageData[0]?.topCanvasType === 101 ?
                                            <Space>
                                                {JSON.parse(item?.pageData[0]?.pageContextList[0]?.pageContextList)[0]?.componentGroupList?.componentGroup?.map((item: any, index: number) => {
                                                    return <Image width={80} src={item?.componentItem?.pureImageUrl} style={{ borderRadius: 8 }} key={index} />
                                                })}
                                            </Space> :
                                            item?.pageData[0]?.topCanvasType === 41 ?
                                                <Image width={80} src={item.pageData[0]?.thumbUrl} style={{ borderRadius: 8 }} />
                                                :
                                                <Image width={80} src={item.pageData[0]?.thumbUrl} style={{ borderRadius: 8 }} />}
                                    </div>
                                </BcForm>

                                <BcForm name="外层素材">
                                    <Radio.Group
                                        className={style.radio}
                                        value={item?.out_material_use_canvas_top}
                                        onChange={(e) => {
                                            let data = oriData[index]
                                            data = { ...data, out_material_use_canvas_top: e.target.value }
                                            oriData[index] = { ...data }
                                            setOriData([...oriData])
                                        }}
                                    >
                                        <Radio value={1} disabled={item?.isCanvasTop}>使用原生推广页顶部素材</Radio>
                                        <Radio value={0}>上传素材</Radio>
                                    </Radio.Group>
                                </BcForm>
                                {
                                    item?.out_material_use_canvas_top === 0 && <BcForm name="外层图片" flex="flex-start">
                                        <div>
                                            <Button onClick={() => { selectImg(item?.imageUrl, index) }}>{item?.imageUrl ? '修改图片' : '上传图片'}</Button>
                                            <div style={{ marginTop: 8, fontSize: 13, color: '#8f9196' }}>图片大小800像素x450像素，不超过300KB</div>
                                            {item?.imageUrl && <div style={{ marginTop: 20 }}><Image width={100} src={item?.imageUrl} style={{ borderRadius: 8, overflow: 'hidden' }} /></div>}
                                        </div>
                                    </BcForm>
                                }
                            </>}

                            <BcForm name="外层文案标题" flex='flex-start'>
                                <div className={style.flexStart}>
                                    <div>
                                        <Input.TextArea
                                            value={item?.title}
                                            onChange={(e) => {
                                                let data = oriData[index]
                                                data = { ...data, title: e.target.value }
                                                oriData[index] = { ...data }
                                                setOriData([...oriData])
                                            }}
                                            className={style.textArea}
                                            style={{ width: 300 }}
                                            placeholder="请填广告标题"
                                            autoSize={{ minRows: 1, maxRows: 2 }}
                                        />
                                        <div className={style.maxLength}>
                                            <div style={{ color: 'rgb(242, 77, 77)', fontSize: 12 }}>{descNum(item?.title) > 10 && '广告文案不得超过10字，请缩短输入内容'}</div>
                                            <div>{descNum(item?.title)}/10</div>
                                        </div>
                                    </div>
                                    <Button onClick={() => { setFieldType('two'); setClerkAideVisible(true); setClickNum(index) }}>文案助手</Button>
                                </div>
                            </BcForm>
                            <BcForm name="外层文案" flex='flex-start'>
                                <div className={style.flexStart}>
                                    <div>
                                        <Input.TextArea
                                            value={item.desc}
                                            onChange={(e) => {
                                                let data = oriData[index]
                                                data = { ...data, desc: e.target.value }
                                                oriData[index] = { ...data }
                                                setOriData([...oriData])
                                            }}
                                            className={style.textArea}
                                            style={{ width: 300 }}
                                            placeholder="请输入文案(可直接编辑，或点击文案助手选择合适文案)"
                                            autoSize={{ minRows: 2, maxRows: 4 }}
                                        />
                                        <div className={style.maxLength}>
                                            <div style={{ color: 'rgb(242, 77, 77)', fontSize: 12 }}>{descNum(item?.desc) > 30 && '广告文案不得超过40字，请缩短输入内容'}</div>
                                            <div>{descNum(item?.desc)}/30</div>
                                        </div>
                                    </div>
                                </div>
                            </BcForm>
                        </> : <></>}


                    </> : posType === 0 || posType === 101 ? <>
                        {crtSize === 538 ? <BcForm name="广告位视频" flex="flex-start">
                            <div>
                                <Button onClick={() => { selectImg(item?.shortVideo?.video_url, index) }}>{item?.shortVideo?.video_url ? '修改视频' : '上传视频'}</Button>
                                {/* ≥ */}
                                <div style={{ marginTop: 8, fontSize: 13, color: '#8f9196' }}>视频尺寸960x540，不超过100MB，视频时长6-30秒</div>
                                {item?.shortVideo?.video_url && <div style={{ marginTop: 20 }}><video width={100} src={item?.shortVideo?.video_url} style={{ borderRadius: 8, overflow: 'hidden' }} /></div>}
                            </div>
                        </BcForm> : <BcForm name="广告位图片" flex="flex-start">
                            <div>
                                <Button onClick={() => { selectImg(item?.imageUrl, index) }}>{item?.imageUrl ? '修改图片' : '上传图片'}</Button>
                                <div style={{ marginTop: 8, fontSize: 13, color: '#8f9196' }}>图片大小960像素x540像素，不超过80KB</div>
                                {item?.imageUrl && <div style={{ marginTop: 20 }}><Image width={100} src={item?.imageUrl} style={{ borderRadius: 8, overflow: 'hidden' }} /></div>}
                            </div>
                        </BcForm>}
                        <BcForm name="信息栏类型">
                            <Radio.Group className={style.radio} value={item?.headDescType} onChange={(e) => { setParams('headDescType', e.target.value, index) }}>
                                <Radio value={1}>头像昵称型</Radio>
                                <Radio value={2}>文案型</Radio>
                            </Radio.Group>
                        </BcForm>
                        {item?.headDescType && item?.headDescType === 2 && <BcForm name="信息栏文案" flex="flex-start">
                            <Input.TextArea showCount maxLength={12} value={item?.description} onChange={(e) => { setParams('description', e.target.value, index) }} placeholder="信息栏文案" autoSize />
                        </BcForm>}

                        {posType === 101 && <>
                            <BcForm name="图文标题" flex="flex-start">
                                <Input.TextArea showCount maxLength={12} value={item?.title} onChange={(e) => { setParams('title', e.target.value, index) }} autoSize />
                            </BcForm>
                            <BcForm name="广告文案" flex="flex-start">
                                <>
                                    <Input.TextArea showCount maxLength={16} value={item?.cardInfoDesc ? item?.cardInfoDesc[0] : undefined} onChange={(e) => { setParams('cardInfoDesc', e.target.value, index, 0) }} autoSize placeholder="请输入首行文案" />
                                    <Input.TextArea showCount maxLength={16} value={item?.cardInfoDesc ? item?.cardInfoDesc[1] : undefined} onChange={(e) => { setParams('cardInfoDesc', e.target.value, index, 1) }} autoSize placeholder="次行文案" />
                                    <Input.TextArea showCount maxLength={16} value={item?.cardInfoDesc ? item?.cardInfoDesc[2] : undefined} onChange={(e) => { setParams('cardInfoDesc', e.target.value, index, 2) }} autoSize placeholder="请输入第三行文案（选填）" />
                                </>
                            </BcForm>
                        </>}

                    </> : <></>}

                    {crtSize !== 1707 && <>
                        <BcForm name="原生推广页">
                            <div className={style.flexStart} style={{ alignItems: 'center' }}>
                                {item.pageData.length > 0 && <div>{item.pageData[0]?.name}</div>}
                                <Button onClick={() => { setPageShow(true); setClickNum(index) }}>选择原生推广页</Button>
                            </div>
                        </BcForm>
                        {item.pageData.length > 0 && <BcForm name="原生推广页顶部素材预览" flex='flex-start'>
                            <div className={style.flexStart}>
                                {item?.pageData[0]?.topCanvasType === 101 ?
                                    <Space>
                                        {JSON.parse(item?.pageData[0]?.pageContextList[0]?.pageContextList)[0]?.componentGroupList?.componentGroup?.map((item: any, index: number) => {
                                            return <Image width={80} src={item?.componentItem?.pureImageUrl} style={{ borderRadius: 8 }} key={index} />
                                        })}
                                    </Space> :
                                    item?.pageData[0]?.topCanvasType === 41 ?
                                        <Image width={80} src={item.pageData[0]?.thumbUrl} style={{ borderRadius: 8 }} />
                                        :
                                        <Image width={80} src={item.pageData[0]?.thumbUrl} style={{ borderRadius: 8 }} />}
                            </div>
                        </BcForm>}
                    </>}
                </>}
            </div>
        })}
        <Button type="link" style={{ padding: '4px 0', marginTop: 10 }} onClick={addOri}><PlusOutlined /> 新增创意</Button>
    </Modal>
}

export default React.memo(BatchPageCopy)