import React, { useCallback, useEffect } from 'react'
import { Modal, Form, Input, Divider, Select, Radio, DatePicker, Switch, Checkbox } from 'antd'
import { SiteSetEnum, BidModeEnum, OptimizationGoalEnum, BidStrategyEnum, PromotedObjectType, EducationEnum } from '@/services/launchAdq/enum'
import { ModalConfig } from '.'
import moment from 'moment';
import { useAjax } from '@/Hook/useAjax';
import { getSceneTagsList } from '@/services/launchAdq/global';
const { RangePicker }: { RangePicker: any } = DatePicker;
let DatePickers: any = DatePicker
interface Props {
    title?: string,
    visible: boolean,
    PupFn: (arg: ModalConfig) => void,
    callback: (params: any) => void,
    confirmLoading: boolean
}
/**广告模板*/
function AdModal(props: Props) {
    let { visible, title, confirmLoading, PupFn, callback } = props
    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')
            }
            if (newValues.wechatPositionType === '1') {
                newValues.sceneSpec = { ...newValues.sceneSpec, wechatPosition: newValues.wechatPosition }
            }
            if (newValues.wechatSceneType === '1') {
                newValues.sceneSpec = { ...newValues.sceneSpec, wechatScene: {
                    officialAccountMediaCategory:newValues.officialAccountMediaCategory,
                    miniProgramAndMiniGame:newValues.miniProgramAndMiniGame,
                    payScene:newValues.payScene
                } }
            }
            if (newValues.sceneSpec.wechatPosition?.length === 0) {
                delete newValues.sceneSpec.wechatPosition
            }
            // if(newValues.sceneSpec.wechatScene)
            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('')
            callback(newValues)
        })
        // PupFn({ visible: false })
    }, [form])
    // 场景定向
    useEffect(() => {
        sceneTagsList.run({ typeList: ['WECHAT_POSITION', 'OFFICIAL_ACCOUNT_MEDIA_CATEGORY', 'MINI_PROGRAM_AND_MINI_GAME', 'PAY_SCENE'] })
    }, [])
    console.log()
    return <Modal
        visible={visible}
        title={title + '广告'}
        onCancel={() => { PupFn({ visible: false }) }}
        onOk={handleOk}
        width={900}
        confirmLoading={confirmLoading}
    >
        <Form
            form={form}
            labelCol={{ span: 5 }}
            initialValues={
                {
                    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>出价方式</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