import React, { useContext, useEffect, useState } from "react"
import style from '../index.less'
import { Button, message, Tooltip, Typography } from "antd"
import { DispatchAddelivery } from "..";
import { PlusCircleOutlined, RedoOutlined, SyncOutlined } from "@ant-design/icons";
import NewText from "./newText";
import { shuffleArray } from "@/utils/utils";
const { Title, Text } = Typography;


const MaterialText: React.FC<{ adDataGroup?: { [x: number]: any[] } }> = ({ adDataGroup }) => {

    /*************************************/
    const { textData, addelivery, setAddelivery, clearData, putInType, accountCreateLogs, setIsDqSubmit } = useContext(DispatchAddelivery)!;
    const { dynamic, dynamicCreativesTextDTOS, dynamicMaterialDTos, mediaType } = addelivery

    const [addVisible, setAddVisible] = useState<boolean>(false)
    const [descName, setDescName] = useState<string>('')
    const [titleName, setTitleName] = useState<string>('')
    /*************************************/

    useEffect(() => {
        if (textData && Object.keys(textData).length > 0) {
            Object.keys(textData).forEach(key => {
                let item = textData[key]
                let content = item.children.content
                if (key === 'description') {
                    setDescName(content.description)
                } else if (key === 'title') {
                    setTitleName(content.description)
                }
            })
        }
    }, [textData])

    const handleDisruption = () => {
        const textDto: { description: string[] }[] = dynamicCreativesTextDTOS.dynamicCreativesTextDetailDTOList
        if (textDto?.[0]?.description) {
            setIsDqSubmit?.(false)
            const textDtoArr = shuffleArray(textDto.reduce((acc: string[], val) => acc.concat(val.description), []))
            setAddelivery({
                ...addelivery,
                dynamicCreativesTextDTOS: { ...dynamicCreativesTextDTOS, dynamicCreativesTextDetailDTOList: textDto.map(item => ({ description: textDtoArr.splice(0, item.description.length) })) }
            })
        } else {
            message.error('打乱文案出错，请联系管理员')
        }
    }

    return <div className={`${style.settingsBody_content_row} ${style.row5}`}>
        <div className={style.title}>
            <span>
                创意文案
                <span className={style.selected}>已选 {dynamicCreativesTextDTOS?.dynamicCreativesTextDetailDTOList?.length || 0}</span>
                {dynamicCreativesTextDTOS?.dynamicCreativesTextDetailDTOList?.length > 1 && <Tooltip title="随机打乱文案">
                    <a style={{ marginLeft: 8, fontSize: 12 }} onClick={handleDisruption}><SyncOutlined /></a>
                </Tooltip>}
            </span>
            {(dynamicCreativesTextDTOS && Object.keys(dynamicCreativesTextDTOS).length > 0) ? <Button
                type="link"
                size="small"
                style={{ fontSize: 11, padding: 0 }}
                onClick={() => {
                    setAddelivery({ ...addelivery, dynamicCreativesTextDTOS: {} })
                    setIsDqSubmit?.(false)
                }}
            ><RedoOutlined />清空</Button> : null}
        </div>
        <div className={style.detail}>
            <div className={style.detail_body}>
                <Title level={5} style={{ fontSize: 12 }} ellipsis>{dynamicCreativesTextDTOS?.type === 0 ? '全部相同' : dynamicCreativesTextDTOS?.type === 1 ? '按创意组一一对应' : dynamicCreativesTextDTOS?.type === 2 ? '按文案顺序分配' : dynamicCreativesTextDTOS?.type === 3 ? '先分配创意组，文案后叉乘' : dynamicCreativesTextDTOS?.type === 4 ? '创意组和文案叉乘打乱后分配' : dynamicCreativesTextDTOS?.type === 5 ? '创意组和广告分配后与文案一一对应' : null}</Title>
                {dynamicCreativesTextDTOS?.dynamicCreativesTextDetailDTOList?.map((item: { [x: string]: (boolean | React.ReactPortal | null | undefined)[]; }, index: number) => {
                    if (item) {
                        let keys = Object.keys(item)
                        return <div key={index}>
                            {keys.includes('description') ? <>
                                <Title level={5} style={{ fontSize: 12 }}>{descName}</Title>
                                {item['description'].map((t, index) => <div className={style.text} key={index}><Text ellipsis={{ tooltip: true }}>{t}</Text></div>)}
                            </> : keys.includes('title') ? <>
                                <Title level={5} style={{ fontSize: 12 }}>{titleName}</Title>
                                {item['title'].map((t, index) => <div className={style.text} key={index}><Text ellipsis={{ tooltip: true }}>{t}</Text></div>)}
                            </> : null}
                        </div>
                    }
                    return null
                })}
                {((dynamic && Object.keys(dynamic).length > 0) && !(textData && Object.keys(textData).length > 0)) && <div className={style.ad_config}>
                    <div className={style.ad_config_item}>无需设置创意文案</div>
                </div>}
            </div>
            <div className={style.detail_footer}>
                <Button disabled={!(dynamicMaterialDTos && Object.keys(dynamicMaterialDTos)?.length > 0)} type="link" icon={<PlusCircleOutlined />} style={{ padding: 0, fontSize: 12 }} onClick={() => setAddVisible(true)}>添加</Button>
            </div>
        </div>

        {addVisible && <NewText
            value={dynamicCreativesTextDTOS}
            dynamicMaterialDTos={dynamicMaterialDTos}
            mediaType={mediaType}
            accountCreateLogs={accountCreateLogs}
            targetingLength={addelivery?.targeting?.length}
            textData={textData}
            visible={addVisible}
            putInType={putInType}
            deliveryMode={dynamic?.deliveryMode}
            adDataGroup={adDataGroup}
            onClose={() => {
                setAddVisible(false)
            }}
            onChange={(values) => {
                setIsDqSubmit?.(false)
                setAddelivery({ ...addelivery, dynamicCreativesTextDTOS: values })
                setAddVisible(false)
                clearData()
            }}
        />}
    </div>
}

export default React.memo(MaterialText)