import React, { useContext, useEffect, useState } from "react"
import style from '../index.less'
import styles from './index.less'
import { DispatchAddelivery } from "..";
import { Button, Empty, message, Tooltip, Typography } from "antd";
import { FolderOpenOutlined, RedoOutlined, SyncOutlined } from "@ant-design/icons";
import AddMaterial from "./addMaterial";
import VideoNews from "@/pages/launchSystemNew/components/newsModal/videoNews";
import { shuffleArray } from "@/utils/utils";
import SaveUseImg from "../Save/saveUseImg";
import ImageXXXC from "@/pages/launchSystemV3/components/AdsComponent/ImageXXXC";
const { Title } = Typography;

const Material: React.FC<{ adData?: any[] }> = ({ adData }) => {

    /***************************************/
    const { materialData, addelivery, setAddelivery, clearData, accountCreateLogs, putInType, adLength, setIsDqSubmit } = useContext(DispatchAddelivery)!;
    const { dynamic, dynamicMaterialDTos, mediaType, adgroups: { marketingAssetOuterSpec, marketingCarrierType }, dynamicCreativesTextDTOS } = addelivery
    const { creativeTemplateId, deliveryMode, dynamicCreativeSwitch } = dynamic

    const [newVisible, setNewVisible] = useState<boolean>(false)
    const [mType, setMtype] = useState<string>()
    /***************************************/

    useEffect(() => {
        if (materialData && Object.keys(materialData).length > 0) {
            let type = Object.keys(materialData)[0];
            setMtype(type)
        }
    }, [materialData])

    const handleDisruption = () => {
        let count = dynamicMaterialDTos?.dynamicGroup?.length
        if (count) {
            let shuffleArrayData = shuffleArray(Array(count).fill(undefined).map((_, index) => index))
            let newDynamicGroup: any[] = [], newDynamicCreativesTextDetailDTOList: any[] = []
            shuffleArrayData.forEach(index => {
                newDynamicGroup.push(dynamicMaterialDTos.dynamicGroup[index])
                if (dynamicCreativesTextDTOS?.type === 1 && dynamicCreativesTextDTOS?.dynamicCreativesTextDetailDTOList?.length) {
                    newDynamicCreativesTextDetailDTOList.push(dynamicCreativesTextDTOS.dynamicCreativesTextDetailDTOList[index])
                } else {
                    newDynamicCreativesTextDetailDTOList = dynamicCreativesTextDTOS?.dynamicCreativesTextDetailDTOList
                }
            })
            setIsDqSubmit?.(false)
            setAddelivery({
                ...addelivery,
                dynamicMaterialDTos: {
                    ...dynamicMaterialDTos,
                    dynamicGroup: newDynamicGroup
                },
                dynamicCreativesTextDTOS: {
                    ...dynamicCreativesTextDTOS,
                    dynamicCreativesTextDetailDTOList: newDynamicCreativesTextDetailDTOList
                }
            })
        }
    }

    // 组件化创意里面所有素材打乱
    const handleDisruptionComponent = () => {
        let count = dynamicMaterialDTos?.dynamicGroup?.length
        if (count) {
            const dynamicGroupList = shuffleArray(dynamicMaterialDTos.dynamicGroup.reduce((cur: any[], pre: { list: any[] }) => {
                cur.push(...pre.list)
                return cur
            }, []))
            const newDynamicGroup = JSON.parse(JSON.stringify(dynamicMaterialDTos.dynamicGroup)).map((item: { list: any[] }) => {
                const length = item.list.length
                return { list: dynamicGroupList.splice(0, length) }
            })
            setIsDqSubmit?.(false)
            setAddelivery({
                ...addelivery,
                dynamicMaterialDTos: {
                    ...dynamicMaterialDTos,
                    dynamicGroup: newDynamicGroup
                }
            })
        }
    }

    return <div className={`${style.settingsBody_content_row} ${style.row4}`}>
        <div className={style.title}>
            <span>
                创意素材
                <span className={style.selected}>已选 {dynamicMaterialDTos?.dynamicGroup?.length || 0}</span>
                {dynamicMaterialDTos?.dynamicGroup?.length > 1 && <Tooltip title="随机打乱素材">
                    <a style={{ marginLeft: 16, fontSize: 12 }} onClick={handleDisruption}><SyncOutlined /></a>
                </Tooltip>}
                {dynamicMaterialDTos?.dynamicGroup?.length > 1 && deliveryMode === 'DELIVERY_MODE_COMPONENT' && <Tooltip title="组件化创意所有素材随机打乱">
                    <a style={{ marginLeft: 16, fontSize: 12, color: '#f50' }} onClick={handleDisruptionComponent}><SyncOutlined /></a>
                </Tooltip>}
            </span>
            {(dynamicMaterialDTos && Object.keys(dynamicMaterialDTos).length > 0) ? <Button
                type="link"
                size="small"
                style={{ fontSize: 11, padding: 0 }}
                onClick={() => {
                    setAddelivery({ ...addelivery, dynamicMaterialDTos: {}, dynamicCreativesTextDTOS: {} })
                    setIsDqSubmit?.(false)
                }}
            ><RedoOutlined />清空</Button> : null}
        </div>
        <div className={style.detail}>
            <div className={style.detail_body}>
                {(dynamicMaterialDTos && Object.keys(dynamicMaterialDTos).length > 0) ?
                    <>
                        <Title level={5} style={{ fontSize: 12 }}>{mediaType === 0 ? '全账号复用' : mediaType === 1 ? '平均分配到广告' : mediaType === 2 ? '顺序分配到广告' : mediaType === 3 ? '账号下平均分配到广告' : null}</Title>
                        <div className={style.detail_body_m}>
                            {dynamicMaterialDTos.dynamicGroup.map((item: any, index: number) => {
                                // if (deliveryMode === 'DELIVERY_MODE_CUSTOMIZE' || dynamicCreativeSwitch) {
                                if (deliveryMode === 'DELIVERY_MODE_CUSTOMIZE') {
                                    return <div key={index} style={{ width: (deliveryMode === 'DELIVERY_MODE_CUSTOMIZE' || dynamicCreativeSwitch) ? [641, 642, 643, 2277].includes(creativeTemplateId) ? '100%' : [720, 721, 722, 1529, 618].includes(creativeTemplateId) ? '50%' : '25%' : '100%' }}>
                                        <Title level={5} style={{ fontSize: 12 }}>创意组{index + 1}</Title>
                                        {mType ? ['short_video', 'video'].includes(mType) ? <div className={style.video}>
                                            <VideoNews src={item?.video_id?.url || item?.short_video1?.url} keyFrameImageUrl={item?.video_id?.keyFrameImageUrl || item?.short_video1?.keyFrameImageUrl} />
                                            {item?.cover_id && <div className={style.cover_image}>
                                                <img src={item?.cover_id?.url} />
                                            </div>}
                                        </div> : ['image_list'].includes(mType) ? <div className={style.imageList}>
                                            {item?.image_list?.map((item: { url: string | undefined; }, index: undefined) => <div className={style.cover_image} key={index}>
                                                <img src={item?.url} />
                                            </div>)}
                                        </div> : ['element_story'].includes(mType) ? <div className={style.imageList}>
                                            {item?.element_story?.map((item: { url: string | undefined; }, index: undefined) => <div className={style.cover_image} key={index}>
                                                <img src={item?.url} />
                                            </div>)}
                                        </div> : ['image'].includes(mType) ? <div className={style.cover_image}>
                                            <img src={item?.image_id?.url} />
                                        </div> : null : null}
                                    </div>
                                } else {
                                    return <div key={index} style={{ width: '100%' }}>
                                        <Title level={5} style={{ fontSize: 12 }}>创意组{index + 1}</Title>
                                        <div style={{ display: 'flex', gap: 5, flexWrap: 'wrap' }}>
                                            {item?.list?.map((item: any, index: number) => {
                                                if (item?.componentSubType?.includes('IMAGE_LIST')) {
                                                    return <div className={styles.boxList_body_item} key={index} style={{ width: 60, height: 60 }}>
                                                         <div className={styles.tag}>{item?.urlList?.length}图</div>
                                                        <div className={styles.content} style={{ width: 60, height: 60 }}>
                                                            <ImageXXXC imageList={item?.urlList} placement="top" style={{ width: '100%', height: '100%' }} />
                                                        </div>
                                                    </div>
                                                } else if (Array.isArray(item)) {
                                                    let length = item.length
                                                    return <div className={styles.boxList_body_item} key={index} style={{ width: 60, height: 60 }}>
                                                        <div className={styles.tag}>{length}图</div>
                                                        <div className={styles.content} style={{ width: 60, height: 60 }}>
                                                            {item.map((l, i) => <img src={l?.url} key={i} style={{ width: length >= 6 ? 19.9 : 29.9 }} />)}
                                                        </div>
                                                    </div>
                                                } else if (item?.url?.includes('mp4') || item?.keyFrameImageUrl) {
                                                    return <div className={styles.boxList_body_item} key={index} style={{ width: 60, height: 60 }}>
                                                        <div className={styles.content} style={{ width: 60, height: 60 }}>
                                                            <VideoNews src={item?.url} style={{ width: 60, height: 60 }} keyFrameImageUrl={item?.keyFrameImageUrl} maskBodyStyle={{ backgroundColor: "rgba(242, 246, 254, 0.1)" }} />
                                                        </div>
                                                    </div>
                                                } else {
                                                    return <div className={styles.boxList_body_item} key={index} style={{ width: 60, height: 60 }}>
                                                        <div className={styles.content} style={{ width: 60, height: 60 }}><img src={item?.url} /></div>
                                                    </div>
                                                }
                                            })}
                                        </div>
                                    </div>
                                }

                            })}
                        </div>
                    </> :
                    <div className={style.empty_block}>
                        <Empty description="暂无素材" imageStyle={{ height: 50 }} />
                    </div>}
                {((dynamic && Object.keys(dynamic).length > 0) && !(materialData && Object.keys(materialData).length > 0)) && <div className={style.ad_config}>
                    <div className={style.ad_config_item}>无需设置创意素材</div>
                </div>}
            </div>
            <div className={style.detail_footer}>
                <Button
                    disabled={!(dynamic && Object.keys(dynamic)?.length > 0)}
                    type="link"
                    icon={<FolderOpenOutlined />}
                    style={{ padding: 0, fontSize: 12 }}
                    onClick={() => {
                        if (!(adData && adData?.length > 0)) {
                            if (['MARKETING_TARGET_TYPE_FICTION'].includes(marketingAssetOuterSpec?.marketingTargetType) && !accountCreateLogs?.some(item => item?.productList?.length)) {
                                message.error('请先选择小说')
                                return
                            }
                            if ((['MARKETING_TARGET_TYPE_WECHAT_OFFICIAL_ACCOUNT'].includes(marketingAssetOuterSpec?.marketingTargetType) || marketingCarrierType === 'MARKETING_CARRIER_TYPE_WECHAT_OFFICIAL_ACCOUNT') && !accountCreateLogs?.some(item => item?.wechatChannelList?.length)) {
                                message.error('请先选择公众号')
                                return
                            }
                        }
                        setNewVisible(true)
                    }}
                >
                    选择素材
                </Button>
                {dynamic && deliveryMode && <SaveUseImg
                    putInType={putInType}
                    type={deliveryMode === "DELIVERY_MODE_CUSTOMIZE" ? creativeTemplateId : deliveryMode}
                    onChange={({ dynamicMaterialDTos, mediaType, dynamicCreativesTextDTOS }) => {
                        setIsDqSubmit?.(false)
                        setAddelivery({ ...addelivery, dynamicMaterialDTos, mediaType: mediaType as any, dynamicCreativesTextDTOS })
                    }}
                />}
            </div>

        </div>

        {newVisible && <AddMaterial
            adLength={adLength}
            creativeTemplateId={creativeTemplateId}
            value={{ dynamicMaterialDTos, mediaType }}
            materialData={materialData}
            deliveryMode={deliveryMode}
            dynamicCreativeSwitch={dynamicCreativeSwitch}
            visible={newVisible}
            onClose={() => {
                setNewVisible(false)
            }}
            putInType={putInType}
            accountCreateLogs={accountCreateLogs}
            onChange={({ dynamicMaterialDTos, mediaType }) => {
                setIsDqSubmit?.(false)
                const newAddelivery = { ...addelivery, dynamicMaterialDTos, mediaType }
                if (addelivery.mediaType !== mediaType && mediaType !== 1 && addelivery.dynamicCreativesTextDTOS?.type === 4) {
                    newAddelivery.dynamicCreativesTextDTOS = {}
                }
                if (newAddelivery.dynamicCreativesTextDTOS && Object.keys(newAddelivery.dynamicCreativesTextDTOS).length && dynamicMaterialDTos.dynamicGroup.length !== addelivery?.dynamicMaterialDTos?.dynamicGroup?.length) {
                    if (addelivery.dynamicCreativesTextDTOS?.type === 1) {
                        const lengthN = dynamicMaterialDTos.dynamicGroup.length
                        const lengthO = addelivery.dynamicMaterialDTos.dynamicGroup.length
                        const diff = lengthN - lengthO
                        const lengthL = addelivery.dynamicCreativesTextDTOS.dynamicCreativesTextDetailDTOList.length
                        if (diff > 0) {
                            newAddelivery.dynamicCreativesTextDTOS.dynamicCreativesTextDetailDTOList = [...newAddelivery.dynamicCreativesTextDTOS.dynamicCreativesTextDetailDTOList, ...Array(diff).fill({})]
                        } else {
                            newAddelivery.dynamicCreativesTextDTOS.dynamicCreativesTextDetailDTOList = newAddelivery.dynamicCreativesTextDTOS.dynamicCreativesTextDetailDTOList.splice(0, lengthL + diff)
                        }
                    } else if (addelivery.dynamicCreativesTextDTOS?.type === 5) {
                        newAddelivery.dynamicCreativesTextDTOS = {}
                    }

                }
                setAddelivery(newAddelivery)
                setNewVisible(false)
                clearData()
            }}
        />}
    </div>
}

export default React.memo(Material)