import { adcreative311, adcreative1707, adcreative928, adcreative929 } from '@/pages/launchSystem/launchManageNew/weChatNew/components/createPlan/components/adList/styleData'
import { message } from 'antd'
import moment from 'moment'
import { Dispatch, useReducer } from 'react'
import { Campaign, Targeting, Adgroup, Adcreative, Material } from '../../pages/launchSystem/launchManage/req'
import { addPlanApi, adsPlan, getAdsPlanApi, adsPlanList, delBatchAjax, getAdsPlanLogApi, adsPlanLogList, delLogBatchAjax, setCopyPlanApi, CopyPlan } from '@/services/operating/adNewAuthorize'
import { useAjax } from '@/Hook/useAjax'

interface State {
    campaign: Campaign
    targeting: Targeting
    adgroup: Adgroup
    adcreative: Adcreative
    material: Material
    pageData: any[] // 落地页
    launchAcc: any[] // 定向包
    releases: { label: string, value: string, id: number }[] // 投放号
    release: string[]
}

const initData: State = {
    campaign: {
        campaign_name: "", //计划名称
        campaign_type: "CAMPAIGN_TYPE_NORMAL", //暂时固定
        promoted_object_type: "PROMOTED_OBJECT_TYPE_WECHAT_OFFICIAL_ACCOUNT", //推广目标--->  PROMOTED_OBJECT_TYPE_WECHAT_OFFICIAL_ACCOUNT->公众号推广  PROMOTED_OBJECT_TYPE_WECHAT_CHANNELS->视频号推广
        daily_budget: 0, //计划日预算
        speed_mode: "SPEED_MODE_STANDARD", //暂时固定
        application_platform: 3, //暂时固定
    },
    targeting: {
        age: [{
            min: 14,
            max: 66
        }],
        behavior_or_interest: {},
        device_brand_model: {},
        geo_location: {
            location_types: ["LIVE_IN"],
            regions: [110000, 120000, 130000, 140000, 150000, 210000, 220000, 230000, 310000, 320000, 330000, 340000, 350000, 360000, 370000, 410000, 420000, 430000, 440000, 450000, 460000, 500000, 510000, 520000, 530000, 540000, 610000, 620000, 630000, 640000, 650000]
        },
    },
    adgroup: {
        account_id: "17383887",
        adgroup_name: "", //广告名称
        begin_date: moment().startOf('day').add(4, 'M').format('YYYY-MM-DD'), //开始日期
        end_date: moment().startOf('day').add(12, 'M').format('YYYY-MM-DD'), //结束日期
        targeting: "", // Targeting
        time_series: "111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111",
        campaign_id: '',//计划ID
        configured_status: "AD_STATUS_NORMAL",
        daily_budget: "100000",   // 广告日预算
        bid_amount: "10", //出价
        expand_enabled: "false",
        promoted_object_id: "", // "wxf82b302b1dde69e9"
        promoted_object_type: "PROMOTED_OBJECT_TYPE_WECHAT_OFFICIAL_ACCOUNT", //推广目标--->  PROMOTED_OBJECT_TYPE_WECHAT_OFFICIAL_ACCOUNT->公众号推广  PROMOTED_OBJECT_TYPE_WECHAT_CHANNELS->视频号推广
        site_set: ["SITE_SET_MOMENTS"],   //流量位--->  SITE_SET_MOMENTS->朋友圈信息流  SITE_SET_WECHAT->公众平台流量
        bid_mode: "BID_MODE_OCPM", //出价方式--->   BID_MODE_OCPM->oCPM BID_MODE_OCPC->oCPC BID_MODE_CPM->CPM
        optimization_goal: "OPTIMIZATIONGOAL_ECOMMERCE_ORDER",  // 优化目标---> OPTIMIZATIONGOAL_CLICK->点击  OPTIMIZATIONGOAL_ECOMMERCE_ORDER->下单 OPTIMIZATIONGOAL_FOLLOW->关注 
        bid_strategy: "BID_STRATEGY_TARGET_COST",   // 投放模式--->  BID_STRATEGY_AVERAGE_COST->均衡投放  BID_STRATEGY_TARGET_COST->跑量优先  BID_STRATEGY_PRIORITY_CAP_COST->控制成本上线
        smart_bid_type: "SMART_BID_TYPE_CUSTOM",  // 投放模式--->  SMART_BID_TYPE_CUSTOM->手动模式  SMART_BID_TYPE_SYSTEMATIC->自动模式
        auto_acquisition_enabled: "false", //
        cold_start_audience: "[]",
    },
    adcreative: {
        account_id: "",
        campaign_id: "",
        adcreative_name: "",
        adcreative_template_id: "311",
        page_type: "PAGE_TYPE_CANVAS_WECHAT",
        adcreative_elements: {
            image_list: [""],  //
            title: ""   // 外层文案
        },
        page_spec: {
            page_id: "",  // 落地页ID 我们平台传name
        },
        countdown_switch: "false",
        head_click_type: "HEAD_CLICK_TYPE_DEFAULT",
        site_set: ["SITE_SET_MOMENTS"],   //流量位--->  SITE_SET_MOMENTS->朋友圈信息流  SITE_SET_WECHAT->公众平台流量
        promoted_object_type: "PROMOTED_OBJECT_TYPE_WECHAT_OFFICIAL_ACCOUNT", //推广目标--->  PROMOTED_OBJECT_TYPE_WECHAT_OFFICIAL_ACCOUNT->公众号推广  PROMOTED_OBJECT_TYPE_WECHAT_CHANNELS->视频号推广
        promoted_object_id: "",
        link_page_type: "LINK_PAGE_TYPE_WECHAT_OFFICIAL_ACCOUNT_DETAIL", // 文字链类型--->  LINK_PAGE_TYPE_WECHAT_OFFICIAL_ACCOUNT_DETAIL->微信公众号详情页 LINK_PAGE_TYPE_CANVAS_WECHAT->微信原生页
        link_name_type: "READ_NOVELS",   // 文字链文案---> READ_NOVELS->阅读小说 FOLLOW_OFFICIAL_ACCOUNT->关注公众号 MORE_INFO->了解更多
    },
    material: {
        page_name: ''
    },
    pageData: [],
    launchAcc: [],
    releases: [],
    release: []
}

interface Action {
    type: 'setCampaign' | 'setTargeting' | 'setAdgroup' | 'setAdcreative' | 'setMaterial' | 'setReleases' | 'setRelease' | 'setLaunchAcc' | 'setPageData' | 'setData' | 'init'
    params: State
}


function reducer(state: State, action: Action) {
    let { type, params } = action
    switch (type) {
        case 'setCampaign':
            return { ...state, campaign: { ...params.campaign } }
        case 'setTargeting':
            return { ...state, targeting: { ...params.targeting } }
        case 'setAdgroup':
            return { ...state, adgroup: { ...params.adgroup } }
        case 'setAdcreative':
            return { ...state, adcreative: { ...params.adcreative } }
        case 'setMaterial':
            return { ...state, material: { ...params.material } }
        case 'setReleases':
            return { ...state, releases: params.releases }
        case 'setRelease':
            return { ...state, release: params.release }
        case 'setPageData':
            return { ...state, pageData: params.pageData }
        case 'setLaunchAcc':
            return { ...state, launchAcc: params.launchAcc }
        case 'setData':
            return { ...state, ...params }
        case 'init':
            return { ...state, ...initData }
        default:
            return state;
    }
}

export default function useNewCreateAd() {
    const [state, dispatch]: [state: State, dispatch: Dispatch<Action>] = useReducer(reducer, initData)

    const { targeting, adgroup, adcreative, material } = state
    const { age } = targeting

    // 设置Adgroup
    const setAdgroup = (key: string, value: any) => {
        let newAdgroup = JSON.parse(JSON.stringify(adgroup))
        if(value !== 'All') {
            if(key === 'bid_mode') {
                let bid_mode = newAdgroup.bid_mode
                dispatch({type: 'setMaterial', params: { ...state, material: { page_name: material.page_name } }})
                if(value === 'BID_MODE_CPM') {
                    delete newAdgroup?.optimization_goal
                    delete newAdgroup?.bid_strategy
                    delete newAdgroup?.smart_bid_type
                    delete newAdgroup?.auto_acquisition_enabled
                    delete newAdgroup?.cold_start_audience
                } else if(bid_mode === 'BID_MODE_CPM') { // 现在在CPM 往其他地方点击
                    newAdgroup.optimization_goal = 'OPTIMIZATIONGOAL_ECOMMERCE_ORDER'
                    newAdgroup.bid_strategy = 'BID_STRATEGY_TARGET_COST'
                    newAdgroup.smart_bid_type = 'SMART_BID_TYPE_CUSTOM'
                    newAdgroup.auto_acquisition_enabled = 'false'
                    newAdgroup.cold_start_audience = "[]"
                }
                if(newAdgroup.site_set[0] === 'SITE_SET_WECHAT') { // 是公众平台流量
                    // if(newAdgroup?.scene_spec?.wechat_position?.length === 0) {
                        if(value === 'BID_MODE_OCPM') { // 视频 929
                            dispatch({ type: 'setAdcreative', params: { ...state, adcreative: { ...adcreative929 as Adcreative } } })
                        } else if(value === 'BID_MODE_OCPC') {  // 图片 928
                            dispatch({ type: 'setAdcreative', params: { ...state, adcreative: { ...adcreative928 as Adcreative } } })
                        }
                    // }
                }
            } else if(key === 'optimization_goal' && value === 'OPTIMIZATIONGOAL_ECOMMERCE_ORDER') { // 如果关注设置了深度优化 切换到下单 要清除
                delete newAdgroup?.deep_conversion_spec
            } else if(key === 'site_set') { // 设置流量位
                // setAdcreative('site_set', value)
                dispatch({type: 'setMaterial', params: { ...state, material: { page_name: material.page_name } }})
                if(value[0] === 'SITE_SET_WECHAT') { // 公众平台流量
                    newAdgroup.scene_spec = {
                        wechat_position: []
                    }
                    if(newAdgroup.bid_mode === 'BID_MODE_CPM') { // 如果是cpm要转
                        newAdgroup.bid_mode = 'BID_MODE_OCPM'
                        newAdgroup.optimization_goal = 'OPTIMIZATIONGOAL_ECOMMERCE_ORDER'
                        newAdgroup.bid_strategy = 'BID_STRATEGY_TARGET_COST'
                        newAdgroup.smart_bid_type = 'SMART_BID_TYPE_CUSTOM'
                        newAdgroup.auto_acquisition_enabled = 'false'
                        newAdgroup.cold_start_audience = "[]"
                    }
                } else {
                    if(Object.keys(newAdgroup).indexOf('scene_spec') !== -1) { // 朋友圈信息流
                        delete newAdgroup.scene_spec
                    }
                }
                if(value[0] === 'SITE_SET_MOMENTS') { // 朋友圈信息流
                    if(newAdgroup.bid_mode === 'BID_MODE_OCPC') { // 如果是OCPC要转
                        newAdgroup.bid_mode = 'BID_MODE_OCPM'
                    }
                }

            } else if(key === 'scene_spec') { // 设置广告位
                if(value.wechat_position.indexOf(1024790) !== -1) {
                    if(newAdgroup.bid_mode === 'BID_MODE_OCPM') {
                        dispatch({type: 'setMaterial', params: { ...state, material: { page_name: material.page_name } }})
                    }
                    newAdgroup.bid_mode = 'BID_MODE_OCPC'
                    dispatch({ type: 'setAdcreative', params: { ...state, adcreative: { ...adcreative928 as Adcreative } } })
                } else if(value.wechat_position.indexOf(1024791) !== -1 || value.wechat_position.indexOf(1024795) !== -1) {
                    if(newAdgroup.bid_mode === 'BID_MODE_OCPC') {
                        dispatch({type: 'setMaterial', params: { ...state, material: { page_name: material.page_name } }})
                    }
                    newAdgroup.bid_mode = 'BID_MODE_OCPM'
                    dispatch({ type: 'setAdcreative', params: { ...state, adcreative: { ...adcreative929 as Adcreative } } })
                }
            }
            newAdgroup[key] = value
        } else {
            for (const key1 in newAdgroup) {
                if (key1 === key) {
                    delete newAdgroup[key1]
                }
            }
        }
        dispatch({ type: 'setAdgroup', params: { ...state, adgroup: { ...newAdgroup } } })
    }

    // 设置targeting
    const setTargeting = (key: string, value: any) => {
        let newTargeting = JSON.parse(JSON.stringify(targeting))
        if (value !== 'All') {
            newTargeting[key] = value
        } else {
            for (const key1 in newTargeting) {
                if (key1 === key) {
                    delete newTargeting[key1]
                }
            }
        }
        dispatch({ type: 'setTargeting', params: { ...state, targeting: { ...newTargeting } } })
    }

    // 设置targeting wechat_ad_behavior
    const setTargeting_wab = (key: string, value: any) => {
        let newTargeting = JSON.parse(JSON.stringify(targeting))
        if (value !== 'All') {
            if(Object.keys(newTargeting).indexOf('wechat_ad_behavior') === -1) {
                newTargeting['wechat_ad_behavior'] = {}
            }
            newTargeting['wechat_ad_behavior'][key] = value
        } else {
            for (const key1 in newTargeting) {
                if (key1 === 'wechat_ad_behavior') {
                    for (const key2 in newTargeting[key1]) {
                        if (key2 === key) {
                            delete newTargeting[key1][key2]
                        }
                    }
                    if(Object.keys(newTargeting[key1]).length === 0) {
                        delete newTargeting[key1]
                    }
                }
            }
        }
        dispatch({ type: 'setTargeting', params: { ...state, targeting: { ...newTargeting } } })
    }

    // 设置年龄
    const setAgeHandle = (value: number, type: 'min' | 'max') => {
        age[0][type] = value
        dispatch({ type: 'setTargeting', params: { ...state, targeting: { ...targeting, age } } })
    }

    // 设置adcreative
    const setAdcreative = (key: string, value: any) => {
        let newAdcreative = JSON.parse(JSON.stringify(adcreative))
        if (value !== 'All') {
            newAdcreative[key] = value
            if (key === 'page_spec' && value?.override_canvas_head_option === 'OPTION_CANVAS_OVERRIDE_CREATIVE') {
                dispatch({type: 'setMaterial', params: { ...state, material: { page_name: material.page_name || "" } }})
            }
        } else {
            for (const key1 in newAdcreative) {
                if (key1 === key) {
                    delete newAdcreative[key1]
                }
            }
        }
        dispatch({ type: 'setAdcreative', params: { ...state, adcreative: { ...newAdcreative } } })
    }


    // 设置创意样式
    const setAdcreativeType = (value: string) => {
        // adcreative311, adcreative1707
        if (['311', '641', '642', '643', '618', '1465', '1480'].includes(value)) {
            let newAdEle = JSON.parse(JSON.stringify(adcreative311?.adcreative_elements)) || { title: '', image_list: [""] }
            if(['311', '641', '642', '643'].includes(value)) {
                delete newAdEle?.short_video_struct
                newAdEle.image_list = [""]
            } else {
                delete newAdEle?.image_list
                newAdEle.short_video_struct = {
                    short_video1: ""
                }
            }
            dispatch({ type: 'setAdcreative', params: { ...state, adcreative: { ...adcreative311 as Adcreative, adcreative_template_id: value, adcreative_elements: { ...newAdEle } } } })
        } else if (['1707', '1708'].includes(value)) {
            let newAdEle = JSON.parse(JSON.stringify(adcreative1707?.adcreative_elements)) || { title: '', description: '', image_list: [""] }
            if(['1707'].includes(value)) {
                delete newAdEle?.video
                newAdEle.image_list = [""]
            } else {
                delete newAdEle?.image_list
                newAdEle.video = ""
            }
            dispatch({ type: 'setAdcreative', params: { ...state, adcreative: { ...adcreative1707 as Adcreative, adcreative_template_id: value, adcreative_elements: { ...newAdEle } } } })
        } else if (['928'].includes(value)) {
            dispatch({ type: 'setAdcreative', params: { ...state, adcreative: { ...adcreative928 as Adcreative } } })
        } else if (['929'].includes(value)) {
            dispatch({ type: 'setAdcreative', params: { ...state, adcreative: { ...adcreative929 as Adcreative } } })
        }
    }

    // 设置落地页
    const setPageData = (value: any) => {
        dispatch({ type: 'setPageData', params: { ...state, pageData: value } })
    }

    // 重置落地页相关
    const resetPage = () => {
        setPageData([])
        dispatch({type: 'setMaterial', params: { ...state, material: { page_name: "" } }})
        dispatch({ type: 'setReleases', params: { ...state, releases: [] } })
        dispatch({ type: 'setRelease', params: { ...state, release: [] } })
        dispatch({ type: 'setLaunchAcc', params: { ...state, launchAcc: [] } })
    }

    // 保存在本地
    const severBd = () => {
        let newState = JSON.parse(JSON.stringify(state))
        delete newState['releases']
        let obj = {
            ...newState
        }
        localStorage.setItem('newBdPlan', JSON.stringify(obj))
        message.success('保存本地成功！')
    }

    // 进入设置成本地数据
    const setBd = () => {
        let plan = localStorage.getItem('newBdPlan')
        if (plan) {
            let obj = JSON.parse(plan)
            dispatch({type: 'setData', params: { ...obj }})
        }
    }

    // 清空本地数据
    const delBdPlan = () => {
        localStorage.setItem('newBdPlan', '')
        dispatch({type: 'init', params: { ...state }})
        message.success('本地保存已清空！')
    }

    // api
    const addPlan = useAjax((props: adsPlan) => addPlanApi(props), { formatResult: true })
    const getAdsPlan = useAjax((props: adsPlanList) => getAdsPlanApi(props), { formatResult: true })
    const delBatch = useAjax((props: { taskIds: string }) => delBatchAjax(props), { formatResult: true, msgNmae: '删除' })
    const delLogBatch = useAjax((props: { logIds: string }) => delLogBatchAjax(props), { formatResult: true, msgNmae: '删除' })
    const getAdsPlanLog = useAjax((props: adsPlanLogList) => getAdsPlanLogApi(props), { formatResult: true })
    const setCopyPlan = useAjax((props: CopyPlan) => setCopyPlanApi(props))

    return {
        state,
        dispatch,
        setAdgroup,
        setTargeting,
        setAgeHandle,
        setTargeting_wab,
        setAdcreative,
        setAdcreativeType,
        setPageData,
        resetPage,
        severBd,
        setBd,
        delBdPlan,
        addPlan,
        getAdsPlan,
        delBatch,
        getAdsPlanLog,
        delLogBatch,
        setCopyPlan
    }
}