import Tables from "@/components/Tables"
import { useAjax } from "@/Hook/useAjax"
import { CreateAdProps } from "@/services/launchAdq/createAd"
import { BidModeEnum, BidStrategyEnum, OptimizationGoalEnum, PromotedObjectType, SiteSetEnum } from "@/services/launchAdq/enum"
import { getTagsList } from "@/services/launchAdq/global"
import { getSysAdgroupsInfo } from "@/services/launchAdq/localAd"
import { getsysTargetingInfo } from "@/services/launchAdq/targeting"
import { CloseOutlined, SearchOutlined } from "@ant-design/icons"
import { Button, Card, Col, Empty, Row, Select, Space, Spin, Tooltip, Image, message } from "antd"
import React, { useEffect, useState } from "react"
import { useModel } from "umi"
import AdModal from "../../components/adModal"
import DataSourceModal from "../../components/dataSourceModal"
import GoodsModal from "../../components/goodsModal"
import IdModal from "../../components/idModal"
import LookLanding from "../../components/lookLanding"
import SelectCloud from "../../components/selectCloud"
import TargetingModal from "../../components/targetingModal"
import TargetingTooltip from "../../components/targetingTooltip"
import { WxAutoButton } from "../../req"
import style from './index.less'
import Selector from "./selector"
import SubmitModal from "./submitModal"
import columns from "./tableConfig"

const CreateAd: React.FC = () => {

    /*************************/
    const { getAdAccount } = useModel('useLaunchAdq.useAdAuthorize')
    const [queryForm, setQueryForm] = useState<Partial<CreateAdProps>>({
        campaignName: '',  // 计划名称
        campaignType: 'CAMPAIGN_TYPE_NORMAL', // 计划类型 CAMPAIGN_TYPE_NORMAL CAMPAIGN_TYPE_SEARCH 
        promotedObjectType: 'PROMOTED_OBJECT_TYPE_WECHAT_OFFICIAL_ACCOUNT', // 推广目标类型
        speedMode: 'SPEED_MODE_STANDARD', // 投放速度模式
        sysAdgroupsId: undefined,  // 广告组内容
        sysTargetingId: undefined,  // 定向包 id
        adName: undefined,  // 广告名称
        configuredStatus: 'AD_STATUS_SUSPEND',  // 广告状态
        sysAdcreativeId: undefined, // 创意ID
        sysPageId: undefined, // 落地页Id
    })
    const [accountCreateLogs, setAccountCreateLogs] = useState<{ adAccountId: number, id: number, userActionSetsList?: number, productList?: any, conversionList?: any }[]>([])  // 账户

    const [adVisible, setAdVisible] = useState<boolean>(false) // 选择广告弹窗控制
    const [dxVisible, setDxVisible] = useState<boolean>(false) // 选择定向弹窗控制
    const [goodsVisible, setGoodsVisible] = useState<boolean>(false) // 选择商品弹窗控制
    const [sourceVisible, setSourceVisible] = useState<boolean>(false) // 选择数据源弹窗控制
    const [idVisible, setIdVisible] = useState<boolean>(false) // 选择转化ID弹窗控制
    const [selectImgVisible, setSelectImgVisible] = useState<boolean>(false) // 选择转化ID弹窗控制
    const [lookVisible, setLookVisible] = useState<boolean>(false) // 选择转化ID弹窗控制
    const [subVisible, setSubVisible] = useState<boolean>(false) // 选择设置名称弹窗控制
    const [wxButtonList, setWxButtonList] = useState<WxAutoButton[]>([])
    const [tableData, setTableData] = useState<any[]>([])   // 预览表格
    const [tableSelect, setTableSelect] = useState<any[]>([])
    const [geoLocationList, setGeoLocationList] = useState<any>({}) // 所有地域列表
    const [modelList, setModelList] = useState<any>({})  // 所有品牌手机
    const { init, get } = useModel('useLaunchAdq.useBdMediaPup')


    const tagsList_REGION = useAjax((params) => getTagsList(params))
    const tagsList_MODEL = useAjax((params) => getTagsList(params))
    const getSysAdgroups = useAjax((params) => getSysAdgroupsInfo(params))
    const getsysTargeting = useAjax((params) => getsysTargetingInfo(params))
    /*************************/

    // 设置地域
    useEffect(() => {
        tagsList_REGION.run({ type: 'REGION' }).then(res => {
            if (res) {
                setGeoLocationList(() => (res as any[])?.reduce((prev: any, cur: { id: number }) => {
                    prev[cur.id] = cur
                    return prev
                }, {}))
            }
        })
        tagsList_MODEL.run({ type: 'DEVICE_BRAND_MODEL' }).then(res => {
            if (res) {
                setModelList(() => (res as any[])?.reduce((prev: any, cur: { id: number }) => {
                    prev[cur.id] = cur
                    return prev
                }, {}))
            }
        })
    }, [])

    // 获取账户列表
    useEffect(() => {
        getAdAccount.run()
        init({ mediaType: 'PAGE' })
    }, [])

    /** 获取广告详情 */
    useEffect(() => {
        if (queryForm?.sysAdgroupsId) {
            getSysAdgroups.run(queryForm?.sysAdgroupsId)
        }
    }, [queryForm?.sysAdgroupsId])
    /** 获取定向详情 */
    useEffect(() => {
        if (queryForm?.sysTargetingId) {
            getsysTargeting.run(queryForm?.sysTargetingId)
        }
    }, [queryForm?.sysTargetingId])

    /** 获取落地页详情 */
    useEffect(() => {
        if (queryForm?.sysPageId) {
            get.run({ mediaType: 'PAGE', sysMediaId: queryForm?.sysPageId }).then(res => {
                let data = res
                let pageElementsSpecList = data?.pageSpecsList[0]?.pageElementsSpecList
                setWxButtonList(() => (pageElementsSpecList as any[])?.filter((item: { elementType: string }) => item?.elementType === 'ENTERPRISE_WX'))
            })
        }
    }, [queryForm?.sysPageId])

    /** 删除商品内容 */
    const goodsDel = (index: number) => {
        let newArr = JSON.parse(JSON.stringify(accountCreateLogs))
        delete newArr[index].productList
        setAccountCreateLogs(newArr)
    }

    /** 删除数据源 */
    const sourceDel = (index: number, num: number) => {
        console.log(index, num);
        let newArr = JSON.parse(JSON.stringify(accountCreateLogs))
        newArr[index].userActionSetsList?.splice(num, 1)
        setAccountCreateLogs(newArr)
    }

    /** 设置落地页 */
    const setPage = (e: any) => {
        setQueryForm({ ...queryForm, sysPageId: e[0]?.id || undefined })
        setSelectImgVisible(false)
    }

    /** 预览 */
    const preview = () => {
        if (accountCreateLogs?.length === 0) {
            message.error('请选择媒体账户')
            return
        }
        if (!queryForm.promotedObjectType) {
            message.error('请选择推广目标')
            return
        }
        if (!queryForm.sysAdgroupsId) {
            message.error('请先设置广告基本信息')
            return
        }
        if (!queryForm.sysTargetingId) {
            message.error('请选择定向')
            return
        }
        // if (!queryForm.sysAdcreativeId) {
        //     message.error('请设置创意的基本信息')
        //     return
        // }
        if (!queryForm.sysPageId) {
            message.error('请选择落地页')
            return
        }
        let data = accountCreateLogs.map((item: any, index) => {
            return { ...item, id: index + 1, ...queryForm, sysAdGroupData: getSysAdgroups?.data, targetingData: getsysTargeting?.data, pageData: get?.data }
        })
        console.log('data--->', data)
        setTableData(data)
    }

    const submit = (data: { adName: string, campaignName: string }) => {
        console.log(111111, tableSelect);
        console.log(222222, data)
    }

    return <Space direction="vertical" style={{ width: '100%' }}>
        <Card title={<div className={style.cardTitle}>配置区</div>} className={style.createAd} hoverable>
            <Space>
                <Selector label="媒体账户">
                    <Select
                        mode="multiple"
                        style={{ minWidth: 200 }}
                        placeholder="请选择媒体账户"
                        maxTagCount={1}
                        allowClear
                        bordered={false}
                        filterOption={(input: any, option: any) =>
                            (option!.children as unknown as string).toLowerCase().includes(input.toLowerCase())
                        }
                        onChange={(e, option) => {
                            setAccountCreateLogs(option?.map((item: any) => ({ adAccountId: item?.children, id: item?.value })))
                        }}
                    >
                        {getAdAccount?.data?.data?.map((item: any) => <Select.Option value={item.id} key={item.id}>{item.accountId}</Select.Option>)}
                        {/* <Select.OptGroup label="Engineer">
                            <Select.Option value="20632113">20632113</Select.Option>
                        </Select.OptGroup> */}
                    </Select>
                </Selector>

                <Selector label="推广目标">
                    <Select style={{ width: 200 }} value={queryForm?.promotedObjectType} placeholder="请选择推广目标" bordered={false} showSearch filterOption={(input: any, option: any) =>
                        (option!.children as unknown as string).toLowerCase().includes(input.toLowerCase())
                    } onChange={(e) => { setQueryForm({ ...queryForm, promotedObjectType: e }) }}>
                        {Object.keys(PromotedObjectType).map(key => {
                            return <Select.Option value={key} key={key}>{PromotedObjectType[key]}</Select.Option>
                        })}
                    </Select>
                </Selector>
            </Space>

            <div className={style.cardBody}>
                <Row className={style.content}>
                    <Col span={16} className={style.conLeft}>
                        <Row className={`${style.conTitle} ${style.conRightBorder}`}><Col span={24}>广告</Col></Row>
                        <Row className={style.items}>
                            {/* =============广告基本信息=========== */}
                            <Col className={style.conRightBorder}>
                                <div className={style.top}>广告基本信息</div>
                                <div className={style.center}>
                                    <Spin spinning={getSysAdgroups.loading}>
                                        <div className={style.centerContent}>
                                            {getSysAdgroups?.data ? <>
                                                <div>广告名称: <span>{getSysAdgroups?.data?.adgroupName}</span></div>
                                                <div>推广目标: <span>{PromotedObjectType[getSysAdgroups?.data?.promotedObjectType]}</span></div>
                                                <div>广告版位: <span>{getSysAdgroups?.data?.siteSet?.map((item: string) => SiteSetEnum[item]).toString()}</span></div>
                                                <div>投放日期: <span>{getSysAdgroups?.data?.endDate ? getSysAdgroups?.data?.beginDate + '~' + getSysAdgroups?.data?.endDate : getSysAdgroups?.data?.beginDate + '~' + '长期投放'}</span></div>
                                                <div>出价方式: <span>{BidModeEnum[getSysAdgroups?.data?.bidMode]}</span></div>
                                                <div>优化目标: <span>{OptimizationGoalEnum[getSysAdgroups?.data?.optimizationGoal]}</span></div>
                                                <div>出价类型: <span>{getSysAdgroups?.data?.smartBidType === 'SMART_BID_TYPE_CUSTOM' ? '手动出价' : '自动出价'}</span></div>
                                                <div>出价策略: <span>{BidStrategyEnum[getSysAdgroups?.data?.bidStrategy]}</span></div>
                                                <div>广告出价: <span>{getSysAdgroups?.data?.bidAmount}</span></div>
                                                <div>广告日预算: <span>{getSysAdgroups?.data?.dailyBudget || '不限'}</span></div>
                                            </> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                                        </div>
                                    </Spin>
                                </div>
                                <div className={style.bottom}>
                                    {queryForm?.promotedObjectType ? <span onClick={() => { setAdVisible(true) }}>{getSysAdgroups?.data ? '修改' : '添加'}</span> : <Tooltip title="请先选择推广目标">
                                        <span>添加</span>
                                    </Tooltip>}
                                </div>
                            </Col>
                            {/* =============定向包=========== */}
                            <Col className={style.conRightBorder}>
                                <div className={style.top}>
                                    定向{/* <span>已选：{1}</span> */}
                                </div>
                                <div className={style.center}>
                                    <Spin spinning={getsysTargeting.loading}>
                                        <div className={style.centerContent}>
                                            {getsysTargeting?.data ? <>
                                                <div>定向名称: <span>{getsysTargeting?.data?.targetingName}</span></div>
                                                <div>定向描述: <span>{getsysTargeting?.data?.description}</span></div>
                                                <TargetingTooltip data={getsysTargeting?.data} geoLocationList={geoLocationList} modelList={modelList}/>
                                            </> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                                        </div>
                                    </Spin>
                                </div>
                                <div className={style.bottom}><span onClick={() => { setDxVisible(true) }}>{getsysTargeting?.data ? '修改' : '添加'}</span></div>
                            </Col>
                            {/* =============商品=========== */}
                            <Col className={style.conRightBorder}>
                                <div className={style.top}>
                                    商品{/* <span>已选：{1}</span> */}
                                </div>
                                <div className={style.center}>
                                    <div className={style.centerContent}>
                                        {accountCreateLogs?.map((item: any, index: number) => {
                                            if (item?.productList) {
                                                return <div className={style.acc} key={index}>
                                                    <div className={style.accName}>{item.adAccountId}</div>
                                                    {
                                                        item?.productList?.map((pack: { productName: string, author: string, id: number }, index: number) => {
                                                            return <div className={style.accCon} key={pack.id}>{pack.productName}<CloseOutlined className={style.close} onClick={() => {
                                                                goodsDel(index)
                                                            }} /></div>
                                                        })
                                                    }
                                                </div>
                                            } else {
                                                return null
                                            }
                                        })}
                                    </div>
                                </div>
                                <div className={style.bottom}>
                                    {accountCreateLogs?.length > 0 ? <span onClick={() => { setGoodsVisible(true) }}>编辑</span> : <Tooltip title="请先选择媒体账户">
                                        <span>编辑</span>
                                    </Tooltip>}
                                </div>
                            </Col>
                            {/* 数据源 */}
                            <Col className={style.conRightBorder}>
                                <div className={style.top}>
                                    数据源 {/* <span>已选：{1}</span> */}
                                </div>
                                <div className={style.center}>
                                    {/* userActionSetsList */}
                                    <div className={style.centerContent}>
                                        {accountCreateLogs?.map((item: any, index: number) => {
                                            if (item?.userActionSetsList && item?.userActionSetsList?.length > 0) {
                                                return <div className={style.acc} key={index}>
                                                    <div className={style.accName}>{item.adAccountId}</div>
                                                    {
                                                        item?.userActionSetsList?.map((pack: { name: string, type: string, id: number }, index1: number) => {
                                                            return <div className={style.accCon} key={pack.id}> <span className={style.title}>{pack.name}{' > '}{pack.type}</span> <CloseOutlined className={style.close} onClick={() => {
                                                                sourceDel(index, index1)
                                                            }} /></div>
                                                        })
                                                    }
                                                </div>
                                            } else {
                                                return null
                                            }
                                        })}
                                    </div>
                                </div>
                                <div className={style.bottom}>
                                    {accountCreateLogs?.length > 0 ? <span onClick={() => { setSourceVisible(true) }}>编辑</span> : <Tooltip title="请先选择媒体账户">
                                        <span>编辑</span>
                                    </Tooltip>}
                                </div>
                            </Col>
                        </Row>
                    </Col>
                    {/* =============广告创意=========== */}
                    <Col span={8} className={style.conRight}>
                        <Row className={style.conTitle}><Col span={24}>广告创意</Col></Row>
                        <Row className={style.items}>
                            <Col span={12} className={style.conRightBorder}>
                                <div className={style.top}>创意基本信息</div>
                                <div className={style.center}>

                                </div>
                                <div className={style.bottom}><span onClick={() => { }}>编辑</span></div>
                            </Col>
                            <Col span={12} >
                                <div className={style.top}>
                                    落地页
                                    {wxButtonList?.length > 0 && <Button type="link" size="small">配置客服</Button>}
                                </div>
                                <div className={style.center}>
                                    <Spin spinning={get.loading}>
                                        <div className={style.centerContent}>
                                            {queryForm?.sysPageId ? <>
                                                <div>落地页名称：{get?.data?.pageName || ''}</div>
                                                <div>分享名称：{get?.data?.shareContentSpec?.shareTitle || ''}</div>
                                                <div>分享描述：{get?.data?.shareContentSpec?.shareDescription || ''}</div>
                                                <div>原生推广页顶部素材预览：
                                                    <div>{get?.data?.pageSpecsList[0]?.pageElementsSpecList?.filter((item: any, index: number) => index === 0)?.map((item: { elementType: 'TOP_IMAGE' | 'TOP_VIDEO' | 'TOP_SLIDER', topImageSpec: any, topSliderSpec: any, topVideoSpec: any }, index: number) => {
                                                        switch (item?.elementType) {
                                                            case 'TOP_IMAGE':
                                                                return <Image width={80} src={item.topImageSpec.imageUrl} style={{ borderRadius: 8, overflow: 'hidden' }} key={index} />
                                                            case 'TOP_SLIDER':
                                                                return <Space wrap>
                                                                    {item?.topSliderSpec?.imageUrlList?.map((url: string, index: number) => <Image width={70} src={url} style={{ borderRadius: 8 }} key={index} />)}
                                                                </Space>
                                                            case 'TOP_VIDEO':
                                                                return <video src={item.topVideoSpec.videoUrl} width={150} controls key={index}></video>
                                                        }
                                                    })}</div>
                                                </div>
                                            </> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                                        </div>
                                    </Spin>
                                </div>
                                <div className={style.bottom}>{queryForm?.sysAdgroupsId ? <>
                                    {queryForm?.sysPageId && <Button type="link" onClick={() => { setLookVisible(true) }}>查看</Button>}
                                    <Button type="link" onClick={() => { setSelectImgVisible(true) }}>{queryForm?.sysPageId ? '修改' : '选择落地页'}</Button>
                                </> : <Tooltip title="请先设置广告基本信息和创意">
                                    <Button type="link"><span>选择落地页</span></Button>
                                </Tooltip>}
                                </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>

        <Card
            className={style.createAd}
            hoverable
            extra={tableData?.length > 0 ? <Space>
                <span>推广计划总数：{accountCreateLogs?.length}</span>
                <span>广告总数：{accountCreateLogs?.length}</span>
                {tableSelect?.length > 0 && <span> 已选：<span style={{ color: '#1890FF' }}>{tableSelect?.length}</span> 条</span>}
                {
                    <Button type='primary' onClick={() => {
                        if (tableSelect.length === 0) {
                            message.error('请选择要提交的计划！')
                            return
                        };
                        setSubVisible(true)
                    }}>批量提交审核</Button>
                }
            </Space> : false
            }
        >
            {tableData?.length > 0 ? <div className={style.cardBody}>
                <div className={style.content} style={{ marginTop: 20 }}>
                    <Tables
                        columns={columns()}
                        dataSource={tableData}
                        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> : <div style={{ minHeight: 400, display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                <Empty description="请先完成模块配置后，再预览广告计划" />
            </div>}
        </Card>


        {/* 选择广告 */}
        {adVisible && <AdModal visible={adVisible} onClose={() => setAdVisible(false)} promotedObjectType={queryForm.promotedObjectType as string} onChange={(e) => { setQueryForm({ ...queryForm, sysAdgroupsId: e }); setAdVisible(false) }} sysAdgroupsId={queryForm?.sysAdgroupsId}/>}
        {/* 选择定向 */}
        {dxVisible && <TargetingModal visible={dxVisible} onClose={() => setDxVisible(false)} onChange={(e) => { setQueryForm({ ...queryForm, sysTargetingId: e }); setDxVisible(false) }} sysTargetingId={queryForm?.sysTargetingId}/>}
        {/* 选择商品 */}
        {goodsVisible && <GoodsModal visible={goodsVisible} data={accountCreateLogs} onClose={() => setGoodsVisible(false)} onChange={(e) => { setAccountCreateLogs(e); setGoodsVisible(false) }} />}
        {/* 选择数据源 */}
        {sourceVisible && <DataSourceModal visible={sourceVisible} data={accountCreateLogs} onClose={() => setSourceVisible(false)} onChange={(e) => { setAccountCreateLogs(e); setSourceVisible(false) }} />}
        {/* 选择转化ID */}
        {idVisible && <IdModal visible={idVisible} data={accountCreateLogs} onClose={() => setIdVisible(false)} onChange={(e) => { setAccountCreateLogs(e); setSourceVisible(false) }} />}
        {/* 选择素材 */}
        {selectImgVisible && <SelectCloud visible={selectImgVisible} onClose={() => setSelectImgVisible(false)} onChange={setPage} isBack={false} />}
        {/* 查看落地页 */}
        {lookVisible && <LookLanding visible={lookVisible} onClose={() => setLookVisible(false)} id={queryForm?.sysPageId as any} />}
        {/* 设置名称 */}
        {subVisible && <SubmitModal visible={subVisible} onClose={() => setSubVisible(false)} onChange={submit} />}
    </Space>
}


export default CreateAd