import React, { useCallback, useEffect } from 'react'
import { Modal, Form, Input, Divider, Select, Radio, DatePicker, Switch, Checkbox, message, Tooltip } from 'antd'
import { SiteSetEnum, BidModeEnum, OptimizationGoalEnum, BidStrategyEnum, PromotedObjectType } from '@/services/launchAdq/enum'
import { ModalConfig } from '.'
import moment from 'moment';
import { useAjax } from '@/Hook/useAjax';
import { getSceneTagsList } from '@/services/launchAdq/global';
import { ExclamationCircleOutlined } from '@ant-design/icons';
const { RangePicker }: { RangePicker: any } = DatePicker;
let DatePickers: any = DatePicker
interface Props {
    visible: boolean,
    PupFn: (arg: ModalConfig) => void,
    callback: (params: any) => void,
    confirmLoading?: boolean,
    type?: 'add' | 'look' | 'edit',//新增，查看，编辑
    dataInfo?: any
}
/**广告模板*/
function AdModal(props: Props) {
    let { visible, confirmLoading, PupFn, callback, type, dataInfo } = props
    let arg = type === 'look' ? { footer: null } : {}
    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)

    // 确定事件
    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')
            }
            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;
                }
            })
            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.payScene
            delete newValues.wechatPositionType
            delete newValues.wechatPosition
            delete newValues.wechatScene
            delete newValues['dateType']
            delete newValues['date']
            newValues['timeSeries'] = Array(336).fill(1).join('')
            console.log(newValues)
            callback(newValues)
        })
    }, [form])
    // 场景定向
    useEffect(() => {
        sceneTagsList.run({ typeList: ['WECHAT_POSITION', 'OFFICIAL_ACCOUNT_MEDIA_CATEGORY', 'MINI_PROGRAM_AND_MINI_GAME', 'PAY_SCENE'] })
    }, [])
    // 数据回填
    useEffect(() => {
        if (dataInfo) {
            form.setFieldsValue({
                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,//订单详情页消费场景
            })
        }
    }, [dataInfo])
    return <Modal
        open={visible}
        title={type === 'add' ? '新建广告' : type === 'look' ? '广告详情' : '编辑广告'}
        onCancel={() => { PupFn({ visible: false, dataInfo: null, type: 'add' }) }}
        onOk={type === 'look' ? () => message.warning('详情无法改动内容') : handleOk}
        width={900}
        confirmLoading={confirmLoading}
        {...arg}
    >
        <Form
            form={form}
            labelCol={{ span: 5 }}
            initialValues={
                {
                    promotedObjectType: 'PROMOTED_OBJECT_TYPE_WECHAT_OFFICIAL_ACCOUNT',
                    siteSet: ['SITE_SET_MOMENTS', 'SITE_SET_WECHAT'],
                    bidMode: 'BID_MODE_OCPM',
                    dateType: '2',
                    bidStrategy: 'BID_STRATEGY_AVERAGE_COST',
                    timeSeries: '1',
                    smartBidType: 'SMART_BID_TYPE_CUSTOM',
                    autoAcquisitionEnabled: false,
                    wechatSceneType: '0',
                    wechatPositionType: '0',
                }
            }
        >
            {/* ============================================================基本信息============================================================= */}
            <Divider orientation='center'>基本信息</Divider>
            <Form.Item label={<strong>广告名称</strong>} name='adgroupName' rules={[{ required: true, message: '请输入广告名称!' }]}>
                <Input placeholder='广告名称' style={{ width: 300 }} />
            </Form.Item>
            <Form.Item label={<strong>推广目标类型</strong>} name='promotedObjectType' 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(PromotedObjectType).map(key => {
                            return <Select.Option value={key} key={key}>{PromotedObjectType[key]}</Select.Option>
                        })
                    }
                </Select>
            </Form.Item>
            <Form.Item label={<strong>广告版位</strong>} name='siteSet' rules={[{ required: true, message: '请输入选择广告版位！' }]}>
                <Select mode='multiple' style={{ width: 300 }} allowClear>
                    {
                        Object.keys(SiteSetEnum).map(key => {
                            return <Select.Option value={key} key={key}>{SiteSetEnum[key]}</Select.Option>
                        })
                    }
                </Select>
            </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 >
                    <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 }}></RangePicker>
                </Form.Item> : <Form.Item name='date' style={{ marginLeft: 177 }} rules={[{ required: true, message: '请选择日期' }]}>
                    <DatePickers />
                </Form.Item>
            }
            <Form.Item label={<strong>投放时段</strong>}>
                <Radio.Group name='timeSeries' defaultValue='1'>
                    <Radio.Button value={'1'}>全天投放</Radio.Button>
                </Radio.Group>
            </Form.Item>
            <Form.Item label={<strong>出价方式<Tooltip title='出价方式不同将影响自定义人群，行为兴趣意向等某些功能无法使用'><ExclamationCircleOutlined style={{ color: '#e91e63', marginLeft: 5 }} /></Tooltip></strong>} name='bidMode'>
                <Radio.Group >
                    {
                        Object.keys(BidModeEnum).map(key => {
                            return <Radio.Button value={key} key={key} disabled={!key.includes('CPM')}>{BidModeEnum[key]}</Radio.Button>
                        })
                    }

                </Radio.Group>
            </Form.Item>
            {/* 出价方式为OCPM才展示 */}
            {
                bidMode === 'BID_MODE_OCPM' && <>
                    <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>
                                })
                            }
                        </Select>
                    </Form.Item>
                    <Form.Item label={<strong>出价类型</strong>} name='smartBidType'>
                        <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'>
                        <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='输入价格 元/千次曝光' style={{ width: 300 }} />
                    </Form.Item>
                    {/* 当版位选择大于1时才出现 */}
                    {/* {siteSet?.length > 1 &&<Form.Item label={<strong>分版位出价</strong>} name='bidAdjustment'>
                        <Switch checkedChildren="开启" unCheckedChildren="关闭" />
                    </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>}
                </>
            }
            <Form.Item label={<strong>广告日预算</strong>} name='dailyBudget'>
                <Input placeholder='不填默认为不限' style={{ width: 300 }} />
            </Form.Item>
        </Form>
    </Modal >
}
export default AdModal