import { Button, Checkbox, message, Modal, Popconfirm, Radio, Select, Space } from "antd";
import React, { useCallback, useEffect, useState } from "react";
import { BcForm } from "../createPlan/components/AdBasicConfig";
import style1 from './index.less'
import { TopImg, TopVideoNew, TopSlider } from '../../../req'
import { DeleteOutlined, PlusOutlined, RetweetOutlined } from "@ant-design/icons";
import {
    SortableUlList,
    SortableItemNoLi,
    SortableItemLi
} from '../../../components/addLandingPage/sortable'
import SelectImg from '../../../components/selectImg'
import arrayMove from "array-move"
import SelectAccount from '../../../../launchManage/components/addLandingPage/selectAccount'
import AdLogin from '../../../../launchManage/components/adLogin'
import { addAndCreateApi, adsSharePageApi } from '@/services/operating/adAuthorize'
import { topsliderContent, topimgContent, topvideoNewContent } from '../../../components/addLandingPage/content'


/** 批量复制落地页 */
interface Props {
    visible: boolean,
    data: any,
    accountsInfo?: { id: number, accountName: string, MP?: any[], ADQ?: any[] }[],
    onChange?: () => void,
    onClose?: () => void,
    ajaxHome?: any
}

function BathLauCopy(props: Props) {
    const { visible, data, onChange, onClose, accountsInfo = [], ajaxHome } = props

    /** 数据参数开始 */
    const [widgetTypeV2, setWidgetTypeV2] = useState<string | undefined>(undefined) // 顶部素材类型
    const [adLocation, setAdLocation] = useState<string>('sns')  // 广告位
    const [viewType, setViewType] = useState<string>('0')  // 外层样式
    const [styleType, setStyleType] = useState<string>('0')  // 视频类型
    const [initHeight, setInitHeight] = useState<number>(1536)  // 视频尺寸
    const [componentCount, setComponentCount] = useState<string>('3')  // 图片数量
    const [topData, setTopData] = useState<Array<TopImg | TopVideoNew | TopSlider>>([])  // 顶部素材数据
    const [selectImgVisible, setSelectImgVisible] = useState<boolean>(false)   // 选择图片弹窗
    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 视频
    }>({})   // 要选择的素材信息
    const [imgType, setimgType] = useState<boolean>(false) // 是否是公众号及其它
    const [isFootlock, setIsFootlock] = useState<boolean>(false)  // 是否横板视频
    const [sliderImgContent, setSliderImgContent] = useState<{ content: string }[]>([])  // 保存回填数据
    const [groupIndex, setGroupIndex] = useState<number>(-1)  // 保存正在操作的组 下标
    const [channelAccounts, setChannelAccounts] = useState<{ MP?: any, ADQ?: any, id: number, accountName: string }[]>([])  // 选择上传公众号
    const [isUpload, setIsUpload] = useState<boolean>(false) // 是否暂时不上传
    const [selectAccShow, setSelectAccShow] = useState<boolean>(false) // 控制选择账户弹窗
    const [authData, setAuthData] = useState<{ base64: string, code: string }>({ base64: '', code: '' })
    const [loading, setLoading] = useState<boolean>(false)  // 确定按钮loading
    const [isWxBt, setIsWxBt] = useState<boolean>(false) // 是否有联系商家按钮
    /** 数据参数结束 */

    // 账号回填
    useEffect(() => {
        setChannelAccounts(accountsInfo)
    }, [accountsInfo])
    // 回填
    useEffect(() => {
        if (data?.topCanvasType) {
            if (data?.topCanvasType === 41) {
                setWidgetTypeV2('topimg')
                setComponentCount('1')
            } else if (data?.topCanvasType === 142) {
                setWidgetTypeV2('topvideo_new')
            } else if (data?.topCanvasType === 101) {
                setWidgetTypeV2('topslider')
                setComponentCount('3')
            } else {
                setWidgetTypeV2(undefined)
            }
        }
        if (data?.pageContextList && data?.pageContextList?.length > 0) {
            let pageContext = data?.pageContextList[0]
            let pageContextList = JSON.parse(pageContext?.pageContextList)
            let globalComponentList = JSON.parse(pageContext?.globalComponentList)
            if (pageContextList && pageContextList?.length > 0) {
                setTopData([{ ...pageContextList[0] }])
                if (data?.topCanvasType === 41) {
                    setAdLocation(() => pageContextList[0].adLocation)
                    setViewType(() => pageContextList[0].viewType)
                } else if (data?.topCanvasType === 142) {
                    setAdLocation(() => pageContextList[0].adLocation)
                    setViewType(() => pageContextList[0].viewType)
                    setStyleType(() => pageContextList[0].styleType)
                    if (pageContextList[0].adLocation === 'sns' && pageContextList[0].viewType === '0' && pageContextList[0].styleType === '1') {
                        setInitHeight(() => pageContextList[0].initHeight)
                    }
                } else if (data?.topCanvasType === 101) {
                    setComponentCount(pageContextList[0].componentCount)
                }
                // 判断是否使用联系商家按钮
                for (const iterator of pageContextList) {
                    if (iterator?.widgetTypeV2 === "enterprise_wx_auto") {
                        setIsWxBt(true)
                        break
                    } else if (iterator?.widgetTypeV2 === "shelfnew") {
                        if (iterator?.type === '103') {
                            let b = iterator?.layoutItems?.componentItem?.every((shelfnewItem: any, index: number) => {
                                let componentItem = shelfnewItem?.layoutItems?.componentItem[0]?.layoutItems?.componentItem
                                if (componentItem[3]?.widgetTypeV2 === 'enterprise_wx_auto') {
                                    setIsWxBt(true)
                                    return false
                                }
                                return true
                            })
                            if (!b) {
                                break
                            }
                        } else {
                            let componentItem103 = iterator?.layoutItems?.componentItem[0]?.layoutItems?.componentItem
                            let componentItem = componentItem103[1]?.layoutItems?.componentItem
                            if (componentItem[2]?.widgetTypeV2 === 'enterprise_wx_auto') {
                                setIsWxBt(true)
                                break
                            }
                        }
                    }
                }
            }
            if (globalComponentList && globalComponentList?.length > 0) {
                // 判断是否使用联系商家按钮
                for (const iterator of globalComponentList) {
                    if (iterator?.widgetTypeV2 === "floatbutton" && iterator?.componentItem?.widgetTypeV2 === 'enterprise_wx_auto') {
                        setIsWxBt(true)
                        break
                    }
                }
            }
        }
    }, [data])

    // 设置选择的图片参数
    /** 获取选中内容 */
    useEffect(() => {
        if (widgetTypeV2 === 'topimg') {
            setIsFootlock(() => false)
            if (adLocation === 'sns') { // 朋友圈信息流
                if (viewType === '0') { // 常规广告
                    setImgSize(() => ({ minWidth: '800', maxWidth: '800', minHeight: '800', maxHeight: '800', minMediaSize: 0, maxMediaSize: 307200, type: 1 }))
                    setimgType(() => false)
                } else { // 卡片广告
                    setImgSize(() => ({ minWidth: '800', maxWidth: '800', minHeight: '450', maxHeight: '450', minMediaSize: 0, maxMediaSize: 307200, type: 1 }))
                    setimgType(() => false)
                }
            } else { // 公众号及其他
                setImgSize(() => ({ minWidth: '800', maxWidth: '800', minHeight: '800', maxHeight: '800', minMediaSize: 0, maxMediaSize: 307200, type: 1 }))
                setimgType(() => true)
            }
        } else if (widgetTypeV2 === 'topslider') { // 轮播图
            setIsFootlock(() => false)
            setImgSize(() => ({ minWidth: '800', maxWidth: '800', minHeight: '800', maxHeight: '800', minMediaSize: 0, maxMediaSize: 307200, type: 1 }))
            setimgType(() => false)
        } else if (widgetTypeV2 === 'topvideo_new') { // 视频
            // setImgSize(() => ({ type: 2 }))
            setimgType(() => false)
            if (adLocation === 'sns') { // 朋友圈信息流
                if (viewType === '0') { // 常规广告
                    if (styleType === '0') { // 横板视频
                        // setIsFootlock(() => true)
                        setImgSize(() => ({ minWidth: '1280', maxWidth: '1280', minHeight: '720', maxHeight: '1280', minMediaSize: 0, maxMediaSize: 99614720, minVideoLength: 5, maxVideoLength: 90, type: 2 }))
                    } else { // 竖版视频
                        setIsFootlock(() => false)
                        if (initHeight === 1536) { // 750像素 x 1536像素
                            setImgSize(() => ({ minWidth: '750', maxWidth: '2000', minHeight: '1536', maxHeight: '4000', minMediaSize: 0, maxMediaSize: 99614720, minVideoLength: 6, maxVideoLength: 90, type: 2 }))
                        } else if (initHeight === 1334) { // 750像素 x 1334像素
                            setImgSize(() => ({ minWidth: '750', maxWidth: '2000', minHeight: '1334', maxHeight: '4000', minMediaSize: 0, maxMediaSize: 99614720, minVideoLength: 6, maxVideoLength: 90, type: 2 }))
                        } else if (initHeight === 1280) { // 720像素 x 1280像素
                            setImgSize(() => ({ minWidth: '720', maxWidth: '2000', minHeight: '1280', maxHeight: '4000', minMediaSize: 0, maxMediaSize: 99614720, minVideoLength: 6, maxVideoLength: 90, type: 2 }))
                        }
                    }
                } else { // 卡片广告

                }
            } else { // 公众号及其它
                setIsFootlock(() => false)
                setImgSize(() => ({ minWidth: '750', maxWidth: '2000', minMediaSize: 0, maxMediaSize: 314572800, minVideoLength: 6, maxVideoLength: 90, type: 2 }))
            }
        }
    }, [widgetTypeV2, adLocation, viewType, styleType, initHeight])

    // 关闭弹窗
    const hideHandle = () => {
        onClose && onClose()
    }

    const handleOk = useCallback(() => {
        if (!data || JSON.stringify(data) === '{}') {
            return
        }
        if (widgetTypeV2 === 'topslider' && !topData?.every((item1: any) => {
            if (!item1.componentGroupList?.componentGroup?.every((item: { componentItem: { pureImageUrl: string } }) => item?.componentItem?.pureImageUrl)) {
                return false
            } else {
                return true
            }
        })) {
            message.error('顶部轮播图组缺少图片')
            return
        } else if (widgetTypeV2 === 'topimg' && !topData?.every((item: any) => item.pureImageUrl)) {
            message.error('顶部图片组缺少图片')
            return
        } else if (widgetTypeV2 === 'topvideo_new' && !topData?.every((item: any) => (item.videoUrl))) {
            message.error('顶部视频组缺少视频')
            return
        }

        setLoading(true)
        // 公众号选择相关
        let channelMpAccounts: number[] = []
        let channelAdqAccounts: number[] = []
        let channelMpWechatInfoList: any[] = []
        let wechatInfoList = data?.wechatInfoList
        if (wechatInfoList) {
            channelMpWechatInfoList = JSON.parse(wechatInfoList)
        }
        channelAccounts?.forEach((item: { id: number, MP?: any[], ADQ?: any[] }) => {
            let { MP, ADQ } = item
            if (MP && MP?.length > 0 || ADQ && ADQ?.length > 0) {
                let mpIds = MP?.map((m: any) => m?.id)
                let adqIds = ADQ?.map((a: any) => a?.id)
                if (mpIds && mpIds?.length > 0) {
                    channelMpAccounts = [...channelMpAccounts, ...mpIds]
                    if (wechatInfoList) {

                    }
                }
                if (adqIds && adqIds?.length > 0) {
                    channelAdqAccounts = [...channelAdqAccounts, ...adqIds]
                }

            }
        })

        let { descContext, name, novelName, title, lastCanvasType, pageContextList, supportInfoType } = data
        let ajax = topData?.map((item: any, index: number) => {
            let time = new Date().getTime()
            let queryData: any = {}
            queryData['descContext'] = descContext
            queryData['name'] = novelName + '_' + index.toString() + '_' + time + index
            queryData['novelName'] = novelName
            queryData['title'] = title
            queryData['lastCanvasType'] = lastCanvasType
            queryData['supportInfoType'] = supportInfoType

            if (widgetTypeV2 === 'topslider') { // 轮播图
                queryData['thumbUrl'] = item?.componentGroupList?.componentGroup[0]?.componentItem?.pureImageUrl  // 封面缩略图
                queryData['topCanvasType'] = 101 // 顶部组件类型
                item = {
                    ...item,
                    componentCount
                }
            } else if (widgetTypeV2 === 'topimg') {
                queryData['thumbUrl'] = item?.pureImageUrl  // 封面缩略图
                queryData['topCanvasType'] = 41  // 顶部组件类型
                item = {
                    ...item,
                    adLocation,
                    viewType
                }
            } else if (widgetTypeV2 === 'topvideo_new') {
                queryData['topCanvasType'] = 142  // 顶部组件类型
                queryData['videoFileSize'] = item?.fileSize  // 视频文件大小
                queryData['thumbUrl'] = ""  // 封面缩略图
                item = {
                    ...item,
                    adLocation,
                    viewType,
                    styleType
                }
                if (adLocation === 'gh') {
                    if (item?.displayWidth < item?.displayHeight) {
                        item.styleType = '1'
                    } else {
                        item.styleType = '0'
                    }
                }
            }

            let pageContext = pageContextList[0]
            let pageData = JSON.parse(pageContext?.pageContextList)
            pageData[0] = item
            // sumFileSize
            queryData['sumFileSize'] = pageData?.reduce((prev: number, cur: any) => {
                if (cur?.widgetTypeV2 === 'topimg' || cur?.widgetTypeV2 === 'topvideo_new' || cur?.widgetTypeV2 === 'img') {
                    return prev + cur?.fileSize
                } else if (cur?.widgetTypeV2 === 'topslider') {
                    let sliderSize = cur?.componentGroupList?.componentGroup?.reduce((prev1: number, cur1: any) => {
                        return prev1 + cur1?.fileSize
                    }, 0)
                    return prev + sliderSize
                } else {
                    return prev
                }
            }, 0)
            pageContextList = [{ ...pageContext, pageContextList: JSON.stringify(pageData) }]
            queryData['pageContextList'] = pageContextList
            if (channelMpAccounts?.length > 0 || channelAdqAccounts?.length > 0) { // 上传
                return addAndCreateApi({ pageDto: queryData, channelMpAccounts, channelAdqAccounts, channelMpWechatInfoList })
            } else {
                return adsSharePageApi(queryData)
            }
        })
        Promise.all(ajax).then((res: any) => {
            setLoading(false)
            if (res && res.length > 0) {
                let data = res[res.length - 1]
                if (data?.code === 200) {
                    onClose && onClose()
                    ajaxHome && ajaxHome?.refresh()
                    message.success('新增成功')
                } else if (res?.code === 1003 && res?.data?.base64) {
                    setAuthData(res?.data)
                }
            }
        }).catch(() => { setLoading(false) })
    }, [data, topData, widgetTypeV2, channelAccounts, adLocation, viewType, loading, styleType, componentCount])

    // 切换顶部素材类型
    const changeType = useCallback((value: string) => {
        setWidgetTypeV2(value)
        switch (value) {
            case 'topimg':
                setTopData([{ ...topimgContent }])
                setComponentCount('1')
                break;
            case 'topslider':
                setTopData([{ ...topsliderContent }])
                setComponentCount('3')
                break;
            case 'topvideo':
                setTopData([{ ...topvideoNewContent }])
                break;
        }
    }, [widgetTypeV2, topData, componentCount])

    /** 轮播图位置拖动切换顺序 */
    const onSortEndSlider = useCallback(({ oldIndex, newIndex }: { oldIndex: number, newIndex: number }) => {
        let topDataNew = JSON.parse(JSON.stringify(topData))
        let selectCon = topDataNew[groupIndex]
        let componentGroup = selectCon?.componentGroupList?.componentGroup
        componentGroup = arrayMove(componentGroup, oldIndex, newIndex)
        selectCon = { ...selectCon, componentGroupList: { componentGroup } }
        topDataNew[groupIndex] = selectCon
        setTopData(topDataNew)
    }, [groupIndex, topData])

    /** 轮播图选择图片 */
    const sliderSelect = useCallback((index: number, indexGroup: number) => {
        let topDataNew = JSON.parse(JSON.stringify(topData))
        // 保存点击了第几组的选择图片
        setGroupIndex(indexGroup)
        // 设置activeIndex
        activeIndexHancdle(index, indexGroup)
        // 回填图片
        let selectCon = topDataNew[indexGroup]
        let newSliderImg: { content: string, mediaSize: string, mediaFormat: string }[] = []
        selectCon?.componentGroupList?.componentGroup?.forEach((item: any) => {
            if (item?.componentItem?.pureImageUrl) {
                newSliderImg.push({ content: item?.componentItem?.pureImageUrl, mediaSize: item?.componentItem?.fileSize.toString() || '', mediaFormat: item?.componentItem?.img_type.toString() })
            }
        })
        setSliderImgContent(newSliderImg)
        setSelectImgVisible(true)
    }, [groupIndex, topData, sliderImgContent, selectImgVisible])

    /** 选择单张图片 */
    const clickUpdateImg = useCallback((index: number) => {
        setSliderImgContent([])
        setSelectImgVisible(true)
        setGroupIndex(index)
    }, [sliderImgContent, selectImgVisible, groupIndex])

    /** 添加素材组 */
    const addTopData = useCallback(() => {
        switch (widgetTypeV2) {
            case 'topimg':
                topData.push({ ...topimgContent })
                setTopData([...topData])
                break
            case 'topslider':
                let newGroup = Array(Number(componentCount)).fill('').map(() => ({
                    id: 'slider_1627457838609_16',
                    componentItem: {
                        type: '41',
                        pureImageUrl: '',
                        imageMd5: '',
                        img_name: 'slider',
                        img_type: '',
                        paddingTop: 0,
                        paddingBottom: 0,
                        paddingLeft: 0,
                        paddingRight: 0,
                        imageHeight: 750,
                        imageWidth: 750,
                        initWidth: 800,
                        initHeight: 800,
                        fileSize: 0,
                        materialId: ''
                    }
                }))
                topData.push({
                    ...topsliderContent,
                    componentGroupList: {
                        componentGroup: [...newGroup]
                    }
                })
                setTopData([...topData])
                break
            case 'topvideo_new':
                topData.push({ ...topvideoNewContent })
                setTopData([...topData])
                break
        }
    }, [widgetTypeV2, topData, componentCount])
    /**删除组 */
    const del = useCallback((index: number) => {
        let newTopData = topData.filter((item, eq) => eq !== index)
        setTopData(newTopData)
    }, [topData])
    /** 设置轮播图个数 */
    const setCount = useCallback((value: string) => {
        setComponentCount(value)
        if (topData?.length > 0) {
            let selectCon = topData[0] as TopSlider
            if (selectCon?.widgetTypeV2 === 'topslider') {
                let componentGroup = selectCon?.componentGroupList?.componentGroup
                if (componentGroup?.length > Number(value)) { // 减少
                    let newTopData = topData.map((item: any) => {
                        let componentGroup = item?.componentGroupList?.componentGroup
                        return {
                            ...item,
                            componentGroupList: {
                                ...item.componentGroupList,
                                componentGroup: [...componentGroup?.splice(0, Number(value))]
                            }
                        }
                    })
                    setTopData([...newTopData])
                } else { // 增加
                    let newGroup = Array(Number(value) - componentGroup?.length).fill('').map(() => ({
                        id: 'slider_1627457838609_16',
                        componentItem: {
                            type: '41',
                            pureImageUrl: '',
                            imageMd5: '',
                            img_name: 'slider',
                            img_type: '',
                            paddingTop: 0,
                            paddingBottom: 0,
                            paddingLeft: 0,
                            paddingRight: 0,
                            imageHeight: 750,
                            imageWidth: 750,
                            initWidth: 800,
                            initHeight: 800,
                            fileSize: 0,
                            materialId: ''
                        }
                    }))
                    let newTopData = topData.map((item: any) => {
                        let componentGroup = item?.componentGroupList?.componentGroup
                        return {
                            ...item,
                            componentGroupList: {
                                ...item.componentGroupList,
                                componentGroup: [...componentGroup, ...newGroup]
                            }
                        }
                    })
                    setTopData([...newTopData])
                }
            }

        }

    }, [componentCount, topData])

    /** 设置图片外层样式 */
    const setImgViewType = useCallback((value: string) => {
        setViewType(value)
        setTopData(topData.map((item: any) => ({ ...item, pureImageUrl: '' })))
    }, [viewType, topData])

    // 设置选择的图片
    const setImg = useCallback((value: any[]) => {
        let topDataNew = JSON.parse(JSON.stringify(topData))
        switch (widgetTypeV2) {
            case 'topimg':
                topDataNew[groupIndex] = {
                    ...topDataNew[groupIndex],
                    pureImageUrl: value[0]?.content,
                    fileSize: Number(value[0]?.mediaSize),
                    initWidth: Number(value[0]?.width),
                    initHeight: Number(value[0]?.height),
                    img_type: value[0]?.mediaFormat,
                    imageWidth: 750,
                    imageHeight: Number(value[0]?.width) === Number(value[0]?.height) ? 750 : Number(value[0]?.height)
                }
                break;
            case 'topslider':
                let componentGroup = topDataNew[groupIndex]?.componentGroupList?.componentGroup
                componentGroup = componentGroup?.map((item: { componentItem: { pureImageUrl: string, fileSize: number } }, index: number) => {
                    return {
                        ...item,
                        componentItem: {
                            ...item.componentItem,
                            pureImageUrl: value[index] && JSON.stringify(value[index]) !== '{}' ? value[index].content : '',
                            fileSize: value[index] && JSON.stringify(value[index]) !== '{}' ? value[index].mediaSize : 0,
                            img_type: value[index] && JSON.stringify(value[index]) !== '{}' ? value[0]?.mediaFormat : ''
                        }
                    }
                })
                topDataNew[groupIndex] = {
                    ...topDataNew[groupIndex],
                    componentGroupList: {
                        componentGroup
                    }
                }
                break;
            case 'topvideo_new':
                topDataNew[groupIndex] = {
                    ...topDataNew[groupIndex],
                    videoUrl: value[0]?.content,
                    fileSize: Number(value[0]?.mediaSize),
                    BitRate: value[0]?.videoBitRate || 0,
                    videoDuration: value[0]?.videoLength || 0,
                    displayWidth: Number(value[0]?.width),
                    displayHeight: Number(value[0]?.height)
                }
                // 设置宽高
                if (adLocation === 'sns') { // 朋友圈信息流
                    if (viewType === '0') { // 常规广告
                        if (styleType === '0') { // 横板视频
                            let bit = Math.ceil(Number(value[0]?.width) / Number(value[0]?.height) * 10) / 10
                            if (bit === 1.8) {
                                topDataNew[groupIndex]['initWidth'] = 640
                                topDataNew[groupIndex]['initHeight'] = 360
                            } else {
                                topDataNew[groupIndex]['initWidth'] = 640
                                topDataNew[groupIndex]['initHeight'] = 480
                            }
                        } else { // 竖版视频
                            if (initHeight === 1536) {
                                topDataNew[groupIndex]['initWidth'] = 750
                            } else if (initHeight === 1334) {
                                topDataNew[groupIndex]['initWidth'] = 750
                            } else {
                                topDataNew[groupIndex]['initWidth'] = 720
                            }
                            topDataNew[groupIndex]['initHeight'] = initHeight
                        }
                    } else { // 卡片广告
                        // if (topDataNew[groupIndex]?.outerUseTopMaterial === '0') { // 顶部素材不用于广告外层 不勾

                        // } else if (topDataNew[groupIndex]?.outerUseTopMaterial === '1') { // 顶部素材不用于广告外层 勾选
                        //     if (topDataNew[groupIndex]?.type === '61') { // 短视频

                        //     } else if (topDataNew[groupIndex]?.type === '62') { // 长视频

                        //     }
                        // }
                    }
                } else { // 公众号及其它
                    topDataNew[groupIndex]['initWidth'] = Number(value[0]?.width)
                    topDataNew[groupIndex]['initHeight'] = Number(value[0]?.height)
                }
                break;
        }
        setTopData(topDataNew)
    }, [widgetTypeV2, groupIndex, topData, adLocation, viewType, styleType, initHeight])

    /** 设置activeIndex */
    const activeIndexHancdle = useCallback((index: number, indexGroup: number) => {
        let topDataNew = JSON.parse(JSON.stringify(topData))
        // 设置activeIndex
        topDataNew[indexGroup] = {
            ...topDataNew[indexGroup],
            activeIndex: index
        }
        setTopData(topDataNew)
    }, [topData])

    /** 选择公众号 */
    const selectAccount = useCallback(() => {
        setIsUpload(false)
        setSelectAccShow(true)
    }, [isUpload, selectAccShow])

    return <Modal
        bodyStyle={{ height: 600, overflowY: 'auto' }}
        title="批量复制推广页"
        visible={visible}
        onCancel={hideHandle}
        confirmLoading={loading}
        onOk={handleOk}
        width={1000}
        className={style1.batchCopy}
        maskClosable={false}
    >
        {/* 选择图片视频 */}
        {selectImgVisible && <SelectImg visible={selectImgVisible} hideModel={() => { setSelectImgVisible(false) }} num={Number(componentCount)} onChange={setImg} listParams={imgSize} sliderImgContent={sliderImgContent} imgType={imgType} isFootlock={isFootlock}></SelectImg>}
        {selectAccShow && <SelectAccount show={selectAccShow} onClose={() => { setSelectAccShow(false) }} onChange={(e: any) => { setChannelAccounts(e); setSelectAccShow(false) }} channelAccounts={channelAccounts} />}
        {/* 授权登录 */}
        <AdLogin value={authData} onChange={() => { message.success('请点击按钮再次提交'); setAuthData({ code: "", base64: "" }) }} onClose={() => { setAuthData({ code: "", base64: "" }) }} />
        <div className={style1.info}>
            <div className={style1.items}>
                <div className={style1.item}>
                    <label className={style1.label}>推广页名称:</label>
                    <span>{data?.name}</span>
                </div>
                <div className={style1.item}>
                    <label className={style1.label}>小说:</label>
                    <span>{data?.novelName}</span>
                </div>
            </div>
            <div className={style1.items}>
                <div className={style1.item}>
                    <label className={style1.label}>分享标题:</label>
                    <span>{data?.title}</span>
                </div>
                <div className={style1.item}>
                    <label className={style1.label}>分享描述:</label>
                    <span>{data?.descContext}</span>
                </div>
            </div>
        </div>

        <div className={style1.title}>顶部素材设置</div>
        <BcForm name="顶部素材类型">
            <Select value={widgetTypeV2} style={{ width: 180 }} onChange={(e) => { changeType(e) }} placeholder="请选择顶部素材类型">
                <Select.Option value="topimg">顶部图片</Select.Option>
                <Select.Option value="topslider">顶部轮播图</Select.Option>
                <Select.Option value="topvideo_new">顶部视频</Select.Option>
            </Select>
        </BcForm>
        {widgetTypeV2 === "topimg" ? <>
            <div className={style1.title}>广告位与样式</div>
            <BcForm name="广告位">
                <Radio.Group onChange={(e) => {
                    setAdLocation(e.target.value)
                    if (topData?.length > 0) {
                        setTopData(topData?.map((item: any) => ({ ...item, pureImageUrl: '' })))
                    }
                }} value={adLocation} size='small'>
                    <Radio value='sns'>朋友圈信息流</Radio>
                    <Radio value='gh'>公众号及其他</Radio>
                </Radio.Group>
            </BcForm>
            {adLocation === 'sns' && <BcForm name="外层样式">
                <Select value={viewType} style={{ width: 100 }} onChange={(e) => { setImgViewType(e) }}>
                    <Select.Option value="0">常规广告</Select.Option>
                    <Select.Option value="1">卡片广告</Select.Option>
                </Select>
            </BcForm>}
        </> : widgetTypeV2 === "topslider" ? <>
            <div className={style1.title}>素材设置</div>
            <BcForm name="图片数量">
                <Radio.Group onChange={(e) => { setCount(e.target.value) }} value={componentCount} size='small'>
                    <Radio.Button value='3'>3张</Radio.Button>
                    <Radio.Button value='4'>4张</Radio.Button>
                    <Radio.Button value='6'>6张</Radio.Button>
                </Radio.Group>
            </BcForm>
        </> : widgetTypeV2 === "topvideo_new" ? <>
            <div className={style1.title}>广告位与样式</div>
            <BcForm name="广告位">
                <Radio.Group onChange={(e) => {
                    setAdLocation(e.target.value);
                    if (topData?.length > 0) {
                        setTopData(topData?.map((item: any) => ({ ...item, videoUrl: '' })))
                    }
                    setViewType('0');
                    setStyleType('0');
                }} value={adLocation} size='small'>
                    <Radio value='sns'>朋友圈信息流</Radio>
                    <Radio value='gh'>公众号及其他</Radio>
                </Radio.Group>
            </BcForm>
            {adLocation === 'sns' && <BcForm name="外层样式">
                <Select value={viewType} style={{ width: 100 }} onChange={(e) => { setImgViewType(e) }}>
                    <Select.Option value="0">常规广告</Select.Option>
                    <Select.Option value="1" disabled>卡片广告</Select.Option>
                </Select>
            </BcForm>}
            {
                adLocation === 'sns' && viewType === '0' && <div className="adui-form-item">
                    <div className="adui-form-label">视频类型</div>
                    <div className="adui-form-control">
                        <Radio.Group onChange={(e) => {
                            setStyleType(e.target.value);
                            if (topData?.length > 0) {
                                setTopData(topData?.map((item: any) => ({ ...item, videoUrl: '' })))
                            }
                        }} value={styleType} size='small'>
                            <Radio value='0'>横板视频</Radio>
                            <Radio value='1'>竖版视频</Radio>
                        </Radio.Group>
                    </div>
                </div>
            }
            {/* {
                adLocation === 'sns' && viewType === '1' && <div className="adui-form-item">
                    <div className="adui-form-label">外层素材</div>
                    <div className="adui-form-control">
                        <Checkbox onChange={(e: CheckboxChangeEvent) => { outerUseTopMaterialHandle(e.target.checked) }} checked={outerUseTopMaterial === '0' ? false : true}>顶部素材不用于广告外层</Checkbox>
                    </div>
                </div>
            } */}
            {adLocation === 'sns' && styleType === '1' && <div className="adui-form-item" style={{ alignItems: 'flex-start' }}>
                <div className="adui-form-label" style={{ marginTop: 2 }}>视频尺寸</div>
                <div className="adui-form-control">
                    <Radio.Group value={initHeight} onChange={(e) => {
                        setInitHeight(e.target.value)
                        if (topData?.length > 0) {
                            setTopData(topData?.map((item: any) => ({ ...item, videoUrl: '' })))
                        }
                    }}>
                        <Radio value={1536}>750像素 x 1536像素</Radio>
                        <Radio value={1334}>750像素 x 1334像素</Radio>
                        <Radio value={1280}>720像素 x 1280像素</Radio>
                    </Radio.Group>
                </div>
            </div>}
        </> : <></>
        }

        <div style={{ height: 1, backgroundColor: '#e2e2e2', marginBottom: 10 }}></div>

        {
            widgetTypeV2 === "topimg" || widgetTypeV2 === "topslider" || widgetTypeV2 === "topvideo_new" ? <>
                <div className={style1.title} style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <span>
                        顶部素材
                        <span style={{ color: 'red' }}>*</span>
                        <span style={{ fontSize: 14, color: '#696969', marginLeft: 10, fontWeight: 'normal' }}>素材组数量：{topData.length} 组</span>
                    </span>
                    <Button type="primary" icon={<PlusOutlined />} onClick={() => { addTopData() }}>添加素材组</Button>
                </div>
                {widgetTypeV2 === "topimg" ?
                    <div className={style1.materials}>
                        {
                            topData?.map((item: any, index: number) => {
                                return <div key={index} className={style1.materialImg}>
                                    <BcForm
                                        name={<div>
                                            <span>素材组{index >= 9 ? (index + 1).toString() : '0' + (index + 1).toString()}</span>
                                            <div style={{ fontSize: 12, color: '#169BD5', textAlign: 'center' }}>图片({item.pureImageUrl ? 1 : 0}/1)</div>
                                        </div>}
                                        flex='flex-start'
                                    >
                                        <div className={style1.box}>
                                            <div className="adui-form-control">
                                                <div className={`upload-img-item ${item.pureImageUrl ? 'upload-img-item_uploaded' : ''}`}>
                                                    {item.pureImageUrl ? <div className="upload-img-item-inner" style={{ backgroundImage: `url(${item.pureImageUrl})` }}>
                                                        <div className='upload-img-item-action' onClick={() => { clickUpdateImg(index) }}>
                                                            <RetweetOutlined />
                                                        </div>
                                                    </div>
                                                        :
                                                        <div className="upload-img-item-inner" onClick={() => { clickUpdateImg(index) }}>
                                                            <PlusOutlined />
                                                        </div>}
                                                </div>
                                            </div>
                                            {topData?.length > 1 && <Popconfirm placement="topLeft" title="确定删除当前素材组？" onConfirm={() => { del(index) }} okText="Yes" cancelText="No">
                                                <Button type="link" danger icon={<DeleteOutlined />} size='small' className={style1.del}></Button>
                                            </Popconfirm>}
                                        </div>
                                    </BcForm>
                                </div>
                            })
                        }
                    </div>
                    : widgetTypeV2 === "topslider" ?
                        <div className={style1.materials}>
                            {topData.map((item1: any, index1: number) => {
                                return <div className={style1.material} key={index1} onMouseDown={() => { setGroupIndex(index1) }}>
                                    <BcForm
                                        name={<div>
                                            <span>素材组{index1 >= 9 ? (index1 + 1).toString() : '0' + (index1 + 1).toString()}</span>
                                            <div style={{ fontSize: 12, color: '#169BD5', textAlign: 'center' }}>图片({item1?.componentGroupList?.componentGroup?.reduce((prev: number, cur: { componentItem: { pureImageUrl: string } }) => cur?.componentItem?.pureImageUrl ? prev + 1 : prev, 0)}/{componentCount})</div>
                                        </div>}
                                        flex='flex-start'
                                    >
                                        <div className={style1.box}>
                                            <SortableUlList axis='xy' onSortEnd={onSortEndSlider} useDragHandle>
                                                {item1?.componentGroupList?.componentGroup?.map((item: any, index: number) => {
                                                    let { componentItem } = item
                                                    if (componentItem?.pureImageUrl) {
                                                        return <SortableItemLi key={`slider-${index}`} index={index} isActive={item1?.activeIndex === index} pureImageUrl={componentItem?.pureImageUrl} click={() => { sliderSelect(index, index1) }} setActiveIndex={() => { activeIndexHancdle(index, index1) }}></SortableItemLi>
                                                    } else {
                                                        return <SortableItemNoLi key={`slider-${index}`} index={index} isActive={item1?.activeIndex === index} click={() => { sliderSelect(index, index1) }}></SortableItemNoLi>
                                                    }
                                                })}
                                            </SortableUlList>
                                            {topData?.length > 1 && <Popconfirm placement="topLeft" title="确定删除当前素材组？" onConfirm={() => { del(index1) }} okText="Yes" cancelText="No">
                                                <Button type="link" danger icon={<DeleteOutlined />} size='small' className={style1.del}></Button>
                                            </Popconfirm>}
                                        </div>
                                    </BcForm>
                                </div>
                            })}
                        </div> : <>
                            {/* topvideo_new */}
                            <div className={style1.materials}>
                                {
                                    topData?.map((item: any, index: number) => {
                                        return <div key={index} className={style1.materialImg}>
                                            <BcForm
                                                name={<div>
                                                    <span>素材组{index >= 9 ? (index + 1).toString() : '0' + (index + 1).toString()}</span>
                                                    <div style={{ fontSize: 12, color: '#169BD5', textAlign: 'center' }}>视频({item.videoUrl ? 1 : 0}/1)</div>
                                                </div>}
                                                flex='flex-start'
                                            >
                                                <div className={style1.box}>
                                                    <div className="adui-form-control">
                                                        <div className={`upload-img-item ${item.pureImageUrl ? 'upload-img-item_uploaded' : ''}`}>
                                                            {item.videoUrl ? <div className="upload-img-item-inner">
                                                                <video src={item.videoUrl} style={{ maxWidth: 70, maxHeight: 70 }}></video>
                                                                <div className='upload-img-item-action' onClick={() => { clickUpdateImg(index) }}>
                                                                    <RetweetOutlined />
                                                                </div>
                                                            </div>
                                                                :
                                                                <div className="upload-img-item-inner" onClick={() => { clickUpdateImg(index) }}>
                                                                    <PlusOutlined />
                                                                </div>}
                                                        </div>
                                                    </div>
                                                    {topData?.length > 1 && <Popconfirm placement="topLeft" title="确定删除当前素材组？" onConfirm={() => { del(index) }} okText="Yes" cancelText="No">
                                                        <Button type="link" danger icon={<DeleteOutlined />} size='small' className={style1.del}></Button>
                                                    </Popconfirm>}
                                                </div>
                                            </BcForm>
                                        </div>
                                    })
                                }
                            </div>
                        </>}
            </> : <></>
        }
        <div style={{ height: 1, backgroundColor: '#e2e2e2', marginBottom: 10 }}></div>
        <div className={style1.title}>同步公众号</div>

        {!isWxBt && <BcForm name="是否上传公众号">
            <Space>
                <Button type='link' onClick={() => { selectAccount() }}>{channelAccounts?.some((item: any) => (item?.MP?.length > 0 || item?.ADQ?.length > 0)) ? '修改' : '选择'}上传的公众号</Button>
                <Radio onChange={() => { setIsUpload(true); setChannelAccounts([]) }} checked={isUpload}>暂时不上传</Radio>
            </Space>
        </BcForm>}
        {
            channelAccounts?.some((item: any) => (item?.MP?.length > 0 || item?.ADQ?.length > 0)) && <BcForm name="已选公众号" flex='flex-start'>
                <div className={style1.selectChannels}>
                    {channelAccounts?.map((item: { id: number, accountName: string, MP?: any[], ADQ?: any[] }) => {
                        if ((item?.MP && item?.MP?.length > 0) || (item?.ADQ && item?.ADQ?.length > 0)) {
                            return <div className={style1.selectChannel} key={item?.id}>
                                {item?.MP && item?.MP?.length > 0 && <div>
                                    <h3>{item?.accountName + '-MP'}</h3>
                                    {item?.MP?.map((mp: { id: number, uname: string }) => <p key={mp?.id}>{mp?.uname}</p>)}
                                </div>}
                                {item?.ADQ && item?.ADQ?.length > 0 && <div key={item?.id}>
                                    <h3>{item?.accountName + '-ADQ'}</h3>
                                    {item?.ADQ?.map((adq: { id: number, uname: string, uid: number }) => <p>{adq?.uname}-{adq?.uid}</p>)}
                                </div>}
                            </div>
                        } else {
                            return null
                        }
                    })}
                </div>
            </BcForm>
        }
    </Modal>
}

export default React.memo(BathLauCopy)