import SelectPage from "@/pages/launchSystem/launchManage/components/SelectPageNew";
import { getChannelName } from "@/utils/utils";
import { Checkbox, Divider, Radio, Select, Space, Switch } from "antd";
import { CheckboxChangeEvent } from "antd/lib/checkbox";
import { CheckboxValueType } from "antd/lib/checkbox/Group";
import React, { useCallback, useEffect, useState } from "react";
import { useModel } from "umi";
import { BcForm } from "../AdBasicConfig";
import { MOMENTSIMAGE, MOMENTSVIDEO, originalitySize, wechatPositionList } from "../adList";
import style from './index.less'

function BasicSettings() {

    /** =====变量Start===== */
    const { state, setAdgroup, setAdcreativeType, dispatch, setPageData, resetPage, setAdcreative } = useModel('useLaunch.useNewCreateAd')
    const { adgroup, adcreative, pageData, launchAcc, releases, release } = state
    const { site_set, scene_spec, bid_mode } = adgroup
    const { adcreative_template_id, page_spec } = adcreative
    const [wpShow, setWpShow] = useState<boolean>(false)  // 是否开启广告位定向
    const [wpList, setWpList] = useState<{ label: string, value: number, bid_mode: string[], disabled?: boolean }[]>(wechatPositionList)
    const [pageShow, setPageShow] = useState<boolean>(false) // 选择落地弹窗
    const [checkAll, setCheckAll] = React.useState(false); // 投放号全选按钮控制 全部状态
    const [smType, setSmType] = useState<'IMAGE' | 'VIDEO'>('IMAGE')   // 素材类型
    const { getSharePageDetail } = useModel('useLaunch.useAdAuthorize')
    /** =====变量End===== */

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

    // 判断广告位勾选
    useEffect(() => {
        // 处理广告位是否可选
        if (scene_spec && scene_spec?.wechat_position?.length > 0) {
            let wpdata = scene_spec?.wechat_position
            if (wpdata?.indexOf(1024790) !== -1) {
                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) {
                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) {
                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) {
                setWpList(() => wpList.map((item: { label: string, value: number, bid_mode: string[], disabled?: boolean }) => {
                    return { ...item, disabled: false }
                }))
            }
        } else {
            setWpList(() => wpList.map((item: any) => ({ ...item, disabled: false })))
        }
    }, [scene_spec?.wechat_position])

    useEffect(() => {
        if (pageData && pageData?.length > 0) {
            getSharePageDetail.run(pageData[0]?.id).then((res: { data: { createRecords: any } }) => {
                let newReleases: { label: string, value: string, id: number, wechat_info: any, serverId: number }[] = []
                res?.data?.createRecords?.forEach((item: { createStatus: number, channelAccountMpInfo: { channel: any, id: number, uname: string } }) => {
                    if (item?.createStatus === 100) {
                        newReleases.push(
                            {
                                label: getChannelName(item?.channelAccountMpInfo?.channel?.accountName) + '-' + item?.channelAccountMpInfo?.uname,
                                value: item?.channelAccountMpInfo?.id.toString(),
                                id: item?.channelAccountMpInfo?.id,
                                serverId: item?.channelAccountMpInfo?.channel?.id,
                                wechat_info: {
                                    service_name: item?.channelAccountMpInfo?.channel?.accountName,
                                    wechat_name: item?.channelAccountMpInfo?.uname
                                }
                            }
                        )
                    }
                })
                let a = newReleases.reduce((prev: any, cur) => {
                    let rele = prev?.find((item: any) => item?.id === cur?.id)
                    if (!rele) {
                        prev.push(cur)
                    }
                    return prev
                }, [])
                dispatch({ type: 'setReleases', params: { ...state, releases: a } })
            })
            // 判断是否是轮播图 图片是800*450
            if (adcreative_template_id === '1707') {
                let topType = pageData[0]?.topCanvasType
                if (topType === 101) {
                    setAdcreative('page_spec', { ...page_spec, override_canvas_head_option: 'OPTION_KEEP_DIFFERENT' })
                } else if (topType === 41) {
                    let pageContextList = JSON.parse(pageData[0]?.pageContextList[0]?.pageContextList)
                    let topContent = pageContextList[0]
                    let initWidth = topContent?.initWidth
                    let initHeight = topContent?.initHeight
                    if (initWidth !== 800 || initHeight !== 450) {
                        setAdcreative('page_spec', { ...page_spec, override_canvas_head_option: 'OPTION_KEEP_DIFFERENT' })
                    }
                }
            } else if (adcreative_template_id === '1708') {
                let topType = pageData[0]?.topCanvasType
                if (topType === 142 || topType === 61) {
                    let initWidth = JSON.parse(pageData[0]?.pageContextList[0]?.pageContextList)[0]?.initWidth
                    let initHeight = JSON.parse(pageData[0]?.pageContextList[0]?.pageContextList)[0]?.initHeight
                    if (initWidth != 1280 || initHeight != 720) {
                        setAdcreative('page_spec', { ...page_spec, override_canvas_head_option: 'OPTION_KEEP_DIFFERENT' })
                    }
                }
            }
        }
        if (MOMENTSVIDEO.includes(adcreative_template_id)) {
            setSmType('VIDEO')
        }
        if (MOMENTSIMAGE.includes(adcreative_template_id)) {
            setSmType('IMAGE')
        }
    }, [pageData, adcreative_template_id])

    // 处理投放号勾选
    useEffect(() => {
        if (releases?.length === 0) {
            setCheckAll(false);
        } else {
            if (release?.length >= releases?.length) {
                setCheckAll(true);
            } else {
                setCheckAll(false);
            }
        }
    }, [release, releases])

    // 选择投放号
    const onSetRelease = useCallback((e: any) => {
        dispatch({ type: 'setRelease', params: { ...state, release: e } })
        let newlaunchAcc: any = []
        releases?.forEach((item: any) => {
            if (e?.indexOf(item?.value) !== -1) {
                newlaunchAcc.push({
                    ...item,
                    package: []
                })
            }
        })
        dispatch({ type: 'setLaunchAcc', params: { ...state, launchAcc: newlaunchAcc } })
    }, [release, launchAcc, releases])

    const onCheckAllChange = (e: CheckboxChangeEvent) => {
        if (releases?.length > 0) {
            let data = e.target.checked ? releases?.map((item: any) => item?.value) : []
            dispatch({ type: 'setRelease', params: { ...state, release: data } })
            setCheckAll(e.target.checked);
            let newlaunchAcc: any = []
            releases?.forEach((item: any) => {
                if (data?.indexOf(item?.value) !== -1) {
                    newlaunchAcc.push({
                        ...item,
                        package: []
                    })
                }
            })
            dispatch({ type: 'setLaunchAcc', params: { ...state, launchAcc: newlaunchAcc } })
        }
    }

    return <div>
        <div className={style.headerform}>
            <div className={style.topTitle}>基本配置</div>
            <BcForm name="推广目标" bottom={5}>
                <span>公众号推广</span>
            </BcForm>
            <BcForm name="流量位" bottom={5}>
                <Radio.Group value={site_set[0]} size="small" 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="广告位定向" bottom={5}>
                    <Switch checked={wpShow} size="small" onChange={(e) => {
                        setWpShow(e)
                        if (!e) {
                            setAdgroup('scene_spec', { wechat_position: [] })
                        }
                    }} />
                </BcForm>
                {wpShow && <BcForm name="广告位" flex='flex-start' bottom={5}>
                    <Checkbox.Group
                        options={wpList}
                        style={{ marginTop: 5 }}
                        value={scene_spec?.wechat_position}
                        onChange={(checkedValue: CheckboxValueType[]) => {
                            setAdgroup('scene_spec', { wechat_position: checkedValue })
                        }}
                    />
                </BcForm>}
            </>}
            <BcForm name="素材类型" bottom={5}>
                {site_set[0] === "SITE_SET_MOMENTS" ? <Radio.Group size="small" className={style.radio} value={smType} onChange={(e) => {
                    setSmType(e.target.value)
                    if (e.target.value === 'IMAGE') {
                        setAdcreativeType("311");
                    } else if (e.target.value === 'VIDEO') {
                        setAdcreativeType("618");
                    }
                    resetPage()
                }}>
                    <Radio.Button value="IMAGE">图片</Radio.Button>
                    <Radio.Button value="VIDEO">视频</Radio.Button>
                </Radio.Group> : <span>{['929', '618', '1465', '1480', '1064', '1708', '721'].includes(adcreative_template_id) ? '视频' : '图片'}</span>}
            </BcForm>
            <BcForm name="创意样式" bottom={5}>
                <Radio.Group className={style.radio} size="small" value={adcreative_template_id} onChange={(e) => { setAdcreativeType(e.target.value); resetPage() }}>
                    {site_set[0] === 'SITE_SET_MOMENTS' ? smType === 'IMAGE' ? <>
                        <Radio.Button value="311">常规大图</Radio.Button>
                        <Radio.Button value="1707">卡片横板大图</Radio.Button>
                        <Radio.Button value="641">常规3图</Radio.Button>
                        <Radio.Button value="642">常规4图</Radio.Button>
                        <Radio.Button value="643">常规6图</Radio.Button>
                    </> : <>
                        <Radio.Button value="618">常规视频4:3</Radio.Button>
                        <Radio.Button value="1465">常规视频16:9</Radio.Button>
                        <Radio.Button value="1480">竖版视频750:1334</Radio.Button>
                        <Radio.Button value="1708">卡片横版视频</Radio.Button>
                    </> : <>
                        {scene_spec?.wechat_position?.length === 0 ? <>
                            {adcreative_template_id === "928" ?
                                <Radio.Button value="928">大图式卡片</Radio.Button> : adcreative_template_id === "929" ?
                                    <Radio.Button value="929">视频式卡片</Radio.Button> : null}
                        </> : <>
                            {bid_mode === 'BID_MODE_OCPM' ? <Radio.Button value="929">视频式卡片</Radio.Button> : <Radio.Button value="928">大图式卡片</Radio.Button>}
                        </>}
                    </>}
                </Radio.Group>
            </BcForm>
            <BcForm name="素材规格" bottom={5}>
                <span>{originalitySize[adcreative_template_id]} 像素</span>
            </BcForm>
            <BcForm name="原生推广页" bottom={5}>
                <Space>
                    {pageData && pageData?.length > 0 && <div style={{ backgroundColor: 'rgb(237, 237, 237)', padding: '4px 8px', borderRadius: 6, fontSize: 12 }}>{pageData[0]?.name}</div>}
                    <a onClick={() => { setPageShow(true) }}>{pageData && pageData?.length > 0 ? '修改' : '选择'}原生页</a>
                </Space>
            </BcForm>
            <BcForm name="投放号" bottom={5}>
                <Select
                    mode="tags"
                    size="small"
                    placeholder="选择投放号"
                    onChange={onSetRelease}
                    style={{ minWidth: '180px', maxWidth: 400 }}
                    maxTagCount={1}
                    allowClear
                    value={release}
                    dropdownRender={menu => (
                        <div>
                            <div style={{ marginLeft: 10 }}><Checkbox indeterminate={!!release.length && release.length < releases.length} onChange={onCheckAllChange} checked={checkAll}>全选</Checkbox></div>
                            <Divider style={{ margin: '4px 0' }} />
                            {menu}
                        </div>
                    )}
                >
                    {releases?.map((item: { label: string, value: string, id: number }) => <Select.Option key={item?.id} value={item?.value}>{item?.label}</Select.Option>)}
                </Select>
            </BcForm>
        </div>
        {/* 选择落地页 */}
        {pageShow && <SelectPage
            type={adcreative_template_id}
            show={pageShow}
            onClose={() => { setPageShow(false) }}
            onChange={(data) => {
                setPageShow(false);
                if (pageData?.length === 0) {
                    setPageData(data)
                } else if (pageData[0]?.id === data[0]?.id) {

                } else {
                    setPageData(data)
                    dispatch({ type: 'setReleases', params: { ...state, releases: [] } })
                    dispatch({ type: 'setRelease', params: { ...state, release: [] } })
                    dispatch({ type: 'setLaunchAcc', params: { ...state, launchAcc: [] } })
                    // setBasicData('tableDate', [])
                }
            }}
            pageData={pageData}
        ></SelectPage>}
    </div>
}

export default React.memo(BasicSettings)