import Tables from "@/components/Tables";
import { Button, Card, Col, message, Row, Space, Modal, Input, Image } from "antd";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import style from './index.less'
import columns from './tableConfig'
import AdBasicConfig from './components/AdBasicConfig'
import SelectPackage from './components/SelectPackage'
import SelectGoods from './components/SelectGoods'
import AdOriginality from './components/AdOriginality'
import { CloseOutlined, SearchOutlined } from "@ant-design/icons";
import { useModel } from "umi";
import moment from "moment";
import AdLogin from '@/pages/launchSystem/launchManage/components/adLogin'
import dic from "./components/Dic"
import BasicSettings from './components/BasicSettings'
import { originalitySize } from "./components/adList";
import { getChannelName, txtLength } from "@/utils/utils";

function CreatePlan(props: { data: { type: string, item: any } | undefined, }) {
    let { data } = props

    /** =====变量Start===== */
    // 新
    const { state, dispatch, severBd, setBd, delBdPlan, addPlan } = useModel('useLaunch.useNewCreateAd')
    const { campaign, pageData, launchAcc, adgroup, targeting, adcreative, material } = state
    const { site_set, begin_date, end_date, bid_mode, bid_strategy, optimization_goal, daily_budget, bid_amount, adgroup_name, deep_conversion_spec } = adgroup
    const { age, gender } = targeting
    const { adcreative_template_id, link_name_type, adcreative_elements, page_spec, adcreative_name } = adcreative
    const { info_bar_spec } = adcreative_elements
    // 新
    const [basicConfigVisible, setBasicConfigVisible] = useState<boolean>(false)  // 广告基本信息弹窗
    const [adOriginalityVisible, setAdOriginalityVisible] = useState<boolean>(false)  // 创意基本信息弹窗
    const [selectPackageVisible, setSelectPackageVisible] = useState<boolean>(false)  // 定向包弹窗
    const [selectGoodsVisible, setSelectGoodsVisible] = useState<boolean>(false)  // 商品弹窗
    const [tableDate, setTableDate] = useState<any[]>([])//table预览信息
    const [tableSelect, setTableSelect] = useState<any[]>([])//选择
    const [authData, setAuthData] = useState<{ base64: string, code: string }>({ base64: '', code: '' })
    const [taskNameShow, setTaskNameShow] = useState<boolean>(false) // 任务名称弹窗
    const [taskName, setTaskName] = useState<string>('')
    /** =====变量End===== */

    useEffect(() => {
        if (data) { //填列表跳转数据
            console.log('data---->', data)
            let { planId, mpAccountInfo, packageInfo, goods, goodsInfo, planInfo } = data?.item
            let { campaign, adgroup, adcreative, material, sharePageInfo } = planInfo
            let newAdgroup = JSON.parse(adgroup)
            let newlaunchAcc: any = []
            if (Object.keys(mpAccountInfo).length > 0) {
                let newGoods: any = {}
                if (goods) {
                    let goodsParams = JSON.parse(goods)
                    newGoods = {
                        key: goodsParams.material_source_id,
                        data: [{ ...goodsInfo }],
                        id: mpAccountInfo?.id
                    }
                }
                newlaunchAcc.push({ // 定向包
                    id: mpAccountInfo?.id,
                    label: getChannelName(mpAccountInfo?.channel?.accountName) + '-' + mpAccountInfo?.uname,
                    package: packageInfo?.length > 0 ? [...packageInfo] : [],
                    goods: goods ? newGoods : {},
                    value: mpAccountInfo?.id?.toString(),
                    serverId: mpAccountInfo?.channel?.id,
                    wechat_info: {
                        wechat_name: mpAccountInfo?.uname,
                        service_name: mpAccountInfo?.channel?.accountName
                    }
                })
            }
            let oldCampaign = JSON.parse(campaign)
            let oldAdcreative = JSON.parse(adcreative)
            let { campaign_name } = oldCampaign
            let { adcreative_name } = oldAdcreative
            let name = campaign_name.split('-')
            let adName = adcreative_name.split('-')
            dispatch({
                type: 'setData', params: {
                    campaign: { ...oldCampaign, campaign_name: name.length === 2 ? name[0] : '' },
                    adgroup: newAdgroup,
                    targeting: JSON.parse(newAdgroup.targeting),
                    adcreative: { ...oldAdcreative, adcreative_name: adName.length === 3 ? name[1] : '' },
                    material: JSON.parse(material),
                    pageData: [sharePageInfo],
                    releases: [],
                    launchAcc: newlaunchAcc,
                    release: [mpAccountInfo?.id?.toString()]
                }
            })
        } else {
            setBd() // 设置本地
        }
        return () => {
            dispatch({ type: 'init', params: state })
        }
    }, [])

    /**计算已选定向包个数 */
    const accNum = useMemo(() => {
        let num = launchAcc?.length
        return num
    }, [launchAcc])

    /**定向包回调 */
    const selectPackageCallback = useCallback((value: any) => {
        dispatch({ type: 'setLaunchAcc', params: { ...state, launchAcc: value } })
    }, [launchAcc])

    /**删除定向包内容 */
    const selectPackageDel = useCallback((title: string, delId: number) => {
        let newArr = launchAcc?.map((item: { label: string, package: { id: number }[] }) => {
            if (item.label === title) {
                let newPageage = item.package.filter((pack: { id: number }) => delId !== pack.id)
                item.package = newPageage
            }
            return item
        })
        dispatch({ type: 'setLaunchAcc', params: { ...state, launchAcc: newArr } })
    }, [launchAcc])

    /** 删除商品内容 */
    const goodsDel = useCallback((index: number) => {
        let newArr = JSON.parse(JSON.stringify(launchAcc))
        delete newArr[index].goods
        dispatch({ type: 'setLaunchAcc', params: { ...state, launchAcc: newArr } })
    }, [launchAcc])

    /**预览 */
    const preview = useCallback(() => {
        let newAdcreative = JSON.parse(JSON.stringify(adcreative))
        if (launchAcc.length === 0) {
            message.error('请选择公众号')
            return
        }
        if (pageData?.length === 0) {
            message.error('请选择原生推广页')
            return
        }
        if (adcreative_template_id === "311" || adcreative_template_id === '641' || adcreative_template_id === '642' || adcreative_template_id === '643') {
            if (txtLength(adcreative_elements.title) === 0 || txtLength(adcreative_elements.title) > 40) {
                message.error('请输入外层文案')
                return
            }
        } else if (adcreative_template_id === '1707') {
            if (txtLength(adcreative_elements.title) === 0 || txtLength(adcreative_elements.title) > 10) {
                message.error('外层文案标题输入有误，请修改')
                return
            }
            if (txtLength(adcreative_elements.description) === 0 || txtLength(adcreative_elements.description) > 30) {
                message.error('外层文案输入有误，请修改')
                return
            }
            if (page_spec?.override_canvas_head_option === "OPTION_KEEP_DIFFERENT" && !material.url) {
                message.error('请上传外层素材')
                return
            }
        } else if (adcreative_template_id === '928' || adcreative_template_id === '929') {
            if (!material.url) {
                message.error('请上传外部素材')
                return
            }
            if (txtLength(adcreative_elements.title) === 0 || txtLength(adcreative_elements.title) > 12) {
                message.error('卡片文案输入有误，请修改')
                return
            }
            if (txtLength(adcreative_elements?.description) === 0 || txtLength(adcreative_elements?.description) > 16) {
                message.error('首行文案输入有误，请修改')
                return
            }
            if (txtLength(adcreative_elements?.caption) === 0 || txtLength(adcreative_elements?.caption) > 16) {
                message.error('次行文案输入有误，请修改')
                return
            }
            if (adcreative_template_id === '928' && info_bar_spec?.info_bar_type === 'INFO_BAR_TYPE_TITLE'){
                if (!info_bar_spec?.info_bar_description) {
                    message.error('请输入信息栏文案')
                    return 
                }
            }

            let adcreativeElements = newAdcreative.adcreative_elements
            if (Object.keys(adcreativeElements).includes('left_bottom_txt') && !adcreativeElements?.left_bottom_txt) {
                delete adcreativeElements.left_bottom_txt
            }
        }
        
        let arr = launchAcc?.map((item: any, eq: number) => {
            return {
                id: eq,
                service_name: item?.wechat_info?.service_name, //广告主账户
                wechat_name: item?.wechat_info?.wechat_name, //公众号
                tg_target: '公众号推广', // 推广目标
                launch_acc: { ...item }, // 人群包信息
                page_spec: pageData[0],//推广页
                human_info_package: { key: item.key, name: item?.package?.map((items: { name: any; }) => items?.name) },//定向包
                human_info_goods: { ...item?.goods, id: item?.id }, // 商品
                campaign: { ...campaign, campaign_name: `${campaign.campaign_name ? campaign.campaign_name + '-' : ''}${moment(new Date()).format('YYYYMMDDHHmmss')}` },
                adgroup: { ...adgroup, adgroup_name: `${campaign.campaign_name ? campaign.campaign_name + '-' : ''}${moment(new Date()).format('YYYYMMDDHHmmss')}-广告` },
                targeting: { ...targeting },
                adcreative: { ...newAdcreative, adcreative_name: `${pageData[0]?.novelName}-${moment(new Date()).format('YYYYMMDDHHmmss')}${adcreative.adcreative_name ? '-' + adcreative.adcreative_name : ''}` },
                material: { ...material }
            }
        })
        setTableDate(arr)
    }, [launchAcc, pageData, adcreative_template_id, adcreative_elements, adgroup, targeting, adcreative, material, page_spec])
    /**批量提交 */
    const submit = useCallback(() => {
        if (!taskName) {
            message.error('请输入任务名称！')
            return
        }
        let channelAdqAccount: any = {}
        let channelMpAccount: any = {}
        let channelMpGoods: any = {}
        tableSelect?.forEach((item: any) => {
            let ids = item?.launch_acc?.package?.map((id: any) => id?.id)
            if (Object.keys(channelMpAccount)?.indexOf(item?.launch_acc?.id) !== -1) {
                channelMpAccount[item?.launch_acc?.id] = [...channelMpAccount[item?.launch_acc?.id], ...ids]
            } else {
                channelMpAccount[item?.launch_acc?.id] = [...ids]
            }
            let human_info_goods = item.human_info_goods
            if (human_info_goods && human_info_goods?.key && human_info_goods?.data) {
                let categories = human_info_goods?.data[0]?.categories ? JSON.parse(human_info_goods?.data[0]?.categories) : []
                if (categories?.length > 0) {
                    categories = categories[0]
                    channelMpGoods[human_info_goods.id] = JSON.stringify({
                        material_source_id: human_info_goods.key,
                        dynamic_product_ad_category: human_info_goods.key,
                        dynamic_recommend_type: '[{"parent_method_id":2,"method_id":2001}]',
                        dynamic_ad_type: 11,
                        dynamic_ad_product_id: human_info_goods?.data[0]?.productOuterId,
                        dynamic_category_id: categories[categories.length - 1]?.id
                    })
                }
            }
        })
        let { campaign, adcreative, adgroup, targeting, material } = tableSelect[0]
        addPlan.run({
            channelAdqAccount,
            channelMpAccount,
            channelMpGoods,
            taskName: taskName ? taskName + '_' + (parseInt((Date.now() / 100).toString())) : moment().unix(),
            planDto: {
                content: adcreative?.adcreative_elements?.title || '',
                posType: adcreative.adcreative_template_id,
                planName: campaign.campaign_name,
                putLocation: adgroup.site_set[0],
                putTarget: campaign.promoted_object_type,
                pageId: pageData[0]?.id,
                campaign: JSON.stringify(campaign),
                adgroup: JSON.stringify({ ...adgroup, targeting: JSON.stringify(targeting) }),
                adcreative: JSON.stringify(adcreative),
                material: JSON.stringify({ ...material, page_name: pageData[0]?.name })
            }
        }).then((res: any) => {
            setTaskNameShow(false)
            if (res?.code === 200) {
                message.success('创建成功')
                window.location.href = '/#/launchSystem/launchManageNew/taskList'
            } else if (res?.code === 1003 && res?.data?.base64) {
                setAuthData(res?.data)
            }
        })
    }, [taskName, tableSelect, pageData])
    /** 输入任务名称 */

    console.log(state)

    return <>
        {/* 授权登录 */}
        <AdLogin onClose={() => { setAuthData({ base64: '', code: '' }) }} value={authData} onChange={() => { setAuthData({ base64: '', code: '' }); message.success('再次点击按钮提交') }} />
        {/* =============广告基本信息弹窗=========== */}
        {basicConfigVisible && <AdBasicConfig visible={basicConfigVisible} hideModel={() => { setBasicConfigVisible(false) }}></AdBasicConfig>}
        {/* =============定向包弹窗=========== */}
        {selectPackageVisible && <SelectPackage launchAcc={launchAcc} visible={selectPackageVisible} hideModel={() => { setSelectPackageVisible(false) }} callback={selectPackageCallback}></SelectPackage>}
        {/* =============商品弹窗=========== */}
        {selectGoodsVisible && <SelectGoods launchAcc={launchAcc} visible={selectGoodsVisible} hideModel={() => { setSelectGoodsVisible(false) }} callback={selectPackageCallback} />}
        {/* =============创意基本信息弹窗=========== */}
        {adOriginalityVisible && <AdOriginality visible={adOriginalityVisible} hideModel={() => { setAdOriginalityVisible(false) }} pageData={pageData}></AdOriginality>}

        {/* 任务名称 */}
        <Modal title="输入任务名称" confirmLoading={addPlan?.loading} visible={taskNameShow} onOk={submit} onCancel={() => { setTaskNameShow(false) }}>
            <Space>
                <Input value={taskName} style={{ width: 370 }} onChange={(e) => { setTaskName(e.target.value) }} placeholder="请输入任务名称" />
                <div>+ 当前时间</div>
            </Space>
        </Modal>

        <Space direction='vertical' style={{ width: '100%' }}>
            <Card title={<div className={style.cardTitle}>配置区</div>} className={style.createPlan} bordered={false} hoverable>
                <div className={style.cardBody}>
                    {/* =============基本配置=========== */}
                    <BasicSettings />
                    <Row className={style.content}>
                        {/* ===========广告========== */}
                        <Col span={18} className={style.conLeft}>
                            <Row className={`${style.conTitle} ${style.conRightBorder}`}><Col span={24}>广告</Col></Row>
                            <Row className={style.items}>
                                {/* =============广告基本信息=========== */}
                                <Col span={8} className={style.conRightBorder}>
                                    <div className={style.top}>广告基本信息</div>
                                    <div className={style.center}>
                                        <div>推广目标：{'公众号推广'}</div>
                                        <div>流量位：{dic.siteSet[site_set[0]]}</div>
                                        <div>投放时间：{begin_date}~{end_date}</div>
                                        <div>投放时段：{'全天投放'}</div>
                                        <div>计划预算：不限</div>
                                        <div>出价方式：{dic.bidModes[bid_mode] || '(空)'}</div>
                                        <div>投放模式：{bid_strategy && dic.bidStrategy[bid_strategy] || '(空)'}</div>
                                        <div>优化目标：{optimization_goal && dic.optimizationGoal[optimization_goal] || '(空)'}</div>
                                        <div>广告预算：{daily_budget && Number(daily_budget) / 100 || 0} </div>
                                        <div>出价：{bid_amount && Number(bid_amount) / 100 || 0}</div>
                                        <div>地域：常住地</div>
                                        <div>地域选择：全选</div>
                                        <div>年龄：{age ? `${age[0].min}岁~${age[0].max}岁` : '(空)'}</div>
                                        <div>性别：{gender ? gender[0] : '不限'}</div>
                                        <div style={{ marginTop: 10 }}>计划名称：{adgroup_name ? `${adgroup_name} + (时间)` : '(时间)'}</div>
                                    </div>
                                    <div className={style.bottom}><span onClick={() => { setBasicConfigVisible(true) }}>编辑</span></div>
                                </Col>
                                {/* =============定向包=========== */}
                                <Col span={8} className={style.conRightBorder}>
                                    <div className={style.top}>
                                        定向包<span>已选：{accNum}</span>
                                    </div>
                                    <div className={style.center}>
                                        {
                                            launchAcc.map((item: { label: string, package: { name: string, id: number }[] }, index: number) => {
                                                return <div className={style.acc} key={index}>
                                                    <div className={style.accName}>{item.label}</div>
                                                    {
                                                        item?.package?.map((pack: { name: string, id: number }) => {
                                                            return <div className={style.accCon} key={pack.id}>{pack.name}<CloseOutlined className={style.close} onClick={() => {
                                                                selectPackageDel(item.label, pack.id)
                                                            }} /></div>
                                                        })
                                                    }
                                                </div>
                                            })
                                        }
                                    </div>
                                    <div className={style.bottom}><span onClick={() => { if (launchAcc?.length > 0) { setSelectPackageVisible(true) } else { message.error('请选择投放号') } }}>添加</span></div>
                                </Col>
                                {/* =============商品=========== */}
                                <Col span={8} className={style.conRightBorder}>
                                    <div className={style.top}>
                                        商品<span>已选：{accNum}</span>
                                    </div>
                                    <div className={style.center}>
                                        {
                                            launchAcc.map((item: { label: string, goods: { data: any[], key: number } }, index: number) => {
                                                return <div className={style.acc} key={index}>
                                                    <div className={style.accName}>{item.label}</div>
                                                    {
                                                        item?.goods?.data?.map((pack: { productName: string, author: string, id: number }, index: number) => {
                                                            return <div className={style.accCon} key={pack.id}>{pack.productName + '-' + pack.author}<CloseOutlined className={style.close} onClick={() => {
                                                                goodsDel(index)
                                                            }} /></div>
                                                        })
                                                    }
                                                </div>
                                            })
                                        }
                                    </div>
                                    <div className={style.bottom}><span onClick={() => { if (launchAcc?.length > 0) { setSelectGoodsVisible(true) } else { message.error('请选择投放号') } }}>添加</span></div>
                                </Col>
                            </Row>
                        </Col>
                        {/* =============广告创意=========== */}
                        <Col span={6} className={style.conRight}>
                            <Row className={style.conTitle}><Col span={24}>广告创意 <span style={{ fontSize: 12, color: '#898989' }}>({dic.adcreativeTemplate[adcreative_template_id]})</span></Col></Row>
                            <Row className={style.items}>
                                <Col span={24}>
                                    <div className={style.top}>创意基本信息</div>
                                    <div className={style.center}>
                                        <div>创意样式：{dic.adcreativeTemplate[adcreative_template_id]}</div>
                                        <div>素材类型：{['929', '618', '1465', '1480', '1708'].includes(adcreative_template_id) ? '视频' : '图片'}</div>
                                        <div>素材规格：{originalitySize[adcreative_template_id]} 像素</div>

                                        {['311', '641', '642', '643', '618', '1465', '1480'].includes(adcreative_template_id) ? <>
                                            {/* 常规大图 */}
                                            <div>点击跳转：原生推广页</div>
                                            <div>文字链：{link_name_type ? dic.linkNameType[link_name_type] : '(空)'}</div>
                                            <div>外层文案：{adcreative_elements?.title || '(空)'}</div>
                                        </> : adcreative_template_id === '1707' || adcreative_template_id === '1708' ? <>
                                            <div>外层素材来源：{page_spec?.override_canvas_head_option ? dic.overrideCanvasHeadOption[page_spec?.override_canvas_head_option] : '(空)'}</div>
                                            {
                                                page_spec?.override_canvas_head_option === "OPTION_KEEP_DIFFERENT" && <div>
                                                    外层素材：{material?.url && adcreative_template_id === '1707' ? <Image width={100} src={material?.url} style={{ borderRadius: 8, overflow: 'hidden' }} /> : <video width={100} src={material?.url} style={{ borderRadius: 8, overflow: 'hidden' }} />}
                                                </div>
                                            }
                                            <div>外层文案标题：{adcreative_elements?.title || '(空)'}</div>
                                            <div>外层文案：{adcreative_elements?.description || '(空)'}</div>
                                        </> : adcreative_template_id === '928' || adcreative_template_id === '929' ? <>
                                            <div>外层素材：{adcreative_template_id === '929' ? <>
                                                {material?.url && <video width={100} src={material?.url} style={{ borderRadius: 8, overflow: 'hidden' }} />}
                                            </> : <>
                                                {material?.url && <Image width={100} src={material?.url} style={{ borderRadius: 8, overflow: 'hidden' }} />}
                                            </>}
                                            </div>
                                            <div>首行文案：{adcreative_elements.description || '(空)'}</div>
                                            <div>次行文案：{adcreative_elements.caption || '(空)'}</div>
                                            <div>第三行文案：{adcreative_elements.left_bottom_txt || '(空)'}</div>
                                        </> : <></>}


                                        <div>原生推广页：{pageData.length > 0 ? pageData[0]?.name : '空'}</div>
                                        {pageData.length > 0 && <div>
                                            原生推广页顶部素材预览：
                                            <div>{pageData[0]?.topCanvasType === 101 ? // 顶部轮播图
                                                <Space>
                                                    {JSON.parse(pageData[0]?.pageContextList[0]?.pageContextList)[0]?.componentGroupList?.componentGroup?.map((item: any, index: number) => {
                                                        return <Image width={80} src={item?.componentItem?.pureImageUrl} style={{ borderRadius: 8 }} key={index} />
                                                    })}
                                                </Space>
                                                :
                                                pageData[0]?.topCanvasType === 41 ? // 顶部图片
                                                    <Image width={80} src={pageData[0]?.thumbUrl} style={{ borderRadius: 8, overflow: 'hidden' }} />
                                                    :
                                                    <span>无此类型预览，请联系管理员</span>}</div>
                                        </div>}

                                        <div style={{ marginTop: 10 }}>创意名称：{`(落地页名称)-(当前时间)`}{adcreative_name || ''}</div>
                                    </div>
                                    <div className={style.bottom}><span onClick={() => { if (pageData && pageData?.length > 0) { setAdOriginalityVisible(true) } else { message.error('请先选择原生页') } }}>编辑</span></div>
                                </Col>
                            </Row>
                        </Col>
                    </Row>
                    {/* =============广告底部按钮=========== */}
                    <Space className={style.bts}>
                        <Button type='primary' onClick={severBd}>暂存到本地</Button>
                        <Button type='primary' onClick={preview}><SearchOutlined /> 批量预览广告</Button>
                        <Button onClick={delBdPlan}>清空本地配置</Button>
                    </Space>
                </div>
            </Card>

            {/* =============预览=========== */}
            {tableDate?.length > 0 && <Card
                title={<div className={style.cardTitle}>预览区</div>}
                className={style.createPlan}
                bordered={false}
                hoverable
                extra={
                    <Space>
                        <span>推广计划总数：{accNum}</span>
                        <span> 广告总数：{accNum}</span>
                        {tableSelect?.length > 0 && <span> 已选：<span style={{ color: '#1890FF' }}>{tableSelect?.length}</span> 条</span>}
                        {
                            data?.type !== '详情' && <Button type='primary' onClick={() => {
                                if (tableSelect.length === 0) {
                                    message.error('请选择要提交的计划！')
                                    return
                                };
                                setTaskNameShow(true)
                            }} loading={addPlan?.loading}>批量提交审核</Button>
                        }
                    </Space>
                }
            >
                <div className={style.cardBody}>
                    <div className={style.content} style={{ marginTop: 20 }}>
                        <Tables
                            columns={columns()}
                            dataSource={tableDate}
                            total={0}
                            size="small"
                            bordered
                            scroll={{ x: 1800 }}
                            rowSelection={{
                                selectedRowKeys: tableSelect?.map((item: any) => item?.id.toString()),
                                onChange: (selectedRowKeys: React.Key[], selectedRows: any) => {
                                    setTableSelect(selectedRows)
                                }
                            }}
                        />
                    </div>
                </div>
            </Card>}
        </Space>

    </>
}
export default CreatePlan