import { Button, Card, Checkbox, Divider, Empty, Modal, Popconfirm, Select, Space, Spin, Table, Tabs, Tag, Tooltip, message } from "antd"
import React, { useEffect, useState } from "react"
import style from './index.less'
import '../index.less'
import Selector from "@/pages/launchSystemNew/launchManage/createAd/selector"
import { CheckOutlined, SearchOutlined } from "@ant-design/icons"
import Ad from "./Ad"
import Target from "./Target"
import { getAccountListApi, getGroupListApi } from "@/services/launchAdq/subgroup"
import { useAjax } from "@/Hook/useAjax"
import { useModel } from "umi"
import GoodsModal from "../../components/GoodsModal"
import DataSourceModal from "../../components/DataSourceModal"
import moment from "moment"
import Dynamic from "./Dynamic"
import Material from "./Material"
import MaterialText from "./MaterialText"
import PageList from "./PageList"
import { cartesianProduct } from "@/utils/utils"
import columns from "./tableConfig"
import SubmitModal from "./submitModal"
import { createAdgroupTaskApi } from "@/services/adqV3"
import WechatAccount from "../../components/WechatAccount"

export const DispatchAddelivery = React.createContext<PULLIN.DispatchAddelivery | null>(null);

/**
 * 创建广告
 * @returns 
 */
const Create: React.FC = () => {

    /*******************************************/
    const { getAllUserAccount } = useModel('useLaunchAdq.useAdAuthorize')
    const { initTargeting } = useModel('useLaunchV3.useTargeting')
    const [addelivery, setAddelivery] = useState<PULLIN.AddeliveryProps>({ adgroups: {}, targeting: [], dynamic: {}, dynamicMaterialDTos: {}, dynamicCreativesTextDTOS: {} })
    const { marketingAssetOuterSpec, marketingCarrierType } = addelivery.adgroups
    const [accSearch, setAccSearch] = useState<string>()
    const [accountCreateLogs, setAccountCreateLogs] = useState<PULLIN.AccountCreateLogsProps[]>([])  // 账户
    const [goodsVisible, setGoodsVisible] = useState<boolean>(false) // 选择小说弹窗控制
    const [wechatVisible, setWechatVisible] = useState<boolean>(false) // 选择微信公众号弹窗控制
    const [sourceVisible, setSourceVisible] = useState<boolean>(false) // 选择数据源弹窗控制
    const [materialData, setMaterialData] = useState<any>({}) // 素材数据
    const [textData, setTextData] = useState<any>({})
    const [tableData, setTableData] = useState<any>({})
    const [activeKey, setActiveKey] = useState<string>()
    const [subVisible, setSubVisible] = useState<boolean>(false) // 选择设置名称弹窗控制
    const [adCount, setAdCount] = useState<number>(0)
    const [dynamicCount, setDynamicCount] = useState<number>(0)

    const getGroupList = useAjax(() => getGroupListApi())
    const createAdgroupTask = useAjax((params) => createAdgroupTaskApi(params))
    /*******************************************/

    useEffect(() => {
        console.log('addelivery---->', addelivery)
        // 获取账户组
        getGroupList.run()
        // 获取账户列表
        getAllUserAccount.run()
        initTargeting()
    }, [])

    /** 获取分组里账号 */
    const getGroupAccountList = (ids: number[]) => {
        if (ids.length > 0) {
            let data = ids.map(id => getAccountListApi(id))
            Promise.all(data).then(res => {
                if (res?.length > 0 && res.every((item: { code: number }) => item.code === 200)) {
                    let userArr: any[] = []
                    res.forEach((item: { data: { adAccountList: { accountId: number, id: number }[] } }) => {
                        item.data.adAccountList.forEach(acc => {
                            let obj = userArr.find((item: { accountId: number }) => item.accountId === acc.accountId)
                            if (!obj) {
                                userArr.push(acc)
                            }
                        })
                    })
                    setAccountCreateLogs(userArr?.map((item) => ({ accountId: item?.accountId })))
                    clearData()
                    setAddelivery({ adgroups: {}, targeting: [], dynamic: {}, dynamicMaterialDTos: {}, dynamicCreativesTextDTOS: {} })
                } else {
                    message.error('操作异常')
                }
            })
        } else {
            setAccountCreateLogs([])
        }
    }

    /** 存为预设 */
    const severBd = () => {
        // queryForm accountCreateLogs
        localStorage.setItem('ADQADV3', JSON.stringify({
            addelivery,
            accountCreateLogs,
            materialData,
            textData
        }))
        message.success('存储成功')
    }

    /** 清除 */
    const delBdPlan = () => {
        localStorage.removeItem('ADQADV3')
        setAccountCreateLogs([])
        setMaterialData({})
        setTextData({})
        setAddelivery({
            adgroups: {},
            targeting: [],
            dynamic: {},
            dynamicMaterialDTos: {},
            dynamicCreativesTextDTOS: {}
        })
        setTableData({})
    }

    /**数据回填 */
    useEffect(() => {
        let adqAdData = localStorage.getItem('ADQADV3')
        if (adqAdData) {
            const { addelivery, accountCreateLogs, materialData, textData } = JSON.parse(adqAdData)
            if (addelivery?.adgroups) {
                if (addelivery?.adgroups?.beginDate && moment(addelivery?.adgroups?.beginDate) < moment()) {
                    addelivery.adgroups.beginDate = moment().format('YYYY-MM-DD')
                    message.warning('请注意，检测投放开始日期小于今天，已自动改成今天，如需修改，请重新设置')
                }
                if (addelivery?.adgroups?.endDate && moment(addelivery?.adgroups?.endDate) < moment()) {
                    addelivery.adgroups.endDate = moment().format('YYYY-MM-DD')
                    message.warning('请注意，检测投放结束日期小于今天，已自动改成今天，如需修改，请重新设置')
                }
            }
            setAddelivery({ ...addelivery })
            setAccountCreateLogs(accountCreateLogs)
            setMaterialData(materialData)
            setTextData(textData)
        }
    }, [])


    const preview = () => {
        console.log('addelivery------>', addelivery)
        console.log('accountCreateLogs------>', accountCreateLogs)
        if (accountCreateLogs?.length === 0) {
            message.error('请先选择媒体账户')
            return
        }
        const { adgroups, targeting, dynamic, dynamicMaterialDTos, dynamicCreativesTextDTOS } = addelivery
        if (!(adgroups && Object.keys(adgroups).length)) {
            message.error('请先配置广告信息')
            return
        }
        if (['MARKETING_TARGET_TYPE_FICTION'].includes(marketingAssetOuterSpec?.marketingTargetType) && !accountCreateLogs?.some(item => item?.productList?.length)) {
            message.error('请先选择小说')
            return
        }
        if ((['MARKETING_TARGET_TYPE_WECHAT_OFFICIAL_ACCOUNT'].includes(marketingAssetOuterSpec?.marketingTargetType) || marketingCarrierType === 'MARKETING_CARRIER_TYPE_WECHAT_OFFICIAL_ACCOUNT') && !accountCreateLogs?.some(item => item?.wechatChannelList?.length)) {
            message.error('请先选择公众号')
            return
        }
        if (!(targeting?.length)) {
            message.error('请先添加定向')
            return
        }
        if (!(dynamic && Object.keys(dynamic).length)) {
            message.error('请先配置创意')
            return
        }
        if ((materialData && Object.keys(materialData).length) && !(dynamicMaterialDTos && Object.keys(dynamicMaterialDTos).length)) {
            message.error('请先配置创意素材')
            return
        }
        if ((textData && Object.keys(textData).length) && !(dynamicCreativesTextDTOS && Object.keys(dynamicCreativesTextDTOS).length)) {
            message.error('请先配置创意文案')
            return
        }
        if (!accountCreateLogs?.some(item => item?.pageList?.length)) {
            message.error('请先选择落地页')
            return
        }

        let newTableData: any = {}
        let newAdCount = 0, newdynamicCount = 0
        accountCreateLogs.forEach(item => {
            let productList: any[] = []
            if (['MARKETING_TARGET_TYPE_FICTION'].includes(marketingAssetOuterSpec?.marketingTargetType)) { // 小说
                productList = item?.productList || []
            } else if (['MARKETING_TARGET_TYPE_WECHAT_OFFICIAL_ACCOUNT'].includes(marketingAssetOuterSpec?.marketingTargetType)) { // 公众号
                productList = item?.wechatChannelList || []
            }
            let data = cartesianProduct(productList, targeting).map(newD => {
                let [productDto, targetDto, index] = newD
                let suffix = '_' + item.accountId + '_' + index
                let dat: any = {
                    id: item.accountId + '_' + index,
                    accountId: item.accountId,                    // 账户
                    userActionSetsList: item.userActionSetsList,  // 数据源
                    pageListDto: item.pageList,                   // 落地页
                    productDto,                                   // 商品
                    targetDto: {                                  // 定向
                        ...targetDto,
                        targetingName: targetDto.targetingName + suffix
                    },
                    adgroupsDto: {                                // 广告信息
                        ...adgroups,
                        adgroupName: adgroups.adgroupName + suffix
                    },
                    dynamicDto: dynamic,                          // 创意信息
                    rowSpan: dynamicMaterialDTos?.dynamicGroup?.length || 1
                }
                if (marketingCarrierType === 'MARKETING_CARRIER_TYPE_WECHAT_OFFICIAL_ACCOUNT') { // 营销载体
                    dat.marketingCarrierDto = item?.wechatChannelList
                }
                return dat
            })
            newAdCount += data.length
            let newData = cartesianProduct(data, dynamicMaterialDTos.dynamicGroup || [{}]).map((item, index) => {
                let [d1, group] = item
                return {
                    ...d1,
                    id: d1.id + '_' + index,
                    dynamicGroup: group,
                    textDto: dynamicCreativesTextDTOS?.dynamicCreativesTextDetailDTOList?.[index % dynamicMaterialDTos.dynamicGroup?.length],                     // 创意文案
                }
            })
            newdynamicCount = newdynamicCount + newData.length

            newTableData[item.accountId] = newData
        })
        setAdCount(newAdCount)
        setDynamicCount(newdynamicCount)
        setActiveKey(accountCreateLogs?.[0].accountId?.toString())
        setTableData(newTableData)
    }

    const onSubmit = (values: any) => {
        const { adgroups, targeting, dynamic, dynamicMaterialDTos, dynamicCreativesTextDTOS } = addelivery

        let dynamicMaterialDTOS = []
        if ((materialData && Object.keys(materialData).length && dynamicMaterialDTos && Object.keys(dynamicMaterialDTos).length)) {
            let mType = Object.keys(materialData)[0];
            dynamicMaterialDTOS = dynamicMaterialDTos.dynamicGroup?.map((item: any) => {
                if (mType === 'image') {
                    return [{
                        type: mType,
                        valueJson: JSON.stringify({
                            value: {
                                imageUrl: item?.image_id?.url,
                                imageId: item?.image_id?.id,
                                materialType: item?.image_id?.materialType
                            }
                        })
                    }]
                } else if (mType === 'image_list' || mType === 'element_story') {
                    let key = 'image_list'
                    if (mType === 'element_story') {
                        key = 'element_story'
                    }
                    let list = item?.[key]?.map((l: any) => {
                        return {
                            imageUrl: l?.url,
                            imageId: l?.id,
                            materialType: l?.materialType
                        }
                    })
                    return [{
                        type: mType,
                        valueJson: JSON.stringify({
                            value: {
                                list
                            }
                        })
                    }]
                } else if (['short_video', 'video'].includes(mType)) {
                    let value: any = {
                        materialType: item?.video_id?.materialType || item?.short_video1?.materialType || 0,
                        videoUrl: item?.video_id?.url || item?.short_video1?.url,
                        videoId: item?.video_id?.id || item?.short_video1?.id
                    }
                    if (item?.cover_id?.url) {
                        value.imageUrl = item?.cover_id?.url
                        value.imageId = item?.cover_id?.id
                        value.materialCoverType = item?.cover_id?.materialType
                    }
                    return [{
                        type: mType,
                        valueJson: JSON.stringify({
                            value
                        })
                    }]
                }
                return [{
                    type: mType,
                    valueJson: ''
                }]
            })
        }
        let accountIdParamDTOMap: any = {}
        accountCreateLogs.forEach(item => {
            let { pageList, productList, userActionSetsList, accountId, wechatChannelList } = item

            let userActionSetsListDto = userActionSetsList?.map((item: any) => ({ id: item?.userActionSetId, type: item?.type })) // dataSourceId

            let map: any = {
                userActionSetsList: userActionSetsListDto,
                pageList: pageList?.map((item: { pageId: any }) => item.pageId)
            }
            if (productList) {
                map.productDTOS = productList?.map(item => {
                    return { productId: item.marketingAssetId }
                })
            }
            if (wechatChannelList) {
                map.wechatChannelId = wechatChannelList?.[0]?.wechatOfficialAccountId
            }

            accountIdParamDTOMap[accountId] = map
        })
        let params = {
            ...values,
            adgroupDTO: adgroups,
            targetings: targeting.map(item => ({ targetingName: item.targetingName, ...item?.targeting || {} })),
            dynamicCreativesDTO: dynamic,
            dynamicCreativesTextDTOS,
            dynamicMaterialDTOS,
            accountIdParamDTOMap
        }
        // setSubVisible(false)
        createAdgroupTask.run(params).then(res => {
            if (res) {
                Modal.success({
                    content: '任务提交成功',
                    bodyStyle: { fontWeight: 700 },
                    okText: '跳转任务列表',
                    closable: true,
                    onOk: () => {
                        sessionStorage.setItem('CAMPV3', values?.taskName)
                        window.location.href = '/#/launchSystemV3/tencentAdPutIn/taskList'
                    },
                    onCancel: () => {
                        setSubVisible(false)
                    }
                })
            }
        })
    }

    const clearData = () => {
        setTableData({})
    }

    return <Space direction="vertical" style={{ width: '100%' }}>
        <Spin spinning={false}>
            <Card
                size="small"
                title={
                    <div>
                        <Space>
                            <div className={style.cardTitle}>配置区</div>
                        </Space>
                    </div>
                }
                className={style.createAd}
            >
                <Space wrap>
                    <Selector label="媒体账户组">
                        <Select
                            mode="multiple"
                            style={{ minWidth: 200 }}
                            placeholder="快捷选择媒体账户组"
                            maxTagCount={1}
                            allowClear
                            bordered={false}
                            filterOption={(input: any, option: any) => {
                                return option!.children?.toString().toLowerCase().includes(input.toLowerCase())
                            }}
                            onChange={(e, option) => { getGroupAccountList(e) }}
                        >
                            {getGroupList?.data && getGroupList?.data?.map((item: any) => <Select.Option value={item.groupId} key={item.groupId}>{item.groupName}</Select.Option>)}
                        </Select>
                    </Selector>
                    <Selector label="媒体账户">
                        <Select
                            mode="multiple"
                            style={{ minWidth: 200, maxWidth: 500 }}
                            placeholder="媒体账户(多个，,空格换行)"
                            maxTagCount={1}
                            allowClear
                            bordered={false}
                            maxTagPlaceholder={
                                <Tooltip
                                    color="#FFF"
                                    title={<span style={{ color: '#000' }}>
                                        {accountCreateLogs?.filter((item, index) => index !== 0)
                                            ?.map((item, index) => <Tag
                                                key={index}
                                                closable
                                                onClose={() => {
                                                    setAccountCreateLogs(accountCreateLogs?.filter(item1 => item1.accountId !== item.accountId))
                                                    // setQueryForm({ ...queryForm, adqPageList: [], pageList: [], taskMediaMaps: queryForm?.taskMediaMaps?.map((item: { sysPageId: number }) => ({ ...item, sysPageId: '', accountPageIdMap: {}, cropUserGroupMap: [] })) })
                                                    // clearData()
                                                }}
                                            >{item.accountId}</Tag>)}</span>
                                    }
                                >
                                    <span>+{accountCreateLogs?.length > 1 ? accountCreateLogs.length - 1 : 0}</span>
                                </Tooltip>
                            }
                            autoClearSearchValue={false}
                            filterOption={(input: any, option: any) => {
                                let newInput: string[] = input ? input?.split(/[,，\n\s]+/ig).filter((item: any) => item) : []
                                return newInput?.some(val => option!.children?.toString().toLowerCase()?.includes(val))
                            }}
                            value={accountCreateLogs?.map(item => item?.accountId)}
                            onChange={(e) => {
                                setAccountCreateLogs(e?.map((item: any) => ({ accountId: item })))
                            }}
                            searchValue={accSearch}
                            onSearch={(val) => {
                                setAccSearch(val)
                            }}
                            dropdownRender={menu => (
                                <>
                                    {menu}
                                    <Divider style={{ margin: '8px 0' }} />
                                    <Space style={{ padding: '0 8px 4px' }}>
                                        <Checkbox onChange={(e) => {
                                            let data = []
                                            if (e.target.checked) {
                                                data = JSON.parse(JSON.stringify(getAllUserAccount?.data?.data))
                                                if (accSearch) {
                                                    let newAccSearch = accSearch?.split(/[,，\n\s]+/ig).filter((item: any) => item)
                                                    data = data?.filter((item: any) => newAccSearch?.some(val => item!.accountId?.toString().toLowerCase()?.includes(val)))
                                                }
                                            }
                                            // setQueryForm({ ...queryForm, adqPageList: [], pageList: [], taskMediaMaps: queryForm?.taskMediaMaps?.map((item: { sysPageId: number }) => ({ ...item, sysPageId: '', accountPageIdMap: {}, cropUserGroupMap: [] })) })
                                            setAccountCreateLogs(data?.map((item: any) => ({ accountId: item?.accountId })))
                                            // clearData()
                                        }}>全选</Checkbox>
                                    </Space>
                                </>
                            )}
                        >
                            {getAllUserAccount?.data?.data?.map((item: any) => <Select.Option value={item.accountId} key={item.id}>{item.remark ? item.accountId + '_' + item.remark : item.accountId}</Select.Option>)}
                        </Select>
                    </Selector>

                    {accountCreateLogs?.length > 0 && <>
                        {marketingAssetOuterSpec?.marketingTargetType === 'MARKETING_TARGET_TYPE_FICTION' && <Button type="primary" danger={!accountCreateLogs?.some(item => item?.productList?.length)} onClick={() => { setGoodsVisible(true) }}>{accountCreateLogs?.some(item => item?.productList?.length) ? <>重新选择小说 <CheckOutlined style={{ color: '#FFFFFF' }} /></> : '请选择小说'}</Button>}
                        {(marketingAssetOuterSpec?.marketingTargetType === 'MARKETING_TARGET_TYPE_WECHAT_OFFICIAL_ACCOUNT' || marketingCarrierType === 'MARKETING_CARRIER_TYPE_WECHAT_OFFICIAL_ACCOUNT') && <Button type="primary" danger={!accountCreateLogs?.some(item => item?.wechatChannelList?.length)} onClick={() => { setWechatVisible(true) }}>{accountCreateLogs?.some(item => item?.wechatChannelList?.length) ? <>重新选择公众号 <CheckOutlined style={{ color: '#FFFFFF' }} /></> : '请选择公众号'}</Button>}
                        <Button onClick={() => { setSourceVisible(true) }}>精准匹配归因（选填）{accountCreateLogs?.some(item => item?.userActionSetsList?.length) && <CheckOutlined style={{ color: '#1890ff' }} />}</Button>
                    </>}
                </Space>

                <div className={style.settingsBody}>
                    <div className={style.settingsBody_content}>
                        <DispatchAddelivery.Provider
                            value={{
                                addelivery,
                                setAddelivery,
                                accountCreateLogs,
                                setAccountCreateLogs,
                                materialData,
                                setMaterialData,
                                textData,
                                setTextData,
                                clearData
                            }}>
                            <div className={style.settingsBody_content_right}>
                                {/* 广告信息 */}
                                <Ad />
                                {/* 定向 */}
                                <Target />
                                {/* 创意 */}
                                <Dynamic />
                                {/* 创意素材 */}
                                <Material />
                            </div>
                            <div className={style.settingsBody_content_left}>
                                {/* 创意文案 */}
                                <MaterialText />
                                {/* 落地页 */}
                                <PageList />
                            </div>
                        </DispatchAddelivery.Provider>
                    </div>
                </div>
                <Space className={style.bts} wrap>
                    <Button type='primary' onClick={severBd}>存为预设</Button>
                    <Popconfirm
                        title="确定清空?"
                        onConfirm={delBdPlan}
                    >
                        <Button>清空配置/预设</Button>
                    </Popconfirm>
                    <Button type='primary' onClick={preview}><SearchOutlined />预览广告</Button>
                </Space>

                {/* 选择小说 */}
                {goodsVisible && <GoodsModal
                    visible={goodsVisible}
                    data={accountCreateLogs}
                    onClose={() => setGoodsVisible(false)}
                    onChange={(e) => {
                        setAccountCreateLogs(e);
                        setGoodsVisible(false);
                        clearData()
                    }}
                />}
                {/* 选择数据源 */}
                {sourceVisible && <DataSourceModal
                    visible={sourceVisible}
                    data={accountCreateLogs}
                    onClose={() => setSourceVisible(false)}
                    onChange={(e) => {
                        setAccountCreateLogs(e);
                        setSourceVisible(false);
                        clearData()
                    }}
                />}
                {/* 选择公众号 */}
                {wechatVisible && <WechatAccount
                    visible={wechatVisible}
                    data={accountCreateLogs}
                    onClose={() => setWechatVisible(false)}
                    onChange={(e) => {
                        setAccountCreateLogs(e);
                        setWechatVisible(false);
                        clearData()
                    }}
                />}
            </Card>
        </Spin>

        <Card
            className={style.createAd}
        >
            {activeKey && tableData && Object.keys(tableData)?.length > 0 ? <div className={style.cardBody}>
                <Tabs
                    onChange={(e) => { setActiveKey(e) }}
                    type="card"
                    activeKey={activeKey}
                    tabBarExtraContent={<Space>
                        <span>广告总数：{adCount}</span>
                        <span>创意总数：{dynamicCount}</span>
                        <Button type='primary' onClick={() => {
                            setSubVisible(true)
                        }}>提交创建</Button>
                    </Space>}
                >
                    {accountCreateLogs.map(item => <Tabs.TabPane tab={item.accountId} key={item.accountId} />)}
                </Tabs>
                <div className={style.content} style={{ marginTop: 20 }}>
                    <Table
                        columns={columns()}
                        dataSource={tableData[activeKey]}
                        size="small"
                        bordered
                        scroll={{ x: 1200 }}
                        rowKey={'id'}
                    // rowSelection={{
                    //     selectedRowKeys: tableSelect?.map((item: any) => item?.myId.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>

        {/* 提交任务 */}
        {subVisible && <SubmitModal
            ajax={createAdgroupTask}
            visible={subVisible}
            onChange={(e) => {
                onSubmit(e)
            }}
            onClose={() => {
                setSubVisible(false)
            }}
        />}
    </Space>
}

export default Create