import { Button, Form, Modal, Space, message } from "antd"
import React, { useEffect, useState } from "react"
import '../../index.less'
import { defaultGameMarketingGoal, defaultMarketingGoal, defaultSiteSet } from "../../const"
import AdgroupsMarketingContent from "./adgroupsMarketingContent"
import AdgroupsSitSet from "./adgroupsSitSet"
import AdgroupsPrice from "./adgroupsPrice"
import AdgroupsAdSetting from "./adgroupsAdSetting"
import moment from "moment"
import { getTimeSeriesList } from "@/pages/launchSystemNew/adq/ad/const"
import AdgroupsTarget from "./adgroupsTarget"
import AdgroupsPutInType from "./adgroupsPutInType"

export const DispatchAd = React.createContext<PULLIN.AdReactContent | null>(null);

interface Props {
    accountIdList: number[]
    putInType?: 'NOVEL' | 'GAME'
    value?: any,
    visible?: boolean
    onClose?: () => void
    onChange?: (value: any) => void
}

/**
 * 广告
 * @param param0 
 * @returns 
 */
const NewCreateAd: React.FC<Props> = ({ accountIdList, value, visible, onChange, onClose, putInType }) => {

    /***********************************/
    const [form] = Form.useForm();
    const marketingCarrierType = Form.useWatch('marketingCarrierType', form);
    // 深度优化副作用参数
    const [OGPParams, setOGPparams] = useState<PULLIN.OGPParamsProps>({ bidMode: 'BID_MODE_OCPM', siteSet: defaultSiteSet, automaticSiteEnabled: false, marketingGoal: putInType === 'NOVEL' ? defaultMarketingGoal : defaultGameMarketingGoal, marketingSubGoal: putInType === 'GAME' ? 'MARKETING_SUB_GOAL_MINI_GAME_NEW_CUSTOMER_GROWTH' : undefined })
    const [smartDeliveryGoalRules, setSmartDeliveryGoalRules] = useState<PULLIN.SmartDeliveryGoalOption[]>([])
    /***********************************/

    const handleOk = (values: any) => {
        if (["OPTIMIZATIONGOAL_FOLLOW", "OPTIMIZATIONGOAL_PAGE_SCAN_CODE"].includes(values?.optimizationGoal) && !values?.depthConversionEnabled) {
            message.error('应公司要求，”关注和加企微“请开启深度转化优化')
            return
        }
        const {
            wechatPositionType,      // 微信公众号与小程序定投
            wechatChannelsSceneType, // 微信视频号定投
            wechatSceneType,         // 微信公众号与小程序场景
            marketingTargetType,     // 推广产品
            tencentNewsType,
            displaySceneType,
            dateType,
            beginDate,
            date,                    // 开始时间 结束时间
            timeSeriesType,          // 选择时段类型
            timeSeries,              // 时段
            isSetfirstDayBeginTime,  // 首日开始时间是否开启
            ecomPkamSwitch,
            smartTargetingMode,
            ...surplusValues
        } = values
        console.log(values)
        let adgroupsValues: any = { ...surplusValues }

        if (dateType === '1') {
            adgroupsValues.beginDate = moment(beginDate).format('YYYY-MM-DD')
            adgroupsValues.endDate = ""
        } else {
            adgroupsValues.beginDate = moment(date?.[0]).format('YYYY-MM-DD')
            adgroupsValues.endDate = moment(date?.[1]).format('YYYY-MM-DD')
        }

        if (marketingTargetType) {
            adgroupsValues.marketingAssetOuterSpec = {
                marketingTargetType
            }
        }

        if (ecomPkamSwitch) {
            adgroupsValues.ecomPkamSwitch = 'ECOM_PKAM_SWITCH_OPEN'
        }

        // 投放时段处理
        if (timeSeriesType === '0') {
            adgroupsValues.timeSeries = Array(336).fill(1).join('');
        } else {
            adgroupsValues.timeSeries = timeSeries.join('');
        }

        // 智能定向处理
        if (smartTargetingMode === 'SMART_TARGETING_MANUAL') {
            adgroupsValues.smartTargetingMode = smartTargetingMode
        }

        Object.keys(adgroupsValues).forEach(key => {
            if (adgroupsValues[key] === undefined || adgroupsValues === null) {
                delete adgroupsValues[key]
            }
        })

        if (values?.deliveryMethod === 'SMART') {
            // 搜索扩量开关
            adgroupsValues.searchExpansionWitch = 'SEARCH_EXPANSION_SWITCH_OPEN'
            adgroupsValues.bidAmount = 1.5
            // 二级营销目的
            adgroupsValues.marketingSubGoal = 'MARKETING_SUB_GOAL_UNKNOWN'
        }
        console.log('adgroupsValues', adgroupsValues)
        onChange?.(adgroupsValues)
    }

    // 数据回填
    useEffect(() => {
        if (value && Object.keys(value).length > 0 && visible) {
            const {
                firstDayBeginTime,
                timeSeries,
                beginDate,
                endDate,
                sceneSpec,
                marketingAssetOuterSpec,
                autoDerivedCreativeEnabled,
                ecomPkamSwitch,
                smartTargetingMode,
                ...surplusValues
            } = JSON.parse(JSON.stringify(value))
            let adgroupsValues: any = {
                ...surplusValues,
                sceneSpec,
                marketingTargetType: marketingAssetOuterSpec?.marketingTargetType,
                autoDerivedCreativeEnabled: autoDerivedCreativeEnabled ? true : false
            }

            if (ecomPkamSwitch === 'ECOM_PKAM_SWITCH_OPEN') {
                adgroupsValues.ecomPkamSwitch = true
            }

            // 首日开始时间
            if (firstDayBeginTime) {
                adgroupsValues.firstDayBeginTime = firstDayBeginTime
                adgroupsValues.isSetfirstDayBeginTime = true
            } else {
                adgroupsValues.isSetfirstDayBeginTime = false
            }

            // 时段
            if (timeSeries && timeSeries.includes('0')) {
                adgroupsValues.timeSeriesType = '2'
            } else {
                adgroupsValues.timeSeriesType = '0'
            }
            adgroupsValues.timeSeries = timeSeries?.split('') || getTimeSeriesList()

            // 投放时间
            if (endDate) {
                adgroupsValues.dateType = '0'
                adgroupsValues.date = [moment(beginDate), moment(endDate)]
            } else {
                adgroupsValues.dateType = '1'
                adgroupsValues.beginDate = moment(beginDate)
            }

            // 微信公众号与小程序定投
            if (sceneSpec?.wechatPosition?.length > 0) {
                adgroupsValues.wechatPositionType = '1'
            } else {
                adgroupsValues.wechatPositionType = '0'
            }
            // 微信视频号定投
            if (sceneSpec?.wechatChannelsScene?.length > 0) {
                adgroupsValues.wechatChannelsSceneType = '1'
            } else {
                adgroupsValues.wechatChannelsSceneType = '0'
            }
            // 微信公众号与小程序场景
            if (sceneSpec?.wechatScene && Object.keys(sceneSpec.wechatScene).length > 0) {
                adgroupsValues.wechatSceneType = '1'
            } else {
                adgroupsValues.wechatSceneType = '0'
            }
            // 腾讯新闻流量场景
            if (sceneSpec?.tencentNews && sceneSpec.tencentNews?.length > 0) {
                adgroupsValues.tencentNewsType = '1'
            } else {
                adgroupsValues.tencentNewsType = '0'
            }
            // 优量汇广告展示场景
            if (sceneSpec?.displayScene && sceneSpec.displayScene?.length > 0) {
                adgroupsValues.displaySceneType = '1'
            } else {
                adgroupsValues.displaySceneType = '0'
            }

            // 智能对象
            if (smartTargetingMode) {
                adgroupsValues.smartTargetingMode = smartTargetingMode
            } else {
                adgroupsValues.smartTargetingMode = 'SMART_TARGETING_OPEN'
            }

            setOGPparams({
                bidMode: adgroupsValues.bidMode,
                siteSet: adgroupsValues.siteSet,
                automaticSiteEnabled: adgroupsValues.automaticSiteEnabled,
                marketingGoal: adgroupsValues.marketingGoal,
                marketingSubGoal: adgroupsValues.marketingSubGoal,
                marketingCarrierType: adgroupsValues?.marketingCarrierType,
                marketingTargetType: adgroupsValues?.marketingTargetType
            })
            form.setFieldsValue({ ...adgroupsValues })
        }
    }, [value, visible])

    return <Modal
        title={<strong style={{ fontSize: 20 }}>广告的基本信息</strong>}
        open={visible}
        onCancel={onClose}
        footer={null}
        width={900}
        className={`modalResetCss`}
        bodyStyle={{ padding: '0 0 40px', position: 'relative', borderRadius: '0 0 8px 8px' }}
        maskClosable={false}
    >
        <Form
            form={form}
            name="newAd"
            labelAlign='left'
            layout="vertical"
            colon={false}
            style={{ backgroundColor: '#f1f4fc', maxHeight: 650, overflow: 'hidden', overflowY: 'auto', padding: '0 10px 10px', borderRadius: '0 0 8px 8px' }}
            scrollToFirstError={{
                behavior: 'smooth',
                block: 'center'
            }}
            onFinishFailed={({ errorFields }) => {
                message.error(errorFields?.[0]?.errors?.[0])
            }}
            onFinish={handleOk}
            initialValues={{
                deliveryMethod: 'NORMAL',
                marketingGoal: putInType === 'NOVEL' ? defaultMarketingGoal : putInType === 'GAME' ? defaultGameMarketingGoal : undefined,
                marketingSubGoal: putInType === 'GAME' ? 'MARKETING_SUB_GOAL_MINI_GAME_NEW_CUSTOMER_GROWTH' : undefined,
                automaticSiteEnabled: false,
                siteSet: defaultSiteSet,
                searchExpandTargetingSwitch: 'SEARCH_EXPAND_TARGETING_SWITCH_OPEN',
                bidMode: 'BID_MODE_OCPM',
                smartBidType: 'SMART_BID_TYPE_CUSTOM',
                bidScene: 'BID_SCENE_NORMAL_AVERAGE',
                optimizationGoal: putInType === 'NOVEL' ? null : 'OPTIMIZATIONGOAL_MOBILE_APP_AD_INCOME',
                deepConversionSpec: {
                    deepConversionType: 'DEEP_CONVERSION_WORTH'
                },
                bidAllocationMode: 1,
                roiAllocationMode: 1,
                // bidAmount: 1000,
                timeSeries: getTimeSeriesList(),
                autoAcquisitionEnabled: false,
                configuredStatus: 'AD_STATUS_SUSPEND',
                // adgroupName: '<营销目的>-<推广产品>-<日期>-<时分秒>',
                // marketingTargetType: 'MARKETING_TARGET_TYPE_FICTION'
                // 自定义字段
                dateType: '0',
                date: [moment().startOf('day').add(7, 'day'), moment().startOf('day').add(20, 'day')],
                wechatPositionType: '0',
                wechatSceneType: '0',
                displaySceneType: '0',
                tencentNewsType: '0',
                wechatChannelsSceneType: '0',
                timeSeriesType: '0',
                isSetfirstDayBeginTime: false,
                autoDerivedCreativeEnabled: false,
                isConversion: false,
                explorationStrategy: 'AUTOMATIC_EXPLORATION',
                smartTargetingMode: 'SMART_TARGETING_MANUAL'
            }}
        >
            <DispatchAd.Provider value={{ form, OGPParams, setOGPparams, putInType, smartDeliveryGoalRules, setSmartDeliveryGoalRules }}>
                <Space direction="vertical" style={{ width: '100%' }}>
                    {/* 投放方式 */}
                    <AdgroupsPutInType />
                    {/* 营销内容 */}
                    <AdgroupsMarketingContent value={value} accountIdList={accountIdList} />
                    {/* 广告版位 */}
                    <AdgroupsSitSet />
                    {/* 定向 */}
                    <AdgroupsTarget marketingCarrierType={marketingCarrierType} />
                    {/* 出价与预算 */}
                    <AdgroupsPrice />
                    {/* 广告设置 */}
                    <AdgroupsAdSetting value={value} />
                </Space>
            </DispatchAd.Provider>

            <Form.Item className="submit_pull">
                <Space>
                    <Button onClick={onClose}>取消</Button>
                    <Button type="primary" htmlType="submit" className="modalResetCss">
                        确定
                    </Button>
                </Space>
            </Form.Item>
        </Form>
    </Modal>
}

export default React.memo(NewCreateAd)