import React, { useContext, useMemo, useState } from "react"
import style from '../index.less'
import NewCreateAd from "./newCreateAd"
import { DispatchAddelivery } from "..";
import { Button, Modal, Typography } from "antd";
import { EditOutlined } from "@ant-design/icons";
import { AD_STATUS_ENUM, BID_ALL_OCATION_MODE, BID_MODE_ENUM, BID_SCENE_NORMAL_ENUM, DEEP_CONVERSION_ENUM, GOAL_ROAS_ENUM, MARKETING_CARRIER_TYPE_ENUM, MARKETING_GOAL_ENUM, MARKETING_SUB_GOAL_ENUM, MARKETING_TARGET_TYPE_ENUM, MARKETING_TARGET_TYPE_GAME_ENUM, OPTIMIZATIONGOAL_ENUM, ROI_ALL_OCATION_MODE, SITE_SET_ENUM, SMART_BID_TYPE_ENUM, SMART_DELIVERY_GOAL_ENUM, SMART_DELIVERY_PLATFORM_ENUM } from "../../const";
import TimeSeriesLook from "@/pages/launchSystemNew/adq/ad/timeSeriesLook";
import { arraysHaveSameValues } from "@/utils/utils";
import '../../index.less'
import { ShowMiniProgramWechatDetail } from "@/pages/launchSystemV3/tencenTasset/miniProgramWechat";
import { ShowGameAppIdDetail } from "@/pages/launchSystemV3/tencenTasset/game";
import { ShowApplication } from "@/pages/launchSystemV3/tencenTasset/application";

/**
 * 广告信息
 * @returns 
 */
const Ad: React.FC = () => {

    /*****************************/
    const { addelivery, setAddelivery, accountCreateLogs, clearData, setAccountCreateLogs, putInType, setIsDqSubmit } = useContext(DispatchAddelivery)!;
    const { adgroups } = addelivery
    const {
        deliveryMethod, marketingGoal, marketingSubGoal, marketingAssetOuterSpec, marketingCarrierType, automaticSiteEnabled, explorationStrategy, siteSet, prioritySiteSet, searchExpandTargetingSwitch, bidMode, smartBidType, bidScene, bidAmount, optimizationGoal, isConversion, depthConversionEnabled,
        deepConversionSpec, ecomPkamSwitch, autoAcquisitionEnabled, autoAcquisitionBudget, dailyBudget, endDate, beginDate, timeSeries, firstDayBeginTime, configuredStatus, adgroupName, sceneSpec, autoDerivedCreativeEnabled, sysWechatAppId, wxGameAppId, promoteApplicationId, rtaId, rtaTargetId, bidAllocationMode,
        bidAmountMin, bidAmountMax, smartDeliveryPlatform, smartDeliverySceneSpec
    } = adgroups
    const [newVisible, setNewVisible] = useState<boolean>(false)
    /*****************************/

    // 智能投放出价
    const smartModel = useMemo(() => {
        if (deliveryMethod === 'SMART') {
            const goalDto = SMART_DELIVERY_GOAL_ENUM[smartDeliverySceneSpec?.smartDeliveryGoal as keyof typeof SMART_DELIVERY_GOAL_ENUM]
            if ([2, 3].includes(bidAllocationMode)) {
                const data = smartDeliverySceneSpec?.smartDeliveryGoalSpec?.[goalDto?.smartDeliveryGoalSpecName]
                return goalDto?.smartDeliveryGoalSpec?.map(item => <p key={item.field_name} style={{ fontWeight: 'bold', color: '#000' }}>{item.title}： {data?.[item.field_name + 'Min']}-{data?.[item.field_name + 'Max']}{item?.unitTips || ''}</p>)
            } else {
                return goalDto?.smartDeliveryGoalSpec?.map(item => <p key={item.field_name} style={{ fontWeight: 'bold', color: '#000' }}>{item.title}： {smartDeliverySceneSpec?.smartDeliveryGoalSpec?.[goalDto?.smartDeliveryGoalSpecName]?.[item.field_name]}{item?.unitTips || ''}</p>)
            }
        }
        return null
    }, [smartDeliverySceneSpec, deliveryMethod, bidAllocationMode])

    return <>
        <div className={`${style.settingsBody_content_row} ${style.row1}`}>
            <div className={style.title}>
                <span>广告信息</span>
            </div>
            <div className={style.detail}>
                <div className={style.detail_body}>
                    {(adgroups && Object.keys(adgroups).length > 0) ? <>
                        <p style={{ fontWeight: 'bold', color: configuredStatus === 'AD_STATUS_NORMAL' ? '#52c41a' : '#FF4D4F' }}>广告状态：{AD_STATUS_ENUM[configuredStatus as keyof typeof AD_STATUS_ENUM]}</p>
                        <p style={{ fontWeight: 'bold', color: '#000' }}>投放方式：{deliveryMethod === 'SMART' ? '智能投放' : '常规投放'}</p>
                        {deliveryMethod === 'NORMAL' ? <>
                            {putInType === 'NOVEL' ? <>
                                <p>营销目的：{MARKETING_GOAL_ENUM[marketingGoal as keyof typeof MARKETING_GOAL_ENUM]}</p>
                                <p style={{ fontWeight: 'bold', color: '#000' }}>推广产品类型：{MARKETING_TARGET_TYPE_ENUM[marketingAssetOuterSpec?.marketingTargetType as keyof typeof MARKETING_TARGET_TYPE_ENUM]}</p>
                            </> : <>
                                <p>营销目的：{MARKETING_SUB_GOAL_ENUM[marketingSubGoal as keyof typeof MARKETING_SUB_GOAL_ENUM]}</p>
                                <p style={{ fontWeight: 'bold', color: '#000' }}>推广产品类型：{MARKETING_TARGET_TYPE_GAME_ENUM[marketingAssetOuterSpec?.marketingTargetType as keyof typeof MARKETING_TARGET_TYPE_GAME_ENUM]}</p>
                            </>}
                            {marketingAssetOuterSpec?.marketingTargetType === 'MARKETING_TARGET_TYPE_MINI_PROGRAM_WECHAT' ?
                                <ShowMiniProgramWechatDetail id={sysWechatAppId} /> :
                                marketingAssetOuterSpec?.marketingTargetType === 'MARKETING_TARGET_TYPE_WECHAT_MINI_GAME' ?
                                    <ShowGameAppIdDetail appId={wxGameAppId} /> :
                                    null
                            }
                            <p>营销载体类型：{MARKETING_CARRIER_TYPE_ENUM[marketingCarrierType as keyof typeof MARKETING_CARRIER_TYPE_ENUM]}</p>
                            {['MARKETING_CARRIER_TYPE_APP_ANDROID', 'MARKETING_CARRIER_TYPE_APP_IOS'].includes(marketingCarrierType) && <ShowApplication id={promoteApplicationId} />}
                            <p>版位选择：{automaticSiteEnabled ? '智能版位' : '选择特定版位'}</p>
                            {!automaticSiteEnabled && <Typography.Paragraph className={style.tpP} style={{ marginBottom: 0 }} ellipsis={{ tooltip: true, rows: 2 }}>广告版位：{siteSet.map((item: string | number) => SITE_SET_ENUM[item as keyof typeof SITE_SET_ENUM]).toString()}</Typography.Paragraph>}
                            {automaticSiteEnabled && <>
                                <p>探索策略：{explorationStrategy === 'STEADY_EXPLORATION' ? '稳步探索' : '自动探索'}</p>
                                {prioritySiteSet?.length > 0 && <Typography.Paragraph className={style.tpP} style={{ marginBottom: 0 }} ellipsis={{ tooltip: true, rows: 2 }}>优先探索版位：{prioritySiteSet.map((item: string | number) => SITE_SET_ENUM[item as keyof typeof SITE_SET_ENUM]).toString()}</Typography.Paragraph>}
                            </>}
                            <p>搜索场景扩量：{searchExpandTargetingSwitch === 'SEARCH_EXPAND_TARGETING_SWITCH_OPEN' ? '开启' : '关闭'}</p>
                            {rtaId && <p>RTA ID：{rtaId}</p>}
                            {rtaTargetId && <p>策略 ID：{rtaTargetId}</p>}
                            <p>计费方式：{BID_MODE_ENUM[bidMode as keyof typeof BID_MODE_ENUM]}</p>
                            {putInType === 'GAME' ? <>
                                <p>出价场景：{BID_SCENE_NORMAL_ENUM[bidScene as keyof typeof BID_SCENE_NORMAL_ENUM]}</p>
                            </> : <p>出价类型：{SMART_BID_TYPE_ENUM[smartBidType as keyof typeof SMART_BID_TYPE_ENUM]}</p>}
                            <p style={{ fontWeight: 'bold', color: '#000' }}>出价分配方式：{BID_ALL_OCATION_MODE.find(item => item.value === bidAllocationMode)?.label}</p>
                            {[2, 3].includes(bidAllocationMode)
                                ?
                                <p style={{ fontWeight: 'bold', color: '#000' }}>出价：{bidAmountMin}-{bidAmountMax} 元/{optimizationGoal ? OPTIMIZATIONGOAL_ENUM[optimizationGoal as keyof typeof OPTIMIZATIONGOAL_ENUM] : ['BID_MODE_OCPM', 'BID_MODE_OCPC'].includes(bidMode) ? '千次曝光' : '点击'}</p>
                                :
                                <p style={{ fontWeight: 'bold', color: '#000' }}>出价：{bidAmount} 元/{optimizationGoal ? OPTIMIZATIONGOAL_ENUM[optimizationGoal as keyof typeof OPTIMIZATIONGOAL_ENUM] : ['BID_MODE_OCPM', 'BID_MODE_OCPC'].includes(bidMode) ? '千次曝光' : '点击'}</p>
                            }

                            {isConversion && <p style={{ fontWeight: 'bold', color: '#000' }}>转化：新链路转化</p>}
                            {optimizationGoal && <p style={{ fontWeight: 'bold', color: '#000' }}>优化目标：{OPTIMIZATIONGOAL_ENUM[optimizationGoal as keyof typeof OPTIMIZATIONGOAL_ENUM]}</p>}
                            {deepConversionSpec && <>
                                <p style={{ fontWeight: 'bold', color: '#000' }}>深度转化优化：开启</p>
                                <p style={{ fontWeight: 'bold', color: '#000' }}>深度优化类型：{DEEP_CONVERSION_ENUM[deepConversionSpec?.deepConversionType as keyof typeof DEEP_CONVERSION_ENUM]}</p>
                                {deepConversionSpec.deepConversionType === 'DEEP_CONVERSION_BEHAVIOR' ? <>
                                    <p style={{ fontWeight: 'bold', color: '#000' }}>深度优化目标：{OPTIMIZATIONGOAL_ENUM[deepConversionSpec.deepConversionBehaviorSpec.goal as keyof typeof OPTIMIZATIONGOAL_ENUM]}</p>
                                    <p style={{ fontWeight: 'bold', color: '#000' }}>深度目标出价：{deepConversionSpec.deepConversionBehaviorSpec.bidAmount}元/{OPTIMIZATIONGOAL_ENUM[deepConversionSpec.deepConversionBehaviorSpec.goal as keyof typeof OPTIMIZATIONGOAL_ENUM] || '优化目标'}</p>
                                </> : <>
                                    <p style={{ fontWeight: 'bold', color: '#000' }}>深度优化目标：{GOAL_ROAS_ENUM[deepConversionSpec.deepConversionWorthSpec.goal as keyof typeof GOAL_ROAS_ENUM]}</p>
                                    <p style={{ fontWeight: 'bold', color: '#000' }}>ROI分配方式：{ROI_ALL_OCATION_MODE.find(item => item.value === deepConversionSpec?.deepConversionWorthSpec?.roiAllocationMode)?.label}</p>
                                    {[2, 3].includes(deepConversionSpec?.deepConversionWorthSpec?.roiAllocationMode)
                                        ?
                                        <p style={{ fontWeight: 'bold', color: '#000' }}>期望ROI：{deepConversionSpec.deepConversionWorthSpec.expectedRoiMin}-{deepConversionSpec.deepConversionWorthSpec.expectedRoiMax}</p>
                                        :
                                        <p style={{ fontWeight: 'bold', color: '#000' }}>期望ROI：{deepConversionSpec.deepConversionWorthSpec.expectedRoi}</p>
                                    }
                                </>}
                            </>}
                            <p>一方人群跑量加强：{ecomPkamSwitch === 'ECOM_PKAM_SWITCH_OPEN' ? '开启' : '关闭'}</p>
                            <p>一键起量：{autoAcquisitionEnabled ? '开启' : '关闭'}</p>
                            {autoAcquisitionEnabled && <p>起量预算：{autoAcquisitionBudget}元/天</p>}
                            <p>广告日预算：{dailyBudget ? dailyBudget + '元/天' : '不限'}</p>
                            <p style={{ fontWeight: 'bold', color: '#000' }}>投放日期：{beginDate} 至 {endDate || '长期投放'}</p>
                            <p>投放时段：{timeSeries.includes('0') ? <TimeSeriesLook timeSeries={timeSeries} /> : '全天'}</p>
                            <p>首日开始时间：{firstDayBeginTime ? firstDayBeginTime : '关闭'}</p>
                            <p>自动衍生创意：{autoDerivedCreativeEnabled ? '系统衍生' : '关闭衍生'}</p>
                            <p>广告名称：{adgroupName}</p>
                        </> : <>
                            {/* 智能投放 */}
                            <p style={{ fontWeight: 'bold', color: '#000' }}>投放场景：{SMART_DELIVERY_PLATFORM_ENUM[smartDeliveryPlatform as keyof typeof SMART_DELIVERY_PLATFORM_ENUM]}</p>
                            {putInType === 'NOVEL' ? <>
                                <p>营销目的：{MARKETING_GOAL_ENUM[marketingGoal as keyof typeof MARKETING_GOAL_ENUM]}</p>
                                <p style={{ fontWeight: 'bold', color: '#000' }}>推广产品类型：{MARKETING_TARGET_TYPE_ENUM[marketingAssetOuterSpec?.marketingTargetType as keyof typeof MARKETING_TARGET_TYPE_ENUM]}</p>
                            </> : <>
                                <p>营销目的：{MARKETING_SUB_GOAL_ENUM[marketingSubGoal as keyof typeof MARKETING_SUB_GOAL_ENUM]}</p>
                                <p style={{ fontWeight: 'bold', color: '#000' }}>推广产品类型：{MARKETING_TARGET_TYPE_GAME_ENUM[marketingAssetOuterSpec?.marketingTargetType as keyof typeof MARKETING_TARGET_TYPE_GAME_ENUM]}</p>
                            </>}
                            {marketingAssetOuterSpec?.marketingTargetType === 'MARKETING_TARGET_TYPE_MINI_PROGRAM_WECHAT' ?
                                <ShowMiniProgramWechatDetail id={sysWechatAppId} /> :
                                marketingAssetOuterSpec?.marketingTargetType === 'MARKETING_TARGET_TYPE_WECHAT_MINI_GAME' ?
                                    <ShowGameAppIdDetail appId={wxGameAppId} /> :
                                    null
                            }
                            <p>营销载体类型：{MARKETING_CARRIER_TYPE_ENUM[marketingCarrierType as keyof typeof MARKETING_CARRIER_TYPE_ENUM]}</p>
                            {['MARKETING_CARRIER_TYPE_APP_ANDROID', 'MARKETING_CARRIER_TYPE_APP_IOS'].includes(marketingCarrierType) && <ShowApplication id={promoteApplicationId} />}
                            <p>版位选择：{automaticSiteEnabled ? '智能版位' : '选择特定版位'}</p>
                            {automaticSiteEnabled && <>
                                <p>探索策略：{explorationStrategy === 'STEADY_EXPLORATION' ? '稳步探索' : '自动探索'}</p>
                            </>}
                            <p>搜索场景扩量：{searchExpandTargetingSwitch === 'SEARCH_EXPAND_TARGETING_SWITCH_OPEN' ? '开启' : '关闭'}</p>
                            <p>计费方式：{BID_MODE_ENUM[bidMode as keyof typeof BID_MODE_ENUM]}</p>
                            {smartDeliverySceneSpec?.smartDeliveryGoal && <p style={{ fontWeight: 'bold', color: '#000' }}>投放目标：{SMART_DELIVERY_GOAL_ENUM[smartDeliverySceneSpec?.smartDeliveryGoal as keyof typeof SMART_DELIVERY_GOAL_ENUM]?.title}</p>}
                            <p style={{ fontWeight: 'bold', color: '#000' }}>出价分配方式：{BID_ALL_OCATION_MODE.find(item => item.value === bidAllocationMode)?.label}</p>
                            {smartModel}
                            {isConversion && <p style={{ fontWeight: 'bold', color: '#000' }}>转化：新链路转化</p>}
                            <p>广告日预算：{dailyBudget ? dailyBudget + '元/天' : '不限'}</p>
                            <p style={{ fontWeight: 'bold', color: '#000' }}>投放日期：{beginDate} 至 {endDate || '长期投放'}</p>
                            <p>投放时段：{timeSeries.includes('0') ? <TimeSeriesLook timeSeries={timeSeries} /> : '全天'}</p>
                            <p>首日开始时间：{firstDayBeginTime ? firstDayBeginTime : '关闭'}</p>
                            <p>广告名称：{adgroupName}</p>
                        </>}
                    </> : <div className={style.ad_config}>
                        {accountCreateLogs?.length > 0 ?
                            <div className={style.ad_config_item} onClick={() => setNewVisible(true)}>新建广告</div>
                            :
                            <div className={style.ad_config_item} style={{ backgroundColor: '#FFF' }}>请完善媒体账户信息</div>
                        }
                    </div>}
                </div>
                <div className={style.detail_footer}>
                    {(adgroups && Object.keys(adgroups).length > 0) ? <>
                        <Button type="link" icon={<EditOutlined />} style={{ padding: 0, fontSize: 12 }} onClick={() => setNewVisible(true)}>编辑</Button>
                    </> : <></>}
                </div>
            </div>
        </div>

        {/* 新建广告 */}
        {newVisible && <NewCreateAd
            accountIdList={accountCreateLogs.map(item => item.accountId)}
            putInType={putInType}
            value={addelivery.adgroups}
            visible={newVisible}
            onClose={() => {
                setNewVisible(false)
            }}
            onChange={(adgroups) => {
                setIsDqSubmit?.(false)
                if (
                    adgroups.marketingGoal === marketingGoal &&  // 营销内容
                    adgroups.marketingCarrierType === marketingCarrierType && // 营销载体
                    adgroups.marketingAssetOuterSpec.marketingTargetType === marketingAssetOuterSpec.marketingTargetType && // 推广产品
                    adgroups.automaticSiteEnabled === automaticSiteEnabled &&  // 版位选择
                    arraysHaveSameValues(adgroups?.siteSet || [], siteSet || []) &&  // 版位
                    arraysHaveSameValues(adgroups?.sceneSpec?.wechatPosition || [], sceneSpec?.wechatPosition || []) // 微信公众号与小程序定投
                ) {
                    if (adgroups?.isConversion !== isConversion || ((isConversion || adgroups?.isConversion) && adgroups?.depthConversionEnabled !== depthConversionEnabled)) {
                        setAccountCreateLogs(accountCreateLogs.map(item => {
                            delete item?.newConversionList
                            delete item?.userActionSetsList
                            return item
                        }))
                    }
                    setNewVisible(false)
                    setAddelivery({ ...addelivery, adgroups })

                    clearData()
                } else {
                    setAccountCreateLogs(accountCreateLogs.map(item => ({ accountId: item.accountId })))
                    if (
                        addelivery?.adgroups && Object.keys(addelivery?.adgroups).length &&
                        ((addelivery?.dynamic && Object.keys(addelivery?.dynamic).length)
                            || addelivery?.targeting?.length
                            || (addelivery?.dynamicMaterialDTos && Object.keys(addelivery?.dynamicMaterialDTos).length)
                            || (addelivery?.dynamicCreativesTextDTOS && Object.keys(addelivery?.dynamicCreativesTextDTOS).length)
                        )
                    ) {
                        Modal.confirm({
                            title: <strong style={{ color: '#FAAD14' }}>注意</strong>,
                            content: <span>当前改变了“营销内容”、“营销载体”、“推广产品”、“版位选择”、“版位”、“微信公众号与小程序定投”中的某些内容，不清空后面内容可能会导致当前“定向”、“创意”、“素材”等一些内容不匹配，<span style={{ color: 'red' }}>是否清空内容</span></span>,
                            okText: '清空',
                            cancelText: '不清空',
                            keyboard: false,
                            onOk() { // 清空
                                setNewVisible(false)
                                setAddelivery({ adgroups, targeting: [], dynamic: {}, dynamicMaterialDTos: {}, dynamicCreativesTextDTOS: {}, mediaType: 0 })
                                clearData()
                            },
                            onCancel() { // 不清空
                                setNewVisible(false)
                                setAddelivery({ ...addelivery, adgroups })
                                clearData()
                            },
                            className: 'modalResetCss'
                        })
                    } else {
                        setNewVisible(false)
                        setAddelivery({ adgroups, targeting: [], dynamic: {}, dynamicMaterialDTos: {}, dynamicCreativesTextDTOS: {}, mediaType: 0 })
                        clearData()
                    }
                }
            }}
        />}
    </>
}


export default React.memo(Ad)