import { Button, Form, Modal, Space, message } from "antd"
import React, { useEffect, useState } from "react"
import '../../index.less'
import { 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"

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

interface Props {
    value?: any,
    visible?: boolean
    onClose?: () => void
    onChange?: (value: any) => void
}

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

    /***********************************/
    const [form] = Form.useForm();
    // 深度优化副作用参数
    const [OGPParams, setOGPparams] = useState<PULLIN.OGPParamsProps>({ bidMode: 'BID_MODE_OCPM', siteSet: defaultSiteSet, automaticSiteEnabled: false, marketingGoal: defaultMarketingGoal })
    /***********************************/

    const handleOk = (values: any) => {
        const {
            wechatPositionType,      // 微信公众号与小程序定投
            wechatChannelsSceneType, // 微信视频号定投
            wechatSceneType,         // 微信公众号与小程序场景
            marketingTargetType,     // 推广产品
            tencentNewsType,
            displaySceneType,
            date,                    // 开始时间 结束时间
            timeSeriesType,          // 选择时段类型
            timeSeries,              // 时段
            isSetfirstDayBeginTime,  // 首日开始时间是否开启
            ...surplusValues
        } = values

        let adgroupsValues: any = {
            ...surplusValues,
            beginDate: moment(date?.[0]).format('YYYY-MM-DD'),
            endDate: moment(date?.[1]).format('YYYY-MM-DD'),
        }

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

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

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

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

            // 首日开始时间
            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()

            // 投放时间
            adgroupsValues.date = [moment(beginDate), moment(endDate)]

            // 微信公众号与小程序定投
            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'
            }
            setOGPparams({
                bidMode: adgroupsValues.bidMode,
                siteSet: adgroupsValues.siteSet,
                automaticSiteEnabled: adgroupsValues.automaticSiteEnabled,
                marketingGoal: adgroupsValues.marketingGoal,
                marketingCarrierType: adgroupsValues?.marketingCarrierType,
                marketingTargetType: adgroupsValues?.marketingTargetType
            })
            form.setFieldsValue({ ...adgroupsValues })
        }
    }, [value])

    return <Modal
        title={<strong style={{ fontSize: 20 }}>广告的基本信息</strong>}
        visible={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={{
                marketingGoal: defaultMarketingGoal,
                automaticSiteEnabled: false,
                siteSet: defaultSiteSet,
                searchExpandTargetingSwitch: 'SEARCH_EXPAND_TARGETING_SWITCH_OPEN',
                bidMode: 'BID_MODE_OCPM',
                smartBidType: 'SMART_BID_TYPE_CUSTOM',
                optimizationGoal: 'OPTIMIZATIONGOAL_ECOMMERCE_ORDER',
                depthConversionEnabled: true,
                deepConversionSpec: {
                    deepConversionType: 'DEEP_CONVERSION_WORTH'
                },
                // bidAmount: 1000,
                timeSeries: getTimeSeriesList(),
                autoAcquisitionEnabled: false,
                configuredStatus: 'AD_STATUS_SUSPEND',
                // adgroupName: '<营销目的>-<推广产品>-<日期>-<时分秒>',
                // marketingTargetType: 'MARKETING_TARGET_TYPE_FICTION'
                // 自定义字段
                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
            }}
        >
            <DispatchAd.Provider value={{ form, OGPParams, setOGPparams }}>
                <Space direction="vertical" style={{ width: '100%' }}>
                    {/* 营销内容 */}
                    <AdgroupsMarketingContent value={value} />
                    {/* 广告版位 */}
                    <AdgroupsSitSet />
                    {/* 出价与预算 */}
                    <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)