import { Card, Form, Select, Switch } from "antd"
import React, { useContext, useEffect, useState } from "react"
import MarketingGoal from "./marketingGoal"
import NewRadio from "@/pages/launchSystemV3/components/NewRadio"
import { DispatchAd } from "./newCreateAd"
import { GOAL_ROAS_ENUM, MARKETING_CARRIER_TYPE_ENUM, MARKETING_TARGET_TYPE_ENUM, OPTIMIZATIONGOAL_ENUM, defaultSiteSet } from "../../const"
import New1Radio from "@/pages/launchSystemV3/components/New1Radio"
import { useAjax } from "@/Hook/useAjax"
import { getOptimizationGoalPermissionsV3Api } from "@/services/adqV3/global"
import { adRules } from "../../rules"


/**
 * 营销内容
 * @param value 回填
 * @returns 
 */
const AdgroupsMarketingContent: React.FC<{ value?: any }> = ({ value }) => {

    /****************************************/
    const { form, OGPParams, setOGPparams } = useContext(DispatchAd)!;

    const marketingGoal = Form.useWatch('marketingGoal', form);
    const marketingTargetType = Form.useWatch('marketingTargetType', form);
    const marketingCarrierType = Form.useWatch('marketingCarrierType', form);
    const bidMode = Form.useWatch('bidMode', form);
    const optimizationGoal = Form.useWatch('optimizationGoal', form);
    const smartBidType = Form.useWatch('smartBidType', form);
    const depthConversionEnabled = Form.useWatch('depthConversionEnabled', form);
    const deepConversionType = Form.useWatch(['deepConversionSpec', 'deepConversionType'], form);
    // 推广产品
    const [marketingTargetTypeList, setMarketingTargetTypeList] = useState<PULLIN.DataType[]>([])
    const [marketingCarrierTypeList, setMarketingCarrierTypeList] = useState<PULLIN.DataType[]>([])
    const [rules, setRules] = useState<any>({})
    const [behaviorList, setBehaviorList] = useState<string[]>([])
    const [worthList, setWorthList] = useState<string[]>([])
    const [deepConversionData, setDeepConversionData] = useState<PULLIN.DataType[]>([])
    const [isUpdateOptimizationGoal, setIsUpdateOptimizationGoal] = useState<boolean>(false)

    const queryOptimizationGoalPermissions = useAjax((params) => getOptimizationGoalPermissionsV3Api(params))
    /****************************************/

    /** 获取深度优化 出价和版位改变时查询 */
    const getOptimizationGoalPermissions = () => {
        let marketingCarrierType = OGPParams?.marketingCarrierType
        let bidMode = OGPParams.bidMode
        let siteSet = OGPParams.siteSet
        let automaticSiteEnabled = OGPParams.automaticSiteEnabled
        let marketingGoal = OGPParams.marketingGoal
        let marketingTargetType = OGPParams?.marketingTargetType
        if (marketingTargetType === 'MARKETING_TARGET_TYPE_WECHAT_OFFICIAL_ACCOUNT') {
            marketingCarrierType = 'MARKETING_CARRIER_TYPE_WECHAT_OFFICIAL_ACCOUNT'
        }
        if ((bidMode && siteSet && siteSet?.length > 0 && marketingGoal && marketingCarrierType && marketingTargetType) || automaticSiteEnabled) {
            let obj: any = { siteSet: automaticSiteEnabled ? defaultSiteSet : siteSet, marketingGoal, marketingCarrierType: marketingCarrierType, marketingTargetType, marketingSubGoal: 'MARKETING_SUB_GOAL_UNKNOWN' }
            if (bidMode === 'BID_MODE_OCPC' || bidMode === 'BID_MODE_OCPM') {
                obj.bidMode = bidMode
            }
            queryOptimizationGoalPermissions.run(obj)
        }
    }

    useEffect(() => {
        if (OGPParams.marketingCarrierType && OGPParams.marketingTargetType) {
            getOptimizationGoalPermissions()
        }
    }, [OGPParams])

    // 处理深度转化优化
    useEffect(() => {
        if (optimizationGoal && queryOptimizationGoalPermissions?.data) {
            let { deepBehaviorOptimizationGoalPermissionList, deepWorthOptimizationGoalPermissionList } = queryOptimizationGoalPermissions?.data
            let behavior = deepBehaviorOptimizationGoalPermissionList?.find((item: { optimizationGoal: string }) => item.optimizationGoal === optimizationGoal)
            let worth = deepWorthOptimizationGoalPermissionList?.find((item: { optimizationGoal: string }) => item.optimizationGoal === optimizationGoal)
            let newBehaviorList = behavior?.deepBehaviorOptimizationGoalList || []
            setBehaviorList(newBehaviorList)
            let newWorthList = worth?.deepWorthOptimizationGoalList || []
            setWorthList(newWorthList)
            let newDeepConversionData: PULLIN.DataType[] = [];
            (newBehaviorList?.length > 0 && newDeepConversionData.push({ label: '优化转化行为', value: 'DEEP_CONVERSION_BEHAVIOR' }))
            { newWorthList?.length > 0 && newDeepConversionData.push({ label: '优化ROI', value: 'DEEP_CONVERSION_WORTH' }) }
            setDeepConversionData(newDeepConversionData)
            form.setFieldsValue({
                deepConversionSpec: {
                    deepConversionType: newBehaviorList?.length > 0 ? 'DEEP_CONVERSION_BEHAVIOR' : newWorthList?.length > 0 ? "DEEP_CONVERSION_WORTH" : ''
                }
            })
        }
    }, [optimizationGoal, queryOptimizationGoalPermissions?.data])

    // 选择营销目的触发
    useEffect(() => {
        let newRule: any = {}
        let newMarketingTargetTypeList: PULLIN.DataType[] = []
        if (marketingGoal) {
            newRule = adRules[marketingGoal]
            // 根据const里数据对比选出可展示数据
            newMarketingTargetTypeList = Object.keys(MARKETING_TARGET_TYPE_ENUM).filter(key => newRule?.[key]).map(key => ({ label: MARKETING_TARGET_TYPE_ENUM[key], value: key }))
        }
        setMarketingTargetTypeList(newMarketingTargetTypeList)
        setRules(newRule)
    }, [marketingGoal])

    // 推广产品设置默认值
    useEffect(() => {
        if (!(value && Object.keys(value).length > 0) && marketingTargetTypeList && (!marketingTargetType || (marketingTargetType && !marketingTargetTypeList.some(item => item.value === marketingTargetType)))) {
            form.setFieldsValue({ marketingTargetType: marketingTargetTypeList?.[0]?.value })
            // setOGPparams({ ...OGPParams, marketingTargetType: marketingTargetTypeList?.[0]?.value })
        }
    }, [marketingTargetType, marketingTargetTypeList, OGPParams, value])

    // 营销载体类型
    useEffect(() => {
        let newMarketingTargetTypeListList: PULLIN.DataType[] = []
        // 推广产品是公众号不展示 营销载体类型
        if (marketingTargetType) {
            let marketingTargetTypeRules: string[] = rules?.[marketingTargetType]?.MARKETING_SUB_GOAL_UNKNOWN
            newMarketingTargetTypeListList = Object.keys(MARKETING_CARRIER_TYPE_ENUM).filter(key => marketingTargetTypeRules?.[key]).map(key => ({ label: MARKETING_CARRIER_TYPE_ENUM[key], value: key }))
        }
        setMarketingCarrierTypeList(newMarketingTargetTypeListList)
    }, [marketingTargetType, rules])

    // 设置营销载体默认值
    useEffect(() => {
        if (!(value && Object.keys(value).length > 0) && !marketingCarrierType || (marketingCarrierType && !marketingCarrierTypeList.some(item => item.value === marketingCarrierType))) {
            let newMarketingCarrierType = marketingCarrierTypeList?.[0]?.value
            form.setFieldsValue({ marketingCarrierType: newMarketingCarrierType })
            setOGPparams({ ...OGPParams, marketingTargetType, marketingCarrierType: newMarketingCarrierType })
        }
    }, [marketingCarrierType, marketingCarrierTypeList, OGPParams, value, marketingTargetType])

    useEffect(() => {
        let optimizationGoalPermissionList: string[] = queryOptimizationGoalPermissions?.data?.optimizationGoalPermissionList
        if (isUpdateOptimizationGoal && optimizationGoalPermissionList?.length > 0 && !optimizationGoalPermissionList?.includes(optimizationGoal)) {
            form.setFieldsValue({ optimizationGoal: optimizationGoalPermissionList?.includes('OPTIMIZATIONGOAL_ECOMMERCE_ORDER') ? 'OPTIMIZATIONGOAL_ECOMMERCE_ORDER' : optimizationGoalPermissionList?.includes('OPTIMIZATIONGOAL_PAGE_SCAN_CODE') ? 'OPTIMIZATIONGOAL_PAGE_SCAN_CODE' : undefined })
            setIsUpdateOptimizationGoal(false)
        }
    }, [queryOptimizationGoalPermissions?.data?.optimizationGoalPermissionList, marketingGoal, marketingTargetType, marketingCarrierType, optimizationGoal, value, isUpdateOptimizationGoal])

    const setIsUpdate = () => {
        if (bidMode === 'BID_MODE_OCPM' || bidMode === 'BID_MODE_OCPC') {
            setIsUpdateOptimizationGoal(true)
        }
    }

    return <Card
        title={<strong style={{ fontSize: 18 }}>营销内容</strong>}
        className="cardResetCss"
    >
        <Form.Item name="marketingGoal" label={<strong>营销目的</strong>} rules={[{ required: true, message: '请选择营销目的!' }]}>
            <MarketingGoal onChange={(e) => { setOGPparams({ ...OGPParams, marketingGoal: e as string }); setIsUpdate() }} />
        </Form.Item>
        {marketingTargetTypeList?.length > 0 && <Form.Item name="marketingTargetType" label={<strong>推广产品</strong>} rules={[{ required: true, message: '请选择推广产品!' }]}>
            <NewRadio data={marketingTargetTypeList} onChange={(e) => {
                if (e === 'MARKETING_CARRIER_TYPE_WECHAT_OFFICIAL_ACCOUNT') { // 公众号
                    setOGPparams({ ...OGPParams, marketingTargetType: e, marketingCarrierType: 'MARKETING_CARRIER_TYPE_WECHAT_OFFICIAL_ACCOUNT' })
                    form.setFieldsValue({ marketingCarrierType: 'MARKETING_CARRIER_TYPE_WECHAT_OFFICIAL_ACCOUNT' })
                } else {
                    setOGPparams({ ...OGPParams, marketingTargetType: e })
                }
                setIsUpdate()
            }} />
        </Form.Item>}
        {marketingCarrierTypeList?.length > 0 && <Form.Item name="marketingCarrierType" label={<strong>营销载体类型</strong>} rules={[{ required: true, message: '请选择营销载体类型!' }]}>
            <New1Radio data={marketingCarrierTypeList} onChange={(e) => { setOGPparams({ ...OGPParams, marketingCarrierType: e }); setIsUpdate() }} />
        </Form.Item>}
        {(bidMode === 'BID_MODE_OCPM' || bidMode === 'BID_MODE_OCPC') && <>
            <Form.Item label={<strong>优化目标</strong>} name='optimizationGoal' rules={[{ required: true, message: '请选择优化目标' }]}>
                <Select
                    style={{ width: 480 }}
                    showSearch
                    filterOption={(input, option) =>
                        (option!.children as unknown as string)?.toLowerCase()?.includes(input?.toLowerCase())
                    }
                    allowClear
                    placeholder='请选择'
                    loading={queryOptimizationGoalPermissions.loading}
                >
                    {queryOptimizationGoalPermissions?.data?.optimizationGoalPermissionList.filter((key: string) => key !== 'UNKNOWN').map((key: string) => {
                        return <Select.Option value={key} key={key}>{OPTIMIZATIONGOAL_ENUM[key]}</Select.Option>
                    })}
                </Select>
            </Form.Item>
            {/* 深度优化 */}
            {((behaviorList?.length > 0 || worthList?.length > 0) && smartBidType !== 'SMART_BID_TYPE_SYSTEMATIC') && <>
                <Form.Item label={<strong>深度转化优化</strong>} name='depthConversionEnabled' valuePropName="checked">
                    <Switch checkedChildren="开启" unCheckedChildren="关闭" onChange={(e) => {
                        if (e) {
                            form.setFieldsValue({
                                deepConversionSpec: {
                                    deepConversionType: behaviorList?.length > 0 ? 'DEEP_CONVERSION_BEHAVIOR' : worthList?.length > 0 ? "DEEP_CONVERSION_WORTH" : ''
                                }
                            })
                        }
                    }} />
                </Form.Item>
                {depthConversionEnabled && <>
                    <Form.Item label={<strong>深度优化类型</strong>} name={['deepConversionSpec', 'deepConversionType']} rules={[{ required: true, message: '请选择深度优化类型' }]}>
                        <New1Radio data={deepConversionData} />
                    </Form.Item>
                    <Form.Item label={<strong>深度优化目标</strong>} name={['deepConversionSpec', deepConversionType === 'DEEP_CONVERSION_BEHAVIOR' ? 'deepConversionBehaviorSpec' : 'deepConversionWorthSpec', 'goal']} rules={[{ required: true, message: '请选择深度优化目标' }]}>
                        <Select style={{ width: 480 }} placeholder='请选择'>
                            {deepConversionType === 'DEEP_CONVERSION_BEHAVIOR' ? Object.keys(OPTIMIZATIONGOAL_ENUM).filter(key => behaviorList?.includes(key)).map(key => <Select.Option value={key} key={key}>{OPTIMIZATIONGOAL_ENUM[key]}</Select.Option>) : deepConversionType === 'DEEP_CONVERSION_WORTH' ?
                                Object.keys(GOAL_ROAS_ENUM).filter(key => worthList?.includes(key)).map(key => <Select.Option value={key} key={key}>{GOAL_ROAS_ENUM[key]}</Select.Option>) : null}
                        </Select>
                    </Form.Item>
                </>}
            </>}
        </>}
    </Card>
}

export default React.memo(AdgroupsMarketingContent)