import React, { useContext, useEffect, useState } from "react"
import style from '../index.less'
import { Button, Radio, Space, Typography } from "antd"
import { PlusCircleOutlined, PlusOutlined, RedoOutlined } from "@ant-design/icons"
import SelectTarget from "./selectTarget"
import { DispatchAddelivery } from ".."
import { useModel } from "umi"
import DataItem from "./dataItem"
import AddTarget from "./addTarget"
import GenerateTarget from "./generateTarget"
import { sdpRules } from "../../rules"
import { SMART_DELIVERY_PLATFORM_ENUM } from "../../const"
import { toCamelCase } from "@/utils/utils"
const { Title } = Typography;

/**
 * 定向
 * @returns 
 */
const Target: React.FC = () => {

    /***************************************/
    const { geoLocationList, modelList } = useModel('useLaunchV3.useTargeting')
    const { addelivery, setAddelivery, clearData, putInType, setIsDqSubmit, targetRules, setTargetRules } = useContext(DispatchAddelivery)!;
    const { targeting, adgroups } = addelivery
    const { smartTargetingMode } = adgroups
    const [addVisible, setAddVisible] = useState<boolean>(false)
    const [addTemVisible, setAddTemVisible] = useState<boolean>(false)
    const [modifyDta, setModifyDta] = useState<any>()
    const [modifyLength, setModifyLength] = useState<number>()
    const [copyDta, setCopyDta] = useState<any>()
    const [copyVisible, setCopyVisible] = useState<boolean>(false)
    const [stm, setStm] = useState<'SMART_TARGETING_OPEN' | 'SMART_TARGETING_MANUAL'>()
    /***************************************/

    useEffect(() => {
        setStm(smartTargetingMode || 'SMART_TARGETING_OPEN')
    }, [smartTargetingMode])

    // 如果是智能投放 处理定向规则
    useEffect(() => {
        if (adgroups && adgroups?.deliveryMethod === "SMART" && adgroups?.smartDeliveryPlatform && adgroups?.smartDeliverySceneSpec?.smartDeliveryGoal) {
            const { smartDeliveryPlatform, smartDeliverySceneSpec: { smartDeliveryGoal } } = adgroups
            const option = sdpRules.find(item => item.smart_delivery_platform === smartDeliveryPlatform)?.smart_delivery_goal_options?.find(item => item.value === smartDeliveryGoal)
            if (option) {
                const targetingRules = option.parameter_definitions.adgroup.find(item => item.field_name === 'targeting')
                setTargetRules?.({
                    desc: '场景化投放-' + SMART_DELIVERY_PLATFORM_ENUM[smartDeliveryPlatform as keyof typeof SMART_DELIVERY_PLATFORM_ENUM],
                    rules: targetingRules?.sub_field_whitelist?.map(item => toCamelCase(item.field_name) as string) || []
                })
            }
        } else {
            setTargetRules?.(undefined)
        }
    }, [adgroups])

    const setSmartTargetingMode = (smartTargetingMode: 'SMART_TARGETING_OPEN' | 'SMART_TARGETING_MANUAL') => {
        const adgroups = { ...addelivery.adgroups, smartTargetingMode }
        if (smartTargetingMode === 'SMART_TARGETING_OPEN') {
            delete adgroups?.smartTargetingMode
        }
        setAddelivery({ ...addelivery, adgroups })
    }

    return <>
        <div className={`${style.settingsBody_content_row} ${style.row2}`}>
            <div className={style.title}>
                <span>定向 <span className={style.selected}>已选 {targeting?.length || 0}</span></span>
                {targeting?.length > 0 && <Button
                    type="link"
                    size="small"
                    style={{ fontSize: 11, padding: 0 }}
                    onClick={() => {
                        setAddelivery({ ...addelivery, targeting: [] })
                        setIsDqSubmit?.(false)
                    }}
                ><RedoOutlined />清空</Button>}
            </div>
            <div className={style.detail}>
                <div className={style.detail_body}>
                    {targeting?.length > 0 && <>
                        {<Space style={{ marginBottom: 5 }}>
                            <Title level={5} style={{ fontSize: 12, marginBottom: 0 }}>全部相同</Title>
                            <Radio.Group
                                value={stm}
                                size="small"
                                optionType="button"
                                buttonStyle="solid"
                                options={[
                                    { label: '智能定向', value: 'SMART_TARGETING_OPEN' },
                                    { label: '手动定向', value: 'SMART_TARGETING_MANUAL' }
                                ]}
                                onChange={(e) => setSmartTargetingMode(e.target.value)}
                            />
                        </Space>}
                        {targeting?.map((item: { targetingName: any; targeting: any, taskType: 'NOVEL' | 'GAME', id?: number }, index: number) => <div key={index}>
                            <DataItem
                                geoLocationList={geoLocationList}
                                modelList={modelList}
                                key={index}
                                taksType={item.taskType || putInType}
                                targeting={{ targetingName: item.targetingName, ...item.targeting }}
                                onClear={() => {
                                    let newTargeting: any[] = JSON.parse(JSON.stringify(targeting))
                                    setIsDqSubmit?.(false)
                                    setAddelivery({ ...addelivery, targeting: newTargeting.filter((_, i) => index !== i) })
                                }}
                                onModify={() => {
                                    setModifyLength(index)
                                    setModifyDta({ targetingName: item?.id ? ('修_' + item.targetingName) : item.targetingName, ...item.targeting })
                                    setAddTemVisible(true)
                                }}
                                onCopy={() => {
                                    setCopyDta(item)
                                    setCopyVisible(true)
                                }}
                            />
                        </div>)}
                    </>}
                </div>
                <div className={style.detail_footer}>
                    <Button
                        type="link"
                        icon={<PlusOutlined />}
                        style={{ padding: 0, fontSize: 12 }}
                        onClick={() => {
                            setModifyDta(undefined)
                            setAddTemVisible(true)
                            setModifyLength(undefined)
                        }}
                        disabled={!(adgroups && Object.keys(adgroups)?.length > 0)}
                    >
                        新增
                    </Button>
                    <Button disabled={!(adgroups && Object.keys(adgroups)?.length > 0)} type="link" icon={<PlusCircleOutlined />} style={{ padding: 0, fontSize: 12 }} onClick={() => setAddVisible(true)}>添加</Button>
                </div>
            </div>
        </div>


        {/* 添加定向 */}
        {addVisible && <SelectTarget
            value={targeting?.filter(item => item?.id)}
            visible={addVisible}
            putInType={putInType}
            targetRules={targetRules}
            onClose={() => {
                setAddVisible(false)
            }}
            onChange={(target) => {
                // 获取当前新增的，不是模板复制的全是当前和模板没关系
                let currentTarget = targeting?.filter((item: { id: any }) => !item?.id) || []
                setAddelivery({ ...addelivery, targeting: [...target, ...currentTarget] })
                setAddVisible(false)
                clearData()
                setIsDqSubmit?.(false)
            }}
        />}

        {/* 新增修改定向模板 */}
        {addTemVisible && <AddTarget
            value={modifyDta}
            isBackVal={true}
            putInType={putInType}
            visible={addTemVisible}
            targetRules={targetRules}
            onClose={() => {
                setAddTemVisible(false)
                setModifyDta(undefined)
            }}
            onChange={(newTargeting) => {
                console.log('----->', newTargeting)
                setAddTemVisible(false)
                setModifyDta(undefined)
                let newTarget: any[] = JSON.parse(JSON.stringify(targeting || []))
                if (modifyLength !== undefined) {
                    newTarget[modifyLength] = newTargeting
                } else {
                    newTarget.push(newTargeting)
                }
                setModifyLength(undefined)
                setAddelivery({ ...addelivery, targeting: newTarget })
                clearData()
                setIsDqSubmit?.(false)
            }}
        />}

        {/* 一键生成 */}
        {copyVisible && <GenerateTarget
            target={copyDta}
            visible={copyVisible}
            onClose={() => {
                setCopyDta(undefined)
                setCopyVisible(false)
            }}
            onChange={(value) => {
                let newTarget: any[] = JSON.parse(JSON.stringify(targeting || []))
                newTarget = newTarget.concat(value)
                setCopyDta(undefined)
                setCopyVisible(false)
                setAddelivery({ ...addelivery, targeting: newTarget })
                clearData()
                setIsDqSubmit?.(false)
            }}
        />}
    </>
}

export default React.memo(Target)