import React, { useContext, useEffect, useState } from "react"
import { DispatchAd } from "./newCreateAd";
import { Card, Checkbox, Form, Radio, Space, Tooltip, message } from "antd";
import New1Radio from "@/pages/launchSystemV3/components/New1Radio";
import { DISPLAY_SCENE_ENUM, TENCENT_NEWS_ENUM, defaultSiteSet } from "../../const";
import NewTree from "@/pages/launchSystemV3/components/NewTree";
import { QuestionCircleFilled } from "@ant-design/icons";
import style from '../index.less'
import { getSceneTagsList } from "@/services/launchAdq/global";
import { useAjax } from "@/Hook/useAjax";
import { ReactComponent as MiaosiSvg } from '@/assets/x-miaosi-mini-brand.svg'

/**
 * 广告版位
 * @returns 
 */
const AdgroupsSitSet: React.FC = () => {

    /****************************************/
    const { form, setOGPparams, OGPParams } = useContext(DispatchAd)!;
    const automaticSiteEnabled = Form.useWatch('automaticSiteEnabled', form);
    const explorationStrategy = Form.useWatch('explorationStrategy', form);
    const siteSet = Form.useWatch('siteSet', form);
    const prioritySiteSet = Form.useWatch('prioritySiteSet', form);
    const wechatPositionType = Form.useWatch('wechatPositionType', form);
    const wechatSceneType = Form.useWatch('wechatSceneType', form);
    const displaySceneType = Form.useWatch('displaySceneType', form);
    const tencentNewsType = Form.useWatch('tencentNewsType', form);
    const wechatChannelsSceneType = Form.useWatch('wechatChannelsSceneType', form);
    const officialAccountMediaCategory = Form.useWatch(['wechatScene', 'officialAccountMediaCategory'], form);
    const miniProgramAndMiniGame = Form.useWatch(['wechatScene', 'miniProgramAndMiniGame'], form);
    const payScene = Form.useWatch(['wechatScene', 'payScene'], form);
    const deliveryMethod = Form.useWatch('deliveryMethod', form);

    const [OFFICIAL_ACCOUNT_MEDIA_CATEGORY, SET_OFFICIAL_ACCOUNT_MEDIA_CATEGORY] = useState<{ description: string, id: number }[]>([])
    const [MINI_PROGRAM_AND_MINI_GAME, SET_MINI_PROGRAM_AND_MINI_GAME] = useState<{ description: string, id: number }[]>([])
    const [PAY_SCENE, SET_PAY_SCENE] = useState<{ description: string, id: number }[]>([])
    const [noLimitOAMC, setNoLimitOAMC] = useState<number>()
    const [noLimitMPAMG, setNoLimitMPAMG] = useState<number>()
    const [noLimitPS, setNoLimitPS] = useState<number>()

    const sceneTagsList = useAjax((params) => getSceneTagsList(params))
    /****************************************/

    // 场景定向
    useEffect(() => {
        if (deliveryMethod === 'NORMAL') {
            sceneTagsList.run({ typeList: ['WECHAT_POSITION', 'OFFICIAL_ACCOUNT_MEDIA_CATEGORY', 'MINI_PROGRAM_AND_MINI_GAME', 'PAY_SCENE', 'MOBILE_UNION_CATEGORY', 'WECHAT_CHANNELS_SCENE'] }).then(res => {
                let NEW_OFFICIAL_ACCOUNT_MEDIA_CATEGORY = res?.OFFICIAL_ACCOUNT_MEDIA_CATEGORY
                let NEW_MINI_PROGRAM_AND_MINI_GAME = res?.MINI_PROGRAM_AND_MINI_GAME
                let NEW_PAY_SCENE = res?.PAY_SCENE
                SET_OFFICIAL_ACCOUNT_MEDIA_CATEGORY(NEW_OFFICIAL_ACCOUNT_MEDIA_CATEGORY || [])
                SET_MINI_PROGRAM_AND_MINI_GAME(NEW_MINI_PROGRAM_AND_MINI_GAME || [])
                SET_PAY_SCENE(NEW_PAY_SCENE || [])
                setNoLimitOAMC(NEW_OFFICIAL_ACCOUNT_MEDIA_CATEGORY?.filter((i: { description: string; }) => i.description === '不限')?.[0]?.id)
                setNoLimitMPAMG(NEW_MINI_PROGRAM_AND_MINI_GAME?.filter((i: { description: string; }) => i.description === '不限')?.[0]?.id)
                setNoLimitPS(NEW_PAY_SCENE?.filter((i: { description: string; }) => i.description === '不限')?.[0].id)
            })
        }
    }, [deliveryMethod])

    return <Card
        title={deliveryMethod === 'NORMAL' ?
            <strong style={{ fontSize: 18 }}>广告版位</strong> :
            <strong style={{ fontSize: 18 }}>智能版位 <span style={{ color: 'rgba(51,55,61,0.58)', fontSize: 12 }}><span role="img" aria-label="fund-view" className="anticon anticon-fund-view"><MiaosiSvg /></span>系统将智能进行版位择优投放</span></strong>
        }
        className="cardResetCss"
    >
        <Form.Item name="automaticSiteEnabled" style={{ marginBottom: automaticSiteEnabled ? 24 : 10 }} label={<strong>版位选择</strong>} rules={[{ required: true, message: '版位选择!' }]}>
            <New1Radio
                data={[{ label: '智能版位', value: true }, { label: '选择特定版位', value: false, disabled: deliveryMethod === 'SMART' }]}
                onChange={(e) => {
                    form.setFieldsValue({ siteSet: defaultSiteSet, explorationStrategy: 'AUTOMATIC_EXPLORATION' })
                    setOGPparams({ ...OGPParams, automaticSiteEnabled: e, siteSet: defaultSiteSet })
                }}
            />
        </Form.Item>
        {!automaticSiteEnabled ? <Form.Item
            name="siteSet"
            rules={[{ required: true, message: '请选择特定版位!' }]}
            getValueFromEvent={(e: string[]) => {
                if (e?.length > 0) {
                    return e
                } else {
                    message.warning('版位不可为空')
                    return siteSet
                }
            }}
        >
            <NewTree onChange={(e) => {
                setOGPparams({ ...OGPParams, siteSet: e as string[] })
                form.setFieldsValue({ bidMode: 'BID_MODE_OCPM' })
            }} />
        </Form.Item> : <>
            <Form.Item name="explorationStrategy" label={<strong>探索策略</strong>} rules={[{ required: true, message: '探索策略!' }]}>
                <Radio.Group>
                    <Radio value={'AUTOMATIC_EXPLORATION'}>自动探索</Radio>
                    <Radio value={'STEADY_EXPLORATION'} disabled={deliveryMethod === 'SMART'}>稳步探索</Radio>
                </Radio.Group>
            </Form.Item>
            {explorationStrategy === 'STEADY_EXPLORATION' && <Form.Item
                name="prioritySiteSet"
                rules={[{ required: true, message: '请选择优先探索版位!' }]}
                getValueFromEvent={(e: string[]) => {
                    if (e?.length > 0) {
                        return e
                    } else {
                        message.warning('版位不可为空')
                        return prioritySiteSet
                    }
                }}
            >
                <NewTree />
            </Form.Item>}
        </>}

        <Form.Item
            label={<Space>
                <strong>搜索场景扩量</strong>
                <Tooltip title="广告将有机会投放至QQ浏览器、搜一搜等搜索流量场景，获取更多曝光">
                    <QuestionCircleFilled />
                </Tooltip>
            </Space>}
        >
            <Card bordered className="cardResetCss newCss" bodyStyle={{ padding: 0 }}>
                <div className={style.newSpace}>
                    <div className={style.newSpace_top}>
                        <div className={style.newSpace_title}>定向拓展</div>
                        <Form.Item name="searchExpandTargetingSwitch" style={{ marginBottom: 0 }}>
                            <Radio.Group buttonStyle="solid">
                                <Radio.Button value="SEARCH_EXPAND_TARGETING_SWITCH_CLOSE" disabled={deliveryMethod === 'SMART'}>关闭</Radio.Button>
                                <Radio.Button value="SEARCH_EXPAND_TARGETING_SWITCH_OPEN">开启</Radio.Button>
                            </Radio.Group>
                        </Form.Item>
                    </div>
                </div>
            </Card>
        </Form.Item>

        {deliveryMethod === 'NORMAL' && <Form.Item style={{ marginBottom: 0 }}>
            <Card bordered className="cardResetCss newCss" bodyStyle={{ padding: 0 }}>
                {(siteSet?.includes('SITE_SET_WECHAT') || automaticSiteEnabled) && <div className={style.newSpace}>
                    <div className={style.newSpace_top}>
                        <div className={style.newSpace_title}>微信公众号与小程序定投</div>
                        <Form.Item name='wechatPositionType' style={{ marginBottom: 0 }}>
                            <Radio.Group >
                                <Radio value="0">不限</Radio>
                                <Radio value="1">自定义</Radio>
                            </Radio.Group>
                        </Form.Item>
                    </div>
                    {wechatPositionType === '1' && <div className={style.newSpace_bottom}>
                        <Form.Item name={['sceneSpec', 'wechatPosition']}>
                            <Checkbox.Group options={sceneTagsList?.data?.WECHAT_POSITION?.map((item: { description: any; id: any; }) => ({ label: item.description, value: item.id }))} />
                        </Form.Item>
                    </div>}
                </div>}

                {(siteSet?.includes('SITE_SET_CHANNELS') || automaticSiteEnabled) && <div className={style.newSpace}>
                    <div className={style.newSpace_top}>
                        <div className={style.newSpace_title}>微信视频号定投</div>
                        <Form.Item name='wechatChannelsSceneType' style={{ marginBottom: 0 }} rules={[{ required: true, message: '请选择!' }]}>
                            <Radio.Group >
                                <Radio value="0">不限</Radio>
                                <Radio value="1">自定义</Radio>
                            </Radio.Group>
                        </Form.Item>
                    </div>
                    {wechatChannelsSceneType === '1' && <div className={style.newSpace_bottom}>
                        <Form.Item name={['sceneSpec', 'wechatChannelsScene']} rules={[{ required: true, message: '请选择!' }]}>
                            <Checkbox.Group options={sceneTagsList?.data?.WECHAT_CHANNELS_SCENE?.map((item: { description: any; id: any; }) => ({ label: item.description, value: item.id }))} />
                        </Form.Item>
                    </div>}
                </div>}


                {(siteSet?.includes('SITE_SET_WECHAT') || automaticSiteEnabled) && <div className={style.newSpace}>
                    <div className={style.newSpace_top}>
                        <div className={style.newSpace_title}>微信公众号与小程序场景</div>
                        <Form.Item name='wechatSceneType' style={{ marginBottom: 0 }}>
                            <Radio.Group
                                onChange={(e) => {
                                    if (e.target.value === '1') {
                                        form.setFieldsValue({
                                            wechatScene: {
                                                officialAccountMediaCategory: [noLimitOAMC], miniProgramAndMiniGame: [noLimitMPAMG], payScene: [noLimitPS]
                                            }
                                        })
                                    }
                                }}
                            >
                                <Radio value="0">不限</Radio>
                                <Radio value="1">自定义</Radio>
                            </Radio.Group>
                        </Form.Item>
                    </div>
                    {wechatSceneType === '1' && <div className={style.newSpace_bottom}>
                        <p style={{ marginBottom: 5 }}><strong style={{ marginRight: 20 }}>公众号媒体类型</strong></p>
                        <Form.Item
                            name={['sceneSpec', 'wechatScene', 'officialAccountMediaCategory']}
                            rules={[{ required: true, message: '请选择!' }]}
                            getValueFromEvent={(e: number[]) => {
                                if (e.length > 1 && !officialAccountMediaCategory?.includes(noLimitOAMC) && noLimitOAMC && e.includes(noLimitOAMC)) {
                                    return [noLimitOAMC]
                                }
                                if (e?.length > 0) {
                                    if (e?.length > 1 && noLimitOAMC && e.includes(noLimitOAMC)) {
                                        return e.filter(item => item !== noLimitOAMC)
                                    } else {
                                        return e
                                    }
                                } else {
                                    return [noLimitOAMC]
                                }
                            }}
                        >
                            <Checkbox.Group options={OFFICIAL_ACCOUNT_MEDIA_CATEGORY?.map((item: { description: any; id: any; }) => ({ label: item.description, value: item.id }))} />
                        </Form.Item>
                        <p style={{ marginBottom: 5 }}><strong style={{ marginRight: 20 }}>小程序小游戏流量类型</strong></p>
                        <Form.Item
                            name={['sceneSpec', 'wechatScene', 'miniProgramAndMiniGame']}
                            rules={[{ required: true, message: '请选择!' }]}
                            getValueFromEvent={(e: number[]) => {
                                if (e.length > 1 && !miniProgramAndMiniGame?.includes(noLimitMPAMG) && noLimitMPAMG && e.includes(noLimitMPAMG)) {
                                    return [noLimitMPAMG]
                                }
                                if (e?.length > 0) {
                                    if (e?.length > 1 && noLimitMPAMG && e.includes(noLimitMPAMG)) {
                                        return e.filter(item => item !== noLimitMPAMG)
                                    } else {
                                        return e
                                    }
                                } else {
                                    return [noLimitMPAMG]
                                }
                            }}
                        >
                            <Checkbox.Group options={MINI_PROGRAM_AND_MINI_GAME?.map((item: { description: any; id: any; }) => ({ label: item.description, value: item.id }))} />
                        </Form.Item>
                        <p style={{ marginBottom: 5 }}><strong style={{ marginRight: 20 }}>订单详情页消费场景</strong></p>
                        <Form.Item
                            name={['sceneSpec', 'wechatScene', 'payScene']}
                            rules={[{ required: true, message: '请选择!' }]}
                            getValueFromEvent={(e: number[]) => {
                                if (e.length > 1 && !payScene?.includes(noLimitPS) && noLimitPS && e.includes(noLimitPS)) {
                                    return [noLimitPS]
                                }
                                if (e?.length > 0) {
                                    if (e?.length > 1 && noLimitPS && e.includes(noLimitPS)) {
                                        return e.filter(item => item !== noLimitPS)
                                    } else {
                                        return e
                                    }
                                } else {
                                    return [noLimitPS]
                                }
                            }}
                        >
                            <Checkbox.Group options={PAY_SCENE?.map((item: { description: any; id: any; }) => ({ label: item.description, value: item.id }))} />
                        </Form.Item>
                    </div>}
                </div>}

                {(siteSet?.includes('SITE_SET_TENCENT_NEWS') || automaticSiteEnabled) && <div className={style.newSpace}>
                    <div className={style.newSpace_top}>
                        <div className={style.newSpace_title}>腾讯新闻流量场景</div>
                        <Form.Item name='tencentNewsType' style={{ marginBottom: 0 }}>
                            <Radio.Group>
                                <Radio value="0">不限</Radio>
                                <Radio value="1">自定义</Radio>
                            </Radio.Group>
                        </Form.Item>
                    </div>
                    {tencentNewsType === '1' && <div className={style.newSpace_bottom}>
                        <Form.Item name={['sceneSpec', 'tencentNews']} rules={[{ required: true, message: '请选择!' }]}>
                            <Checkbox.Group options={Object.keys(TENCENT_NEWS_ENUM)?.map(key => ({ label: TENCENT_NEWS_ENUM[key as keyof typeof TENCENT_NEWS_ENUM], value: key }))} />
                        </Form.Item>
                    </div>}
                </div>}

                {(siteSet?.includes('SITE_SET_MOBILE_UNION') || automaticSiteEnabled) && <div className={style.newSpace}>
                    <div className={style.newSpace_top}>
                        <div className={style.newSpace_title}>优量汇广告展示场景</div>
                        <Form.Item name='displaySceneType' style={{ marginBottom: 0 }}>
                            <Radio.Group>
                                <Radio value="0">不限</Radio>
                                <Radio value="1">自定义</Radio>
                            </Radio.Group>
                        </Form.Item>
                    </div>
                    {displaySceneType === '1' && <div className={style.newSpace_bottom}>
                        <Form.Item name={['sceneSpec', 'displayScene']} rules={[{ required: true, message: '请选择!' }]}>
                            <Checkbox.Group options={Object.keys(DISPLAY_SCENE_ENUM)?.map(key => ({ label: DISPLAY_SCENE_ENUM[key as keyof typeof DISPLAY_SCENE_ENUM], value: key }))} />
                        </Form.Item>
                    </div>}
                </div>}
            </Card>
        </Form.Item>}
    </Card>
}


export default React.memo(AdgroupsSitSet)