import React, { useCallback, useEffect, useState } from 'react'
import { Modal, Form, Input, Divider, Select, Radio, DatePicker, Switch, Checkbox, message, Tooltip, Row, Col, Space, TimePicker, Button } from 'antd'
import { BidModeEnum, OptimizationGoalEnum, BidStrategyEnum, AdStatus, GoalRoasEnum } from '@/services/launchAdq/enum'
import { ModalConfig } from '../index'
import moment from 'moment';
import { useAjax } from '@/Hook/useAjax';
import { getSceneTagsList } from '@/services/launchAdq/global';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { CreateAdProps } from '@/services/launchAdq/createAd';
import { createSysAdgroups } from '@/services/launchAdq/localAd';
import AdPositionList from './adPositionList';
import BidAdjustment from './bidAdjustment';
import { RangePickerProps } from 'antd/lib/date-picker';
import { txtLength } from '@/utils/utils';
import InputName from '@/components/InputName';
const { RangePicker }: { RangePicker: any } = DatePicker;
let DatePickers: any = DatePicker
interface Props {
    queryForm: Partial<CreateAdProps>,
    visible: boolean,
    PupFn: (arg: ModalConfig) => void,
    callback: (params: any) => void,
    confirmLoading?: boolean,
    type?: 'add' | 'look' | 'edit',//新增，查看，编辑
    dataInfo?: any,
    ajax: any
}

export const siteSetData = [
    { siteSet: 'SITE_SET_MOMENTS', type: 1 },
    { siteSet: 'SITE_SET_MOBILE_UNION', type: 3 },
    { siteSet: 'SITE_SET_TENCENT_NEWS', type: 2 },
    { siteSet: 'SITE_SET_TENCENT_VIDEO', type: 2 },
    { siteSet: 'SITE_SET_KANDIAN', type: 2 },
    { siteSet: 'SITE_SET_QQ_MUSIC_GAME', type: 2 },
    { siteSet: 'SITE_SET_WECHAT', type: 4 },
    { siteSet: 'SITE_SET_WECHAT_PLUGIN', type: 4 },
]

export interface SiteSetPackageDataProps {
    siteSet: string[],
    bidCoefficient?: number,
    deepBidCoefficient?: number
}

/**收集线索广告弹窗*/
function LeadAdModal(props: Props) {
    let { visible, PupFn, callback, type, dataInfo, queryForm, ajax } = props
    const createSysAdgroup = useAjax((params) => createSysAdgroups(params))
    let arg = type === 'look' ? { footer: null } : {}
    let [state, setState] = useState<any>({
        isShowTime: []
    })
    let [template_checked, settemplate_checked] = useState<boolean>(dataInfo?.isTemplate || false)
    const sceneTagsList = useAjax((params) => getSceneTagsList(params))
    const [form] = Form.useForm();
    let dateType = Form.useWatch('dateType', form)
    let bidMode = Form.useWatch('bidMode', form)
    let smartBidType = Form.useWatch('smartBidType', form)
    let autoAcquisitionEnabled = Form.useWatch('autoAcquisitionEnabled', form)
    let siteSet = Form.useWatch('siteSet', form)
    let wechatPositionType = Form.useWatch('wechatPositionType', form)
    let wechatSceneType = Form.useWatch('wechatSceneType', form)
    let automaticSiteEnabled = Form.useWatch('automaticSiteEnabled', form)
    let optimizationGoal = Form.useWatch('optimizationGoal', form)

    let depthConversionEnabled = Form.useWatch('depthConversionEnabled', form)
    let deepConversionType = Form.useWatch('deepConversionType', form)
    let goal = Form.useWatch('goal', form)
    let bidAdjustmentEnabled = Form.useWatch('bidAdjustmentEnabled', form)
    let siteSetPackage = Form.useWatch('siteSetPackage', form)
    let deepBidAmount = Form.useWatch('deepBidAmount', form)
    let bidAmountAdjustmentEnabled = Form.useWatch('bidAmountAdjustmentEnabled', form)
    let bidAmount = Form.useWatch('bidAmount', form)

    const [behaviorList, setBehaviorList] = useState<string[]>([])
    const [worthList, setWorthList] = useState<string[]>([])



    // 确定事件
    const handleOk = useCallback(() => {
        form.validateFields().then(values => {
            let newValues = JSON.parse(JSON.stringify(values))
            newValues.sceneSpec = {}
            if (newValues.dateType === '2') {
                newValues['beginDate'] = moment(newValues.date).format('YYYY-MM-DD')
            } else {
                newValues['beginDate'] = moment(newValues.date[0]).format('YYYY-MM-DD')
                newValues['endDate'] = moment(newValues.date[1]).format('YYYY-MM-DD')
            }
            if (newValues.firstDayBeginTime) {
                console.log(newValues.firstDayBeginTime)
                newValues['firstDayBeginTime'] = moment(newValues.firstDayBeginTime).format('HH:mm:ss')
            }
            Object.keys(newValues).forEach(key => {
                switch (key) {
                    case 'wechatPositionType':
                        if (newValues[key] === '1') {
                            newValues.sceneSpec = { ...newValues.sceneSpec, wechatPosition: newValues.wechatPosition }
                        }
                        break;
                    case 'wechatSceneType':
                        if (newValues[key] === '1') {
                            newValues.sceneSpec = {
                                ...newValues.sceneSpec, wechatScene: {
                                    officialAccountMediaCategory: newValues.officialAccountMediaCategory,
                                    miniProgramAndMiniGame: newValues.miniProgramAndMiniGame,
                                    payScene: newValues.payScene
                                }
                            }
                        }
                        break;
                        case 'siteSetPackage':   // 处理分版位出价
                        if (newValues[key]?.length > 0) {
                            let newSiteSetPackage: SiteSetPackageDataProps[] = JSON.parse(JSON.stringify(newValues[key]))
                            if (!newValues?.bidAmountAdjustmentEnabled) {
                                newSiteSetPackage = newSiteSetPackage.map(item => {
                                    let { bidCoefficient, ...newItem } = item
                                    return { ...newItem }
                                })
                            }
                            if (!newValues?.bidAdjustmentEnabled) {
                                newSiteSetPackage = newSiteSetPackage.map(item => {
                                    let { deepBidCoefficient, ...newItem } = item
                                    return { ...newItem }
                                })
                            }
                            newValues.bidAdjustment = {
                                siteSetPackage: newSiteSetPackage
                            }
                            delete newValues.siteSetPackage
                        }
                        break
                    case 'deepConversionType': // 处理深度优化
                        let deepConversionSpec: any = {
                            deepConversionType: newValues[key]
                        }
                        if (newValues[key] === 'DEEP_CONVERSION_WORTH') { // 优化 ROI
                            deepConversionSpec.deepConversionWorthSpec = {
                                goal: newValues.goal,
                                expectedRoi: newValues.deepBidAmount
                            }
                        } else if (newValues[key] === 'DEEP_CONVERSION_BEHAVIOR') { // 优化转化行为
                            deepConversionSpec.deepConversionBehaviorSpec = {
                                goal: newValues.goal,
                                bidAmount: newValues.deepBidAmount * 100
                            }
                        }
                        newValues.deepConversionSpec = deepConversionSpec
                        delete newValues.deepBidAmount
                        delete newValues.goal
                        delete newValues.optimizationMode
                        delete newValues.deepConversionType
                        delete newValues.depthConversionEnabled
                        break
                }
            })
            if (newValues.sceneSpec.wechatPosition?.length === 0) {
                delete newValues.sceneSpec.wechatPosition
            }
            if (newValues.sceneSpec.wechatScene) {
                newValues.sceneSpec.wechatScene.officialAccountMediaCategory?.length === 0 && (delete newValues.sceneSpec.wechatScene.officialAccountMediaCategory)
                newValues.sceneSpec.wechatScene.miniProgramAndMiniGame?.length === 0 && (delete newValues.sceneSpec.wechatScene.miniProgramAndMiniGame)
                newValues.sceneSpec.wechatScene.payScene?.length === 0 && (delete newValues.sceneSpec.wechatScene.payScene)
            }
            if (!newValues.sceneSpec.wechatPosition && !newValues.sceneSpec.wechatScene) {
                delete newValues.sceneSpec
            }
            delete newValues.officialAccountMediaCategory
            delete newValues.miniProgramAndMiniGame
            delete newValues?.bidAmountAdjustmentEnabled
            delete newValues?.bidAdjustmentEnabled
            delete newValues.payScene
            delete newValues.wechatPositionType
            delete newValues.wechatPosition
            delete newValues.wechatScene
            delete newValues['dateType']
            delete newValues['date']
            newValues['timeSeries'] = Array(336).fill(1).join('')
            newValues['promotedObjectType'] = queryForm.promotedObjectType
            console.log(newValues)
            newValues['isTemplate'] = template_checked
            // 开启存为模板开关执行
            // if (template_checked && type==='add') {
            //     createSysAdgroup.run(newValues).then(res => {
            //         if (res) {
            //             callback(newValues)
            //         }
            //     })
            // } else {
            callback(newValues)
            // }
        })
    }, [form, template_checked, queryForm, type])
    // 场景定向
    useEffect(() => {
        sceneTagsList.run({ typeList: ['WECHAT_POSITION', 'OFFICIAL_ACCOUNT_MEDIA_CATEGORY', 'MINI_PROGRAM_AND_MINI_GAME', 'PAY_SCENE'] })
    }, [])
    // 数据回填
    useEffect(() => {
        if (dataInfo) {
            let formData: any = {
                adgroupName: dataInfo?.adgroupName,//广告名称
                promotedObjectType: dataInfo?.promotedObjectType,//推广目标
                siteSet: dataInfo?.siteSet,//广告版位
                autoAcquisitionEnabled: dataInfo?.autoAcquisitionEnabled,//一键起量
                bidAmount: dataInfo?.bidAmount,//出价
                smartBidType: dataInfo?.smartBidType,//出价类型
                bidStrategy: dataInfo?.bidStrategy,//出价策略
                bidMode: dataInfo?.bidMode,//出价方式
                optimizationGoal: dataInfo?.optimizationGoal,//优化目标
                dateType: dataInfo?.endDate ? '1' : '2',//投放日期
                dailyBudget: dataInfo?.dailyBudget,//广告日预算
                date: dataInfo?.endDate ? [moment(dataInfo?.beginDate), moment(dataInfo?.endDate)] : moment(dataInfo?.beginDate),//日期
                autoAcquisitionBudget: dataInfo?.autoAcquisitionBudget,//起量预算
                wechatPositionType: dataInfo?.sceneSpec?.wechatPosition ? '1' : '0',//微信公众号与小程序定投
                wechatPosition: dataInfo?.sceneSpec?.wechatPosition,//微信公众号与小程序定投
                wechatSceneType: dataInfo?.sceneSpec?.wechatScene?.officialAccountMediaCategory || dataInfo?.sceneSpec?.wechatScene?.miniProgramAndMiniGame || dataInfo?.sceneSpec?.wechatScene?.payScene ? '1' : '0',//微信公众号与小程序场景
                officialAccountMediaCategory: dataInfo?.sceneSpec?.wechatScene?.officialAccountMediaCategory,//公众号媒体类型
                miniProgramAndMiniGame: dataInfo?.sceneSpec?.wechatScene?.miniProgramAndMiniGame,//小程序小游戏流量类型
                payScene: dataInfo?.sceneSpec?.wechatScene?.payScene,//订单详情页消费场景
                firstDayBeginTime: dataInfo?.firstDayBeginTime ? moment(`${dataInfo?.beginDate} ${dataInfo?.firstDayBeginTime}`) : undefined,//首日开始时间
                configuredStatus: dataInfo?.configuredStatus || 'AD_STATUS_SUSPEND',//广告启停
            }
            Object.keys(dataInfo).forEach(key => {
                switch (key) {
                    case 'bidAdjustment': // 处理分版位出价
                        if (dataInfo[key]?.siteSetPackage && dataInfo[key]?.siteSetPackage?.length > 0) {
                            let siteSetPackage: SiteSetPackageDataProps[] = dataInfo[key].siteSetPackage
                            if (siteSetPackage.some(item => item.bidCoefficient)) { // 判断出价是否开启了分版位
                                formData.bidAmountAdjustmentEnabled = true
                            } else {
                                siteSetPackage = siteSetPackage.map(item => ({ ...item, bidCoefficient: 1 }))
                            }
                            if (siteSetPackage.some(item => item.deepBidCoefficient)) { // 判断深度出价是否开启了分版位
                                formData.bidAdjustmentEnabled = true
                            } else {
                                siteSetPackage = siteSetPackage.map(item => ({ ...item, deepBidCoefficient: 1 }))
                            }
                            formData.siteSetPackage = siteSetPackage
                        }
                        break
                    case 'deepConversionSpec': // 处理深度优化
                        if (dataInfo[key]?.deepConversionType === 'DEEP_CONVERSION_WORTH') {
                            formData = {
                                ...formData,
                                optimizationMode: 'DEEP_CONVERSION_TARGET',
                                depthConversionEnabled: true,
                                deepConversionType: dataInfo[key]?.deepConversionType,
                                goal: dataInfo[key]?.deepConversionWorthSpec?.goal,
                                deepBidAmount: dataInfo[key]?.deepConversionWorthSpec?.expectedRoi,
                            }
                        } else if (dataInfo[key]?.deepConversionType === 'DEEP_CONVERSION_BEHAVIOR') {
                            formData = {
                                ...formData,
                                optimizationMode: 'DEEP_CONVERSION_TARGET',
                                depthConversionEnabled: true,
                                deepConversionType: dataInfo[key]?.deepConversionType,
                                goal: dataInfo[key]?.deepConversionBehaviorSpec?.goal,
                                deepBidAmount: dataInfo[key]?.deepConversionBehaviorSpec?.bidAmount / 100,
                            }
                        }
                        break
                }
            })
            form.setFieldsValue(formData)
            if (dataInfo?.firstDayBeginTime) {//存在首日开始时间，选中开关
                setState({ ...state, isShowTime: ['1'] })
            }
        } else {
            form.setFieldsValue({ 
                adgroupName: '广告_销售线索',
                date: moment().startOf('day').add(2, 'M'),
                optimizationGoal: "OPTIMIZATIONGOAL_ECOMMERCE_ORDER",
                bidStrategy: "BID_STRATEGY_TARGET_COST",
                bidAmount: '1000'
            })
        }
    }, [dataInfo])
    // 出价方式改变清空某些数据
    const bidModeChange = useCallback((props) => {
        form.setFieldsValue({
            ...props,
            optimizationGoal: 'OPTIMIZATIONGOAL_ECOMMERCE_ORDER',
            smartBidType: 'SMART_BID_TYPE_CUSTOM',
            // bidAmount:null,
            bidStrategy: 'BID_STRATEGY_TARGET_COST',
            autoAcquisitionEnabled: false,
            autoAcquisitionBudget: null,
            dailyBudget: null,
        })
    }, [])
    // 出价和版位改变时查询
    useEffect(() => {
        if (bidMode && siteSet && siteSet?.length > 0) {
            let obj: any = { siteSet, promotedObjectType: queryForm.promotedObjectType }
            if (bidMode === 'BID_MODE_OCPC' || bidMode === 'BID_MODE_OCPM') {
                obj = { ...obj, bidMode }
            }
            ajax.run(obj).then((res: any) => {
                console.log(res)
            })
        }
    }, [bidMode, siteSet])

    // 处理深度转化优化
    useEffect(() => {
        if (optimizationGoal && ajax?.data) {
            let { deepBehaviorOptimizationGoalPermissionList, deepWorthOptimizationGoalPermissionList } = ajax?.data
            // deepBehaviorOptimizationGoalPermissionList 优化转化行为
            // deepWorthOptimizationGoalPermissionList 优化ROI
            let behavior = deepBehaviorOptimizationGoalPermissionList?.find((item: { optimizationGoal: string }) => item.optimizationGoal === optimizationGoal)
            let worth = deepWorthOptimizationGoalPermissionList?.find((item: { optimizationGoal: string }) => item.optimizationGoal === optimizationGoal)
            setBehaviorList(behavior?.deepBehaviorOptimizationGoalList || [])
            setWorthList(worth?.deepWorthOptimizationGoalList || [])
        }
    }, [optimizationGoal, ajax?.data])

    /**处理分版位数据 */
    const setSiteSetHandle = (siteSet: string[]) => {
        let data: SiteSetPackageDataProps[] = []
        if (siteSet && siteSet?.length > 0) {
            let data1: string[] = []
            let data2: string[] = []
            let data3: string[] = []
            let data4: string[] = []
            siteSet.forEach((item: string) => {
                let siteData = siteSetData?.find(item1 => item1.siteSet === item)
                if (siteData) {
                    switch (siteData.type) {
                        case 1:
                            data1.push(item)
                            break
                        case 2:
                            data2.push(item)
                            break
                        case 3:
                            data3.push(item)
                            break
                        case 4:
                            data4.push(item)
                            break
                    }
                }
            });
            let newSiteSetPackageData: SiteSetPackageDataProps[] = []
            if (data1?.length > 0) {
                newSiteSetPackageData.push({ siteSet: data1, bidCoefficient: 1, deepBidCoefficient: 1 })
            }
            if (data2?.length > 0) {
                newSiteSetPackageData.push({ siteSet: data2, bidCoefficient: 1, deepBidCoefficient: 1 })
            }
            if (data3?.length > 0) {
                newSiteSetPackageData.push({ siteSet: data3, bidCoefficient: 1, deepBidCoefficient: 1 })
            }
            if (data4?.length > 0) {
                newSiteSetPackageData.push({ siteSet: data4, bidCoefficient: 1, deepBidCoefficient: 1 })
            }
            data = newSiteSetPackageData
        } else {
            data = []
        }
        form.setFieldsValue({
            siteSetPackage: data
        })
    }

    /** 禁止选择以前时间 */
    const disabledDate: RangePickerProps['disabledDate'] = current => {
        // Can not select days before today and today
        return current && current < moment().startOf('day');
    };

    return <Modal
        visible={visible}
        title={type === 'add' ? '新建广告' : type === 'look' ? '广告详情' : '编辑广告'}
        onCancel={() => { PupFn({ visible: false, dataInfo: null, type: 'add' }) }}
        onOk={type === 'look' ? () => message.warning('详情无法改动内容') : handleOk}
        width={900}
        confirmLoading={createSysAdgroup?.loading}
        footer={<Space>
            <Button onClick={() => { PupFn({ visible: false, dataInfo: null, type: 'add' }) }}>取消</Button>
            <Button type='primary' onClick={handleOk}>确定</Button>
            {<Checkbox checked={template_checked} onChange={(e) => {
                let checked = e.target.checked
                settemplate_checked(checked)
            }}>存为模板</Checkbox>}
        </Space>}
        {...arg}
    >
        <Form
            form={form}
            labelCol={{ span: 5 }}
            className='ad_form_style'
            initialValues={
                {
                    promotedObjectType: queryForm.promotedObjectType,
                    siteSet: ['SITE_SET_MOMENTS', 'SITE_SET_WECHAT', 'SITE_SET_WECHAT_PLUGIN'],
                    bidMode: 'BID_MODE_OCPM',
                    automaticSiteEnabled: false,
                    dateType: '2',
                    bidStrategy: 'BID_STRATEGY_AVERAGE_COST',
                    timeSeries: '1',
                    smartBidType: 'SMART_BID_TYPE_CUSTOM',
                    autoAcquisitionEnabled: false,
                    wechatSceneType: '0',
                    wechatPositionType: '0',
                    // optimizationGoal: 'OPTIMIZATIONGOAL_ECOMMERCE_ORDER',
                    configuredStatus: 'AD_STATUS_SUSPEND',
                    siteSetPackage: [{ siteSet: ["SITE_SET_MOMENTS"], bidCoefficient: 1, deepBidCoefficient: 1 }, { siteSet: ["SITE_SET_WECHAT"], bidCoefficient: 1, deepBidCoefficient: 1 }]
                }
            }
        >
            {/* ============================================================基本信息============================================================= */}
            <Divider orientation='center'>基本信息</Divider>
            <Form.Item
                label={<strong>广告名称</strong>}
                name='adgroupName'
                tooltip="下标、日期时分秒、广告账户创建时默认自带"
                rules={[
                    { required: true, message: '请输入广告名称!' },
                    {
                        required: true, message: '广告名称不能包含特殊字符：< > & ‘ ” / 以及TAB、换行、回车键，请修改', validator(rule, value, callback) {
                            let reg = /[&‘’“”/\n\t\f]/ig
                            if (value && reg.test(value)) {
                                return Promise.reject()
                            }
                            return Promise.resolve()
                        },
                    },
                    // {
                    //     required: true, message: '您可能使用了不支持的通配符，请您确认后再保存', validator(rule, value, callback) {
                    //         let reg = /(<账号备注>)|(<商品ID>)|(<账号ID>)|(<日期>)|(<时分秒>)|(<定向名>)|(<素材名>)|(<落地页名>|(<优化目标>)/ig
                    //         let reg1 = /[<>]/ig
                    //         if (value && (reg1.test(value))) {
                    //             if (reg.test(value)) {
                    //                 return Promise.resolve()
                    //             }
                    //             return Promise.reject()
                    //         }
                    //         return Promise.resolve()
                    //     },
                    // },
                    {
                        required: true, message: '请确保广告名称长度不超过60个字（1个汉字等于2个字符)', validator(rule, value, callback) {
                            if (value && txtLength(value) > 60) {
                                return Promise.reject()
                            }
                            return Promise.resolve()
                        },
                    }
                ]}
            >
                <InputName placeholder='广告名称' style={{ width: 400 }} length={60} />
            </Form.Item>
            <Form.Item label={<strong>广告版位</strong>}>
                <Form.Item name='automaticSiteEnabled'>
                    <Radio.Group buttonStyle="solid">
                        <Radio.Button value={true} disabled={queryForm.promotedObjectType === 'PROMOTED_OBJECT_TYPE_WECHAT_OFFICIAL_ACCOUNT'}>自动版位</Radio.Button>
                        <Radio.Button value={false}>选择特定版位</Radio.Button>
                    </Radio.Group>
                </Form.Item>
                {!automaticSiteEnabled && <Form.Item name='siteSet' noStyle rules={[{ required: true, message: '请输入选择广告版位！' }]}>
                    <Checkbox.Group style={{ width: '100%' }} onChange={(e) => { bidModeChange({ bidMode: 'BID_MODE_OCPM' }); setSiteSetHandle(e as string[]) }}>
                        <Row>
                            <Col span={4}>
                                <Checkbox value="SITE_SET_MOMENTS">微信朋友圈</Checkbox>
                            </Col>
                            <Col span={4}>
                                <Checkbox value="SITE_SET_MOBILE_UNION">优量汇</Checkbox>
                            </Col>
                            <Col span={4}>
                                <Checkbox value="SITE_SET_TENCENT_NEWS">腾讯新闻</Checkbox>
                            </Col>
                            <Col span={4}>
                                <Checkbox value="SITE_SET_TENCENT_VIDEO">腾讯视频</Checkbox>
                            </Col>
                            <Col span={4}>
                                <Checkbox value="SITE_SET_KANDIAN">QQ 浏览器</Checkbox>
                            </Col>
                            <Col span={6}>
                                <Checkbox value="SITE_SET_QQ_MUSIC_GAME">QQ、腾讯音乐及游戏</Checkbox>
                            </Col>
                            <Col span={6}>
                                <Checkbox value="SITE_SET_WECHAT">微信公众号与小程序</Checkbox>
                            </Col>
                            <Col span={5}>
                                <Checkbox value="SITE_SET_WECHAT_PLUGIN">微信新闻插件</Checkbox>
                            </Col>
                        </Row>
                    </Checkbox.Group>
                </Form.Item>}
            </Form.Item>
            {
                siteSet?.some((s: string) => s === 'SITE_SET_WECHAT') && <>
                    <Form.Item label={<strong>微信公众号与小程序定投</strong>} name='wechatPositionType' style={wechatPositionType === '1' ? { marginBottom: 5 } : {}}>
                        <Radio.Group >
                            <Radio.Button value="0">不限</Radio.Button>
                            <Radio.Button value="1">自定义</Radio.Button>
                        </Radio.Group>
                    </Form.Item>
                    {wechatPositionType === '1' && <Form.Item style={{ marginLeft: 177 }} name='wechatPosition'>
                        <Checkbox.Group options={sceneTagsList?.data?.WECHAT_POSITION?.map((item: { description: any; id: any; }) => ({ label: item.description, value: item.id }))} />
                    </Form.Item>}
                    <Form.Item label={<strong>微信公众号与小程序场景</strong>} name='wechatSceneType' style={wechatSceneType === '1' ? { marginBottom: 5 } : {}} >
                        <Radio.Group >
                            <Radio.Button value="0">不限</Radio.Button>
                            <Radio.Button value="1">自定义</Radio.Button>
                        </Radio.Group>
                    </Form.Item>
                    {wechatSceneType === '1' && <>
                        <p style={{ marginBottom: 5, marginLeft: 177 }}><strong style={{ marginRight: 20 }}>公众号媒体类型</strong></p>
                        <Form.Item style={{ marginLeft: 177 }} name='officialAccountMediaCategory'>
                            <Checkbox.Group options={sceneTagsList?.data?.OFFICIAL_ACCOUNT_MEDIA_CATEGORY?.filter((i: { description: string; }) => i.description !== '不限')?.map((item: { description: any; id: any; }) => ({ label: item.description, value: item.id }))} />
                        </Form.Item>
                        <p style={{ marginBottom: 5, marginLeft: 177 }}><strong style={{ marginRight: 20 }}>小程序小游戏流量类型</strong></p>
                        <Form.Item style={{ marginLeft: 177 }} name='miniProgramAndMiniGame'>
                            <Checkbox.Group options={sceneTagsList?.data?.MINI_PROGRAM_AND_MINI_GAME?.filter((i: { description: string; }) => i.description !== '不限')?.map((item: { description: any; id: any; }) => ({ label: item.description, value: item.id }))} />
                        </Form.Item>
                        <p style={{ marginBottom: 5, marginLeft: 177 }}><strong style={{ marginRight: 20 }}>订单详情页消费场景</strong></p>
                        <Form.Item style={{ marginLeft: 177 }} name='payScene'>
                            <Checkbox.Group options={sceneTagsList?.data?.PAY_SCENE?.filter((i: { description: string; }) => i.description !== '不限')?.map((item: { description: any; id: any; }) => ({ label: item.description, value: item.id }))} />
                        </Form.Item>
                    </>}
                </>
            }
            {/* ============================================================排期与出价============================================================= */}
            <Divider orientation='center'>排期与出价</Divider>
            <Form.Item label={<strong>投放日期</strong>} name='dateType'>
                <Radio.Group onChange={(e) => {
                    if (e.target.value === "1") {
                        form.setFieldsValue({ date: [moment().startOf('day').add(2, 'M'), moment().startOf('day').add(5, 'M')] })
                    }
                    if (e.target.value === "2") {
                        form.setFieldsValue({ date: moment().startOf('day').add(2, 'M') })
                    }
                }}>
                    <Radio.Button value="1">选择开始与结束日期</Radio.Button>
                    <Radio.Button value="2">长期投放</Radio.Button>
                </Radio.Group>
            </Form.Item>
            {/* 投放日期的不同展示不同的日期选择 */}
            {
                dateType === '1' ? <Form.Item name='date' rules={[{ required: true, message: '请选择日期' }]}>
                    <RangePicker style={{ marginLeft: 177 }} disabledDate={disabledDate}></RangePicker>
                </Form.Item> : <Form.Item name='date' style={{ marginLeft: 177 }} rules={[{ required: true, message: '请选择日期' }]}>
                    <DatePickers disabledDate={disabledDate}/>
                </Form.Item>
            }
            <Form.Item label={<strong>投放时段</strong>}>
                <Space>
                    <Radio.Group name='timeSeries' defaultValue='1'>
                        <Radio.Button value={'1'}>全天投放</Radio.Button>
                    </Radio.Group>
                    <Checkbox.Group options={[{ label: '指定首日开始投放时间', value: '1' }]} onChange={(checkedValue) => {
                        setState({ ...state, isShowTime: checkedValue })
                    }
                    } value={state.isShowTime} />
                </Space>
                {state?.isShowTime?.length > 0 && <Form.Item name='firstDayBeginTime' noStyle rules={[{ required: true, message: '请选择时间' }]}>
                    <TimePicker />
                </Form.Item>}
            </Form.Item>
            <Form.Item label={<strong>出价方式<Tooltip title='出价方式不同将影响自定义人群，行为兴趣意向等某些功能无法使用'><ExclamationCircleOutlined style={{ color: '#e91e63', marginLeft: 5 }} /></Tooltip></strong>} name='bidMode' rules={[{ required: true, message: '请选择出价方式' }]}>
                <Radio.Group onChange={(e) => {
                    console.log(e.target.value);
                    
                    if (e.target.value === "BID_MODE_CPM" || e.target.value === "BID_MODE_CPC") {
                        form.setFieldsValue({
                            optimizationGoal: null,
                            smartBidType: null,
                            // bidAmount:null,
                            bidStrategy: null,
                            autoAcquisitionEnabled: false,
                            autoAcquisitionBudget: null,
                            dailyBudget: null,
                        })
                    } else {
                        form.setFieldsValue({
                            optimizationGoal: "OPTIMIZATIONGOAL_ECOMMERCE_ORDER",
                            smartBidType: "SMART_BID_TYPE_CUSTOM",
                            bidAmount: '1000',
                            bidStrategy: "BID_STRATEGY_TARGET_COST",
                            autoAcquisitionEnabled: false,
                            autoAcquisitionBudget: null,
                            dailyBudget: null,
                        })
                    }
                }}>
                    {
                        Object.keys(BidModeEnum).filter(key => { if (siteSet?.some((name: string) => name === "SITE_SET_MOMENTS")) { return key === 'BID_MODE_OCPM' || key === 'BID_MODE_CPM' } else { return true } })?.map(key => {
                            return <Radio.Button value={key} key={key} >{BidModeEnum[key]}</Radio.Button>
                        })
                    }

                </Radio.Group>
            </Form.Item>
            {/* 出价方式为OCPM才展示 */}
            {
                (bidMode === 'BID_MODE_OCPM' || bidMode === 'BID_MODE_OCPC') && <>
                    <Form.Item label={<strong>优化目标</strong>} name='optimizationGoal' rules={[{ required: true, message: '请选择优化目标' }]}>
                        <Select style={{ width: 300 }} showSearch filterOption={(input, option) =>
                            (option!.children as unknown as string).toLowerCase().includes(input.toLowerCase())
                        } allowClear>
                            {
                                // Object.keys(OptimizationGoalEnum).map(key => {
                                //     return <Select.Option value={key} key={key}>{OptimizationGoalEnum[key]}</Select.Option>
                                // })
                                ajax?.data?.optimizationGoalPermissionList.map((key: string) => {
                                    return <Select.Option value={key} key={key}>{OptimizationGoalEnum[key]}</Select.Option>
                                })
                            }
                        </Select>
                    </Form.Item>
                    <Form.Item label={<strong>出价类型</strong>} name='smartBidType' rules={[{ required: true, message: '请选择出价类型' }]}>
                        <Radio.Group >
                            <Radio.Button value="SMART_BID_TYPE_CUSTOM">手动出价</Radio.Button>
                            <Radio.Button value="SMART_BID_TYPE_SYSTEMATIC">自动出价</Radio.Button>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item label={<strong>出价策略</strong>} name='bidStrategy' rules={[{ required: true, message: '请选择出价策略' }]}>
                        <Radio.Group >
                            {
                                Object.keys(BidStrategyEnum).map(key => {
                                    return <Radio.Button value={key} key={key} disabled={smartBidType === 'SMART_BID_TYPE_SYSTEMATIC' && key === 'BID_STRATEGY_PRIORITY_CAP_COST'}> {BidStrategyEnum[key]}</Radio.Button>
                                })
                            }
                        </Radio.Group>
                    </Form.Item>
                </>
            }
            {/* 出价类型为手动出价才展示 */}
            {smartBidType !== 'SMART_BID_TYPE_SYSTEMATIC' && <>
                <Form.Item label={<strong>出价</strong>} name='bidAmount' rules={[{ required: true, message: '请输入价格' }]}>
                    <Input placeholder={`输入价格 元/${bidMode === 'BID_MODE_CPM' ? '千次曝光' : bidMode === 'BID_MODE_CPC' ? '点击' : OptimizationGoalEnum[optimizationGoal]}`} style={{ width: 300 }} />
                </Form.Item>
                {(bidMode === 'BID_MODE_OCPM' || bidMode === 'BID_MODE_OCPC') && <>
                    {/* 当版位选择大于1时才出现 */}
                    {siteSet?.length > 1 && <Form.Item label={<strong>分版位出价</strong>} name='bidAmountAdjustmentEnabled' valuePropName="checked">
                        <Switch checkedChildren="开启" unCheckedChildren="关闭" />
                    </Form.Item>}
                    {bidAmountAdjustmentEnabled && <Form.Item
                        label={<strong>分版位出价</strong>}
                        name='siteSetPackage'
                        rules={[{ required: bidAmountAdjustmentEnabled ? true : false, message: '请设置系数' }]}
                    >
                        <BidAdjustment bidAmount={bidAmount} deepConversionType='BID_MODE' goal={goal}>
                            <AdPositionList value={siteSetPackage} onChange={(data) => {
                                form.setFieldsValue({
                                    siteSetPackage: data
                                })
                            }} />
                        </BidAdjustment>
                    </Form.Item>}
                    <Form.Item label={<strong>一键起量</strong>} name='autoAcquisitionEnabled' valuePropName="checked">
                        <Switch checkedChildren="开启" unCheckedChildren="关闭" />
                    </Form.Item>
                    {/* 一键起量开启时才出现 */}
                    {autoAcquisitionEnabled && <Form.Item label={<strong>起量预算</strong>} name='autoAcquisitionBudget' rules={[{ required: true, message: '请输入起量预算' }]}>
                        <Input placeholder='起量预算' style={{ width: 300 }} />
                    </Form.Item>}

                    {/* 深度优化 */}
                    {(behaviorList?.length > 0 || worthList?.length > 0) && <Form.Item label={<strong>深度转化优化</strong>} name='depthConversionEnabled' valuePropName="checked">
                        <Switch checkedChildren="开启" unCheckedChildren="关闭" onChange={(e) => {
                            if (e) {
                                form.setFieldsValue({
                                    optimizationMode: 'DEEP_CONVERSION_TARGET',
                                    deepConversionType: behaviorList?.length > 0 ? 'DEEP_CONVERSION_BEHAVIOR' : worthList?.length > 0 ? 'DEEP_CONVERSION_WORTH' : ''
                                })
                            }
                        }} />
                    </Form.Item>}
                    {depthConversionEnabled && <div style={{ backgroundColor: 'rgb(247, 248, 250)', padding: '18px 0 3px', marginBottom: 10, borderRadius: 8 }}>
                        <Form.Item label={<strong>深度优化方式</strong>} name='optimizationMode' rules={[{ required: true, message: '请选择深度优化方式' }]}>
                            <Radio.Group>
                                <Radio.Button value="DEEP_CONVERSION_TARGET">深度目标优化</Radio.Button>
                            </Radio.Group>
                        </Form.Item>
                        <Form.Item label={<strong>深度优化类型</strong>} name='deepConversionType' rules={[{ required: true, message: '请选择深度优化类型' }]}>
                            <Radio.Group onChange={() => {
                                form.setFieldsValue({
                                    goal: undefined,
                                    deepBidAmount: undefined
                                })
                            }}>
                                {behaviorList?.length > 0 && <Radio.Button value="DEEP_CONVERSION_BEHAVIOR">优化转化行为</Radio.Button>}
                                {worthList?.length > 0 && <Radio.Button value="DEEP_CONVERSION_WORTH">优化 ROI</Radio.Button>}
                            </Radio.Group>
                        </Form.Item>
                        <Form.Item label={<strong>深度优化目标</strong>} name='goal' rules={[{ required: true, message: '请选择深度优化目标' }]}>
                            <Select style={{ width: 380 }} placeholder='请选择'>
                                {deepConversionType === 'DEEP_CONVERSION_BEHAVIOR' ? Object.keys(OptimizationGoalEnum).filter(key => behaviorList?.includes(key)).map(key => <Select.Option value={key} key={key}>{OptimizationGoalEnum[key]}</Select.Option>) : deepConversionType === 'DEEP_CONVERSION_WORTH' ?
                                    Object.keys(GoalRoasEnum).filter(key => worthList?.includes(key)).map(key => <Select.Option value={key} key={key}>{GoalRoasEnum[key]}</Select.Option>) : null}
                            </Select>
                        </Form.Item>
                        {deepConversionType === 'DEEP_CONVERSION_BEHAVIOR' ? <>
                            <Form.Item label={<strong>深度目标出价</strong>} name='deepBidAmount' rules={[{ required: true, message: '请输入深度目标出价' }]}>
                                <Input style={{ width: 380 }} suffix={`元/${OptimizationGoalEnum[goal] || '优化目标'}`} placeholder={`请输入深度目标出价，范围0.1~10000`} />
                            </Form.Item>
                        </> :
                            deepConversionType === 'DEEP_CONVERSION_WORTH' ? <>
                                <Form.Item label={<strong>期望ROI</strong>} name='deepBidAmount' rules={[{ required: true, message: '请输入期望ROI' }]}>
                                    <Input style={{ width: 380 }} placeholder={`期望ROI目标范围0.001~1000，输入0.05，表示ROI目标为5%`} />
                                </Form.Item>
                            </> : null}
                        {siteSet?.length > 1 && <Form.Item label={<strong>开启分版位深度目标出价</strong>} name='bidAdjustmentEnabled' valuePropName="checked">
                            <Switch checkedChildren="开启" unCheckedChildren="关闭" />
                        </Form.Item>}
                        {bidAdjustmentEnabled && <Form.Item
                            label={<strong>分版位深度目标出价</strong>}
                            name='siteSetPackage'
                            rules={[{ required: bidAdjustmentEnabled ? true : false, message: '请设置系数' }]}
                        >
                            <BidAdjustment bidAmount={deepBidAmount} deepConversionType={deepConversionType} goal={goal}>
                                {!(bidAmountAdjustmentEnabled) ? <AdPositionList value={siteSetPackage} onChange={(data) => {
                                    form.setFieldsValue({
                                        siteSetPackage: data
                                    })
                                }} /> : <></>}
                            </BidAdjustment>
                        </Form.Item>}
                    </div>}
                </>}
            </>}
            <Form.Item label={<strong>广告日预算</strong>} name='dailyBudget'>
                <Input placeholder='不填默认为不限' style={{ width: 300 }} />
            </Form.Item>
            <Form.Item label={<strong>广告状态</strong>} name="configuredStatus" rules={[{ required: true, message: '请选择广告状态' }]}>
                <Select placeholder="选择广告状态" style={{ width: 300 }}>
                    {Object.keys(AdStatus).map(key => {
                        return <Select.Option value={key} key={key}>{AdStatus[key]}</Select.Option>
                    })}
                </Select>
            </Form.Item>
        </Form>
    </Modal >
}
export default LeadAdModal