import React, { useContext, useEffect, useState } from 'react'
import style from '../index.less'
import { Button, Empty, Typography, message } from 'antd'
import { DispatchAddelivery } from '..';
import { PlusCircleOutlined } from '@ant-design/icons';
import PageModal from '@/pages/launchSystemV3/components/PageModal';
import PageOfficialModal from '@/pages/launchSystemV3/components/PageModal/indexOfficial';
import { PAGE_TYPE_ENUM } from '../../const';
import MiniProgramPage from '@/pages/launchSystemV3/components/PageModal/MiniProgramPage';
const { Title, Text } = Typography;

/**
 * 落地页
 * @returns 
 */
const PageList: React.FC<{ adDataGroup?: { [x: number]: any[] } }> = ({ adDataGroup }) => {

    /********************************/
    const { addelivery, setAddelivery, accountCreateLogs, setAccountCreateLogs, clearData, setIsDqSubmit } = useContext(DispatchAddelivery)!;
    const { dynamic, adgroups, targeting } = addelivery

    const [addVisible, setAddVisible] = useState<boolean>(false)
    const [addOfficialVisible, setAddOfficialVisible] = useState<boolean>(false)
    const [addMiniProgramVisible, setAddMiniProgramVisible] = useState<boolean>(false)
    const [pageType, setPageType] = useState<keyof typeof PAGE_TYPE_ENUM>()
    /********************************/

    // 获取落地页类型
    useEffect(() => {
        if (dynamic?.creativeComponents?.mainJumpInfo?.length) {
            setPageType(dynamic?.creativeComponents?.mainJumpInfo?.[0]?.value?.pageType)
        }
    }, [dynamic])

    const setPageData = ({ data, landingPageType }: { data: PULLIN.AccountCreateLogsProps[]; landingPageType: 0 | 1; }, type: 1 | 2 | 3) => {
        setIsDqSubmit?.(false)
        if (landingPageType === 1) {
            if (adDataGroup && Object.keys(adDataGroup).length) {
                if (data.some(item => {
                    let total = adDataGroup[item.accountId].length
                    let pageLength = item.pageList.length
                    if (total > pageLength) {
                        message.error(`当前${item.accountId}下的广告总数（${total}）大于落地页总数（${pageLength}），平均分配需要落地页总数大于广告总数`)
                        return true
                    }
                    return false
                })) {
                    return
                }
            } else {
                let targetingLength = targeting.length
                const mainJumpInfoLength = dynamic?.creativeComponents?.mainJumpInfo?.length || 1
                if (data.some(item => {
                    let productListLength = item?.productList?.length || 1
                    let total = targetingLength * productListLength
                    let pageLength = item.pageList.length
                    if (mainJumpInfoLength > 1) {
                        if (!(total * mainJumpInfoLength <= pageLength && pageLength % mainJumpInfoLength === 0)) {
                            message.error(`当前${item.accountId}下的广告总数是：${total}，落地页组数是：${mainJumpInfoLength}，平均分配需要落地页总数（${pageLength}）要大于${total * mainJumpInfoLength}并且要是${mainJumpInfoLength}倍数`)
                            return true
                        }
                    } else {
                        if (total > pageLength) {
                            message.error(`当前${item.accountId}下的广告总数（${total}）大于落地页总数（${pageLength}），平均分配需要落地页总数大于广告总数`)
                            return true
                        }
                    }
                    return false
                })) {
                    return
                }
            }
        }
        setAccountCreateLogs(data);
        setAddelivery({ ...addelivery, dynamic: { ...dynamic, landingPageType } })
        switch (type) {
            case 1:
                setAddVisible(false);
                break
            case 2:
                setAddOfficialVisible(false);
                break
            case 3:
                setAddMiniProgramVisible(false);
                break
        }
        clearData()
    }

    return <div className={`${style.settingsBody_content_row} ${style.row6}`}>
        <div className={style.title}>
            <span>{PAGE_TYPE_ENUM[pageType as keyof typeof PAGE_TYPE_ENUM] || '原生推广页'}</span>
        </div>
        <div className={style.detail}>
            <div className={style.detail_body}>
                {[910].includes(dynamic?.creativeTemplateId) && <Title level={5} style={{ fontSize: 12 }}>{dynamic?.landingPageType === 1 ? '平均分配' : '全部相同'}</Title>}
                {accountCreateLogs?.map((item, index) => {
                    return <div key={index}>
                        <Title level={5} style={{ fontSize: 12 }}>{item.accountId}</Title>
                        {item?.pageList?.length ?
                            item?.pageList?.map((page: { pageName: string, pageId: number }) => <div key={page.pageId} className={style.text}><Text ellipsis={{ tooltip: true }}>{page['pageName']}</Text></div>) :
                            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} style={{ margin: 0, fontSize: 12 }} imageStyle={{ height: 18 }} />}
                    </div>
                })}
                {pageType === "PAGE_TYPE_WECHAT_MINI_GAME" && <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={<PlusCircleOutlined />}
                    style={{ padding: 0, fontSize: 12 }}
                    onClick={() => {
                        if (pageType === 'PAGE_TYPE_OFFICIAL') {
                            setAddOfficialVisible(true)
                        } else if (pageType === "PAGE_TYPE_WECHAT_MINI_PROGRAM") {
                            setAddMiniProgramVisible(true)
                        } else {
                            setAddVisible(true)
                        }
                    }}
                >
                    添加
                </Button>
            </div>
        </div>

        {/* 原生推广页 */}
        {addVisible && <PageModal
            data={accountCreateLogs}
            adgroups={adgroups}
            dynamic={dynamic}
            visible={addVisible}
            onClose={() => {
                setAddVisible(false)
            }}
            onChange={(data) => {
                setPageData(data, 1)
            }}
        />}

        {/* 灵鹊落地页 */}
        {addOfficialVisible && <PageOfficialModal
            data={accountCreateLogs}
            adgroups={adgroups}
            dynamic={dynamic}
            visible={addOfficialVisible}
            onClose={() => {
                setAddOfficialVisible(false)
            }}
            onChange={(data) => {
                setPageData(data, 2)
            }}
        />}

        {/* 微信小程序 */}
        {addMiniProgramVisible && <MiniProgramPage
            data={accountCreateLogs}
            adgroups={adgroups}
            dynamic={dynamic}
            visible={addMiniProgramVisible}
            onClose={() => {
                setAddMiniProgramVisible(false)
            }}
            onChange={(data) => {
                setPageData(data, 3)
            }}
        />}
    </div>
}

export default React.memo(PageList)