import { DownOutlined, ExclamationCircleOutlined, QuestionCircleOutlined, UpOutlined } from "@ant-design/icons"
import { Button, Checkbox, DatePicker, Input, InputNumber, message, Modal, Radio, RadioChangeEvent, Select, Space, Switch, Tooltip } from "antd"
import { CheckboxValueType } from "antd/lib/checkbox/Group"
import moment from "moment"
import React, { useCallback, useEffect, useState } from "react"
import { useModel } from "umi"
import { inactionlist, connections, telcoms, deviceprices, oss, educations, wechatPositionList } from "../adList"
import style from './index.less'

const ageVal = {
    start: [14, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65],
    end: [18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65]
}

interface Props {
    visible: boolean,
    hideModel: () => void
}

function AdBasicConfig(props: Props) {
    const { visible, hideModel } = props

    // ===变量start===
    const { state, dispatch, setAdgroup, setTargeting, setAgeHandle, setTargeting_wab, setAdcreativeType, resetPage } = useModel('useLaunch.useNewCreateAd')
    const { targeting, adgroup, campaign } = state
    const { campaign_name } = campaign
    const { site_set, begin_date, end_date, bid_mode, optimization_goal, bid_strategy, daily_budget, bid_amount, deep_conversion_spec, scene_spec } = adgroup
    const { age, gender, education, user_os, device_price, network_operator, network_type, wechat_ad_behavior } = targeting
    const [onShow, setOnShow] = useState<boolean>(false)
    const [wpShow, setWpShow] = useState<boolean>(false)  // 是否开启广告位定向
    const [wpList, setWpList] = useState<{ label: string, value: number, bid_mode: string[], disabled?: boolean }[]>(wechatPositionList)
    const [mode, setMode] = useState<string>('All')
    // ===变量end===

    // 初始化
    useEffect(() => {
        if (scene_spec && scene_spec?.wechat_position?.length > 0) {
            setWpShow(() => true)
        }
    }, [])

    // 判断广告位勾选
    useEffect(() => {
        // 处理广告位是否可选
        if (scene_spec && scene_spec?.wechat_position?.length > 0) {
            let wpdata = scene_spec?.wechat_position
            if (wpdata?.indexOf(1024790) !== -1) {
                setMode(() => 'OCPC')
                setWpList(() => wpList.map((item: { label: string, value: number, bid_mode: string[], disabled?: boolean }) => {
                    if (item.value === 1024791 || item.value === 1024795) {
                        return { ...item, disabled: true }
                    } else {
                        return { ...item, disabled: false }
                    }
                }))
            } else if (wpList.find((item: { value: number, disabled?: boolean }) => item.value === 1024791)?.disabled) {
                setMode(() => 'All')
                setWpList(() => wpList.map((item: { label: string, value: number, bid_mode: string[], disabled?: boolean }) => {
                    return { ...item, disabled: false }
                }))
            }
            if (wpdata?.indexOf(1024791) !== -1 || wpdata?.indexOf(1024795) !== -1) {
                setMode(() => 'OCPM')
                setWpList(() => wpList.map((item: { label: string, value: number, bid_mode: string[], disabled?: boolean }) => {
                    if (item.value === 1024790) {
                        return { ...item, disabled: true }
                    } else {
                        return { ...item, disabled: false }
                    }
                }))
            } else if (wpList.find((item: { value: number, disabled?: boolean }) => item.value === 1024790)?.disabled) {
                setMode(() => 'All')
                setWpList(() => wpList.map((item: { label: string, value: number, bid_mode: string[], disabled?: boolean }) => {
                    return { ...item, disabled: false }
                }))
            }
        } else {
            setMode(() => 'All')
            setWpList(() => wpList.map((item: any) => ({ ...item, disabled: false })))
        }
    }, [scene_spec?.wechat_position])

    /** 确定按妞 */
    const handleOk = useCallback(() => {
        console.log(scene_spec?.wechat_position)
        if (wpShow && scene_spec?.wechat_position?.length === 0) {
            message.error('请选择广告位')
            return
        }
        hideModel()
    }, [wpShow, scene_spec])


    // 不可选择日期
    function disabledDate(current: any) {
        return current && current < moment().subtract(1, 'day') || current > (moment().add(1, 'year').startOf('day'))
    }

    // 结束日期不可选择日期
    const disabledEndDate = useCallback((current: any) => {
        if (begin_date) {
            return current && current < moment(begin_date) || current < moment().subtract(1, 'day') || current > (moment().add(1, 'year').startOf('day'))
        } else {
            return current && current < moment().subtract(1, 'day') || current > (moment().add(1, 'year').startOf('day'))
        }
    }, [begin_date])

    console.log('=====', state.adcreative)

    return <Modal
        bodyStyle={{ height: 600, overflowY: 'auto' }}
        title="广告基本信息"
        visible={visible}
        onCancel={() => { hideModel && hideModel() }}
        width={950}
        className={style.AdBasicConfig}
        footer={<div className={style.footer}>
            <div></div>
            <Space>
                <Button onClick={() => { hideModel && hideModel() }}>取消</Button>
                <Button type="primary" onClick={handleOk}>确定</Button>
            </Space>
        </div>}
    >
        <div className={style.title}>投放计划名称</div>
        <div className={style.form}>
            <div className={style.content}>
                <div className={style.label} style={{ width: 90 }}><label>投放计划名称</label></div>
                <div className={style.control}>
                    <div className={style.children}>
                        <div className={style.inputGroup}>
                            <Input className={`${style.input}`} placeholder='自定义标记' value={campaign_name} onChange={(e) => { 
                                dispatch({type: 'setCampaign', params: { ...state, campaign: { ...state.campaign, campaign_name: e.target.value } }})
                             }} maxLength={16} />
                            <span style={{ paddingRight: 8 }}>{`<当前时间>`}</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div className={style.title}>推广目标</div>
        <BcForm name="推广目标">
            <Radio.Group value={1} onChange={() => { }} className={style.radio}>
                <Radio.Button value={1}>公众号推广</Radio.Button>
            </Radio.Group>
        </BcForm>
        <div className={style.title}>投放位置</div>
        <BcForm name="流量位">
            <Radio.Group value={site_set[0]} className={style.radio} onChange={(e) => {
                resetPage()
                setAdgroup('site_set', [e.target.value])
                if (e.target.value === 'SITE_SET_MOMENTS') {
                    setWpShow(false)
                    setAdcreativeType("311")
                } else if (e.target.value === 'SITE_SET_WECHAT') {
                    setAdcreativeType("929")
                }
            }}>
                <Radio.Button value="SITE_SET_MOMENTS">朋友圈信息流</Radio.Button>
                <Radio.Button value="SITE_SET_WECHAT">公众平台流量</Radio.Button>
            </Radio.Group>
        </BcForm>
        {site_set[0] === 'SITE_SET_WECHAT' && <>
            <BcForm name="广告位定向" tips='让广告在指定广告位中展示'>
                <Switch checked={wpShow} size="small" onChange={(e) => {
                    setWpShow(e)
                    if (!e) {
                        setAdgroup('scene_spec', { wechat_position: [] })
                    }
                }} />
            </BcForm>
            {wpShow && <BcForm name="广告位" flex='flex-start'>
                <Checkbox.Group
                    options={wpList}
                    style={{ marginTop: 5 }}
                    value={scene_spec?.wechat_position}
                    onChange={(checkedValue: CheckboxValueType[]) => {
                        setAdgroup('scene_spec', { wechat_position: checkedValue })
                    }}
                />
            </BcForm>}
        </>}


        <div className={style.title}>投放时间</div>
        <BcForm name='开始与结束日期' >
            <div style={{ display: 'flex', justifyContent: 'flex-start', alignItems: 'center' }}>
                <DatePicker
                    className={style.picker}
                    disabledDate={disabledDate}
                    value={begin_date ? moment(begin_date) : undefined}
                    onChange={(e: moment.Moment | null) => {
                        setAdgroup('begin_date', e ? moment(e).format('YYYY-MM-DD') : "")
                    }}
                    allowClear={false}
                    placeholder="开始日期"
                />
                <span style={{ margin: '0 10px' }}>-</span>
                <DatePicker
                    className={style.picker}
                    disabledDate={disabledEndDate}
                    value={end_date ? moment(end_date) : undefined}
                    onChange={(e: moment.Moment | null) => {
                        setAdgroup('end_date', e ? moment(e).format('YYYY-MM-DD') : "")
                    }}
                    allowClear={false}
                    placeholder="结束日期"
                />
            </div>
        </BcForm>
        <BcForm name="投放时段">
            <Radio.Group value={"1"} className={style.radio} onChange={(e) => { }}>
                <Radio.Button value="1">全天投放</Radio.Button>
            </Radio.Group>
        </BcForm>

        <div className={style.title}>预算出价</div>
        <BcForm name="出价方式">
            <Radio.Group className={style.radio} value={bid_mode} onChange={(e) => { setAdgroup('bid_mode', e.target.value); resetPage() }}>
                {site_set[0] === 'SITE_SET_MOMENTS' ? <>
                    <Radio.Button value="BID_MODE_OCPM">oCPM</Radio.Button>
                    <Radio.Button value="BID_MODE_CPM">CPM</Radio.Button>
                </> : mode === 'All' ? <>
                    <Radio.Button value="BID_MODE_OCPM">oCPM</Radio.Button>
                    <Radio.Button value="BID_MODE_OCPC">oCPC</Radio.Button>
                </> : mode === 'OCPM' ? <Radio.Button value="BID_MODE_OCPM">oCPM</Radio.Button> : <Radio.Button value="BID_MODE_OCPC">oCPC</Radio.Button>}
            </Radio.Group>
        </BcForm>
        {(bid_mode === 'BID_MODE_OCPM' || bid_mode === 'BID_MODE_OCPC') && <>
            <BcForm name="优化目标">
                <Radio.Group className={style.radio} value={optimization_goal} onChange={(e) => { setAdgroup('optimization_goal', e.target.value) }}>
                    <Radio value="OPTIMIZATIONGOAL_FOLLOW">关注</Radio>
                    <Radio value="OPTIMIZATIONGOAL_ECOMMERCE_ORDER">下单</Radio>
                </Radio.Group>
            </BcForm>
            <BcForm name="投放模式">
                <Radio.Group className={style.radio} value={bid_strategy} onChange={(e) => { setAdgroup('bid_strategy', e.target.value) }}>
                    <Radio value="BID_STRATEGY_AVERAGE_COST">均衡投放</Radio>
                    <Radio value="BID_STRATEGY_TARGET_COST">优先跑量</Radio>
                    <Radio value="BID_STRATEGY_PRIORITY_CAP_COST">控制成本上限</Radio>
                </Radio.Group>
            </BcForm>

            {optimization_goal === 'OPTIMIZATIONGOAL_FOLLOW' && <>
                <BcForm name="深度优化">
                    <Radio.Group className={style.radio} value={deep_conversion_spec ? 'DEEP_CONVERSION_WORTH' : 'All'} onChange={(e) => {
                        setAdgroup('deep_conversion_spec', e.target.value === 'All' ? 'All' : {
                            deep_conversion_type: "DEEP_CONVERSION_WORTH",
                            deep_conversion_worth_spec: {
                                goal: "GOAL_1DAY_PURCHASE_ROAS",
                                expected_roi: 10
                            }
                        })
                    }}>
                        <Radio value="All">不启用</Radio>
                        <Radio value="DEEP_CONVERSION_WORTH">
                            优化转化价值
                            <Tooltip title="注意：公众号需要开通《优化转化价值》，没开通不允许选择创建">
                                <QuestionCircleOutlined style={{ color: 'red', marginLeft: 6 }} />
                            </Tooltip>
                        </Radio>
                    </Radio.Group>
                </BcForm>
                {deep_conversion_spec?.deep_conversion_type === 'DEEP_CONVERSION_WORTH' && <>
                    <BcForm name="价值优化目标">
                        <Radio.Group className={style.radio} value={deep_conversion_spec?.deep_conversion_worth_spec?.goal} onChange={(e) => { }}>
                            <Radio value="GOAL_1DAY_PURCHASE_ROAS">首日付费ROI</Radio>
                        </Radio.Group>
                    </BcForm>
                    <BcForm name="ROI目标值" flex='flex-start' footTips={`ROI 目标范围0.001~1000，计算公式： ROI = 广告转化价值/广告消耗。输入0.05，表示ROI目标为5%`}>
                        <InputNumber min={0.001} max={1000} className={style.input} step={1} placeholder="请输入" value={deep_conversion_spec?.deep_conversion_worth_spec?.expected_roi / 100} onChange={(e) => {
                            setAdgroup('deep_conversion_spec', {
                                deep_conversion_type: "DEEP_CONVERSION_WORTH",
                                deep_conversion_worth_spec: {
                                    goal: "GOAL_1DAY_PURCHASE_ROAS",
                                    expected_roi: e * 100
                                }
                            })
                        }} />
                    </BcForm>
                </>}
            </>}

            <BcForm
                flex='flex-start'
                name="每日预算"
                footTips='广告日预算有效范围为 50 元 ~ 40,000,000 元/天'>
                <Space>
                    <InputNumber
                        placeholder="请输入"
                        min={50}
                        className={style.input}
                        value={daily_budget !== '0' ? Number(daily_budget) / 100 : 0}
                        onChange={(e) => {
                            setAdgroup('daily_budget', e !== 0 ? (e * 100).toString() : '0')
                        }}
                    />
                    <div style={{ width: 40 }}>元/天</div>
                </Space>
            </BcForm>
            <BcForm
                flex='flex-start'
                name="出价"
                footTips={`出价有效范围为 0.1 元 ~ 5,000 元/${optimization_goal === 'OPTIMIZATIONGOAL_FOLLOW' ? '关注' : '下单'}`}>
                <Space>
                    <InputNumber
                        placeholder="请输入"
                        className={style.input}
                        min={0.1}
                        value={bid_amount !== '0' ? Number(bid_amount) / 100 : 0}
                        onChange={(e) => {
                            setAdgroup('bid_amount', e !== 0 ? (e * 100).toString() : '0')
                        }}
                    />
                    <div>元/{optimization_goal === 'OPTIMIZATIONGOAL_FOLLOW' ? '关注' : '下单'}</div>
                </Space>
            </BcForm>
        </>}

        <div className={style.title}>定向拓展</div>
        <BcForm name="地域">
            <Radio.Group className={style.radio} value={'1'} onChange={(e) => { }}>
                <Radio value="1">常住地</Radio>
                {/* <Radio value="2">差旅出行</Radio> */}
            </Radio.Group>
        </BcForm>
        <BcForm name="地域选择">
            <Radio.Group className={style.radio} value={'1'} onChange={(e) => { }}>
                <Radio value="1">全选</Radio>
            </Radio.Group>
        </BcForm>

        <BcForm name="年龄">
            <div style={{ display: 'flex', justifyContent: 'flex-start', alignItems: 'center' }}>
                <Select className={style.select} value={age[0].min} onChange={(value) => { setAgeHandle(value, 'min') }}>
                    {ageVal.start?.map((item: number) => (<Select.Option value={item} key={`start` + item}>{item}岁</Select.Option>))}
                </Select>
                <span style={{ display: 'inline-block', width: '24px', lineHeight: '32px', textAlign: 'center' }} > - </span>
                <Select className={style.select} value={age[0].max} onChange={(value) => { setAgeHandle(value, 'max') }}>
                    {ageVal.end?.map((item: number) => (<Select.Option value={item} key={`end` + item}>{item}岁</Select.Option>))}
                    <Select.Option value={66}>65岁以上</Select.Option>
                </Select>
            </div>
        </BcForm>

        <BcForm name="性别">
            <Radio.Group className={style.radio} value={gender ? gender[0] : 'All'} onChange={(e) => { setTargeting('gender', e.target.value === 'All' ? e.target.value : [e.target.value]) }}>
                <Radio value="All">不限</Radio>
                <Radio value="MALE">男</Radio>
                <Radio value="FEMALE">女</Radio>
            </Radio.Group>
        </BcForm>

        <a onClick={() => setOnShow(!onShow)} style={{ marginBottom: 20, display: 'block' }}>更多人群信息{onShow ? <UpOutlined /> : <DownOutlined />}</a>
        {
            onShow && <>
                <BcForm name="学历">
                    <>
                        <Radio.Group className={style.radio} value={education ? 'true' : 'All'} onChange={(e: RadioChangeEvent) => {
                            setTargeting('education', e.target.value === 'All' ? 'All' : [])
                        }}>
                            <Radio value="All">不限</Radio>
                            <Radio value="true">自定义</Radio>
                        </Radio.Group>
                        {education && <Checkbox.Group
                            options={educations}
                            style={{ marginTop: 5 }}
                            value={education}
                            onChange={(checkedValue: CheckboxValueType[]) => {
                                setTargeting('education', checkedValue)
                            }} />}
                    </>
                </BcForm>
                <BcForm name="操作系统">
                    <>
                        <Radio.Group className={style.radio} value={user_os ? 'true' : 'All'} onChange={(e: RadioChangeEvent) => {
                            setTargeting('user_os', e.target.value === 'All' ? 'All' : [])
                        }}>
                            <Radio value="All">不限</Radio>
                            <Radio value="true">自定义</Radio>
                        </Radio.Group>
                        {user_os && <Checkbox.Group
                            options={oss}
                            style={{ marginTop: 5 }}
                            value={user_os}
                            onChange={(checkedValue: CheckboxValueType[]) => {
                                setTargeting('user_os', checkedValue)
                            }} />}
                    </>
                </BcForm>
                <BcForm name="手机价格">
                    <>
                        <Radio.Group className={style.radio} value={device_price ? 'true' : 'All'} onChange={(e: RadioChangeEvent) => {
                            setTargeting('device_price', e.target.value === 'All' ? 'All' : [])
                        }}>
                            <Radio value="All">不限</Radio>
                            <Radio value="true">自定义</Radio>
                        </Radio.Group>
                        {device_price && <Checkbox.Group
                            options={deviceprices}
                            style={{ marginTop: 5 }}
                            value={device_price}
                            onChange={(checkedValue: CheckboxValueType[]) => {
                                setTargeting('device_price', checkedValue)
                            }} />}
                    </>
                </BcForm>
                <BcForm name="运营商">
                    <>
                        <Radio.Group className={style.radio} value={network_operator ? 'true' : 'All'} onChange={(e: RadioChangeEvent) => {
                            setTargeting('network_operator', e.target.value === 'All' ? 'All' : [])
                        }}>
                            <Radio value="All">不限</Radio>
                            <Radio value="true">自定义</Radio>
                        </Radio.Group>
                        {network_operator && <Checkbox.Group
                            options={telcoms}
                            style={{ marginTop: 5 }}
                            value={network_operator}
                            onChange={(checkedValue: CheckboxValueType[]) => {
                                setTargeting('network_operator', checkedValue)
                            }} />}
                    </>
                </BcForm>
                <BcForm name="联网方式">
                    <>
                        <Radio.Group className={style.radio} value={network_type ? 'true' : 'All'} onChange={(e: RadioChangeEvent) => {
                            setTargeting('network_type', e.target.value === 'All' ? 'All' : [])
                        }}>
                            <Radio value="All">不限</Radio>
                            <Radio value="true">自定义</Radio>
                        </Radio.Group>
                        {network_type && <Checkbox.Group
                            options={connections}
                            style={{ marginTop: 5 }}
                            value={network_type}
                            onChange={(checkedValue: CheckboxValueType[]) => {
                                setTargeting('network_type', checkedValue)
                            }} />}
                    </>
                </BcForm>
                <BcForm name="再营销">
                    <>
                        <Radio.Group className={style.radio} value={wechat_ad_behavior?.actions ? 'true' : 'All'} onChange={(e: RadioChangeEvent) => {
                            setTargeting_wab('actions', e.target.value === 'All' ? 'All' : [])
                        }}>
                            <Radio value="All">不限</Radio>
                            <Radio value="true">自定义</Radio>
                        </Radio.Group>
                        {wechat_ad_behavior?.actions && <Checkbox.Group
                            options={inactionlist}
                            style={{ marginTop: 5 }}
                            value={wechat_ad_behavior?.actions}
                            onChange={(checkedValue: CheckboxValueType[]) => {
                                setTargeting_wab('actions', checkedValue)
                            }} />}
                    </>
                </BcForm>
                <BcForm name="排除营销">
                    <>
                        <Radio.Group className={style.radio} value={wechat_ad_behavior?.excluded_actions ? 'true' : 'All'} onChange={(e: RadioChangeEvent) => {
                            setTargeting_wab('excluded_actions', e.target.value === 'All' ? 'All' : [])
                        }}>
                            <Radio value="All">不限</Radio>
                            <Radio value="true">自定义</Radio>
                        </Radio.Group>
                        {wechat_ad_behavior?.excluded_actions && <Checkbox.Group
                            options={inactionlist}
                            style={{ marginTop: 5 }}
                            value={wechat_ad_behavior?.excluded_actions}
                            onChange={(checkedValue: CheckboxValueType[]) => {
                                setTargeting_wab('excluded_actions', checkedValue)
                            }} />}
                    </>
                </BcForm>
            </>
        }
    </Modal>
}

interface BcProps {
    name?: string | JSX.Element,
    children?: JSX.Element | string,
    tips?: string,
    footTips?: string,
    flex?: 'flex-start' | 'center' | 'flex-end'
    bottom?: number | string
}
export function BcForm(props: BcProps) {
    let { name = '', children = '', tips, footTips, flex = 'center', bottom = 24 } = props
    return <div className={style.form}>
        <div className={style.content} style={{ alignItems: flex, marginBottom: bottom }}>
            <div className={style.label}><label>{name}</label></div>
            <div className={style.control}>
                <div className={style.children}>
                    {children}
                    {footTips && <div className={style.tips} style={{ margin: '5px 0 0 0' }}>{footTips}</div>}
                </div>
                {tips && <div className={style.tips}><ExclamationCircleOutlined style={{ color: '#FA8C16', marginRight: 10 }} />{tips}</div>}
            </div>
        </div>
    </div>
}

export default React.memo(AdBasicConfig)