import React, { useEffect, useState } from "react"
import '../../tencentAdPutIn/index.less'
import style from '../../components/GoodsModal/index.less'
import { Button, Checkbox, Input, message, Modal, Select, Space, Table, Tooltip, Typography } from "antd"
import { batchUpdateDownloadApi, getAdgroupDetailApi } from "@/services/launchAdq/adqv3";
import { useAjax } from "@/Hook/useAjax";
import { getAdqLandingPageOfficialListApi, getWXDownPageAuthInfoListApi } from "@/services/adqV3/global";
import { CheckOutlined, CloseOutlined, QuestionCircleOutlined, SyncOutlined } from "@ant-design/icons";
import columns from "../../components/PageModal/tableConfig";
const { Title, Text } = Typography;

interface ReplacePageProps {
    selectedRows: any[];
    visible?: boolean;
    onClose?: () => void;
    onChange?: () => void;
}

/**
 * 替换官方落地页
 * @returns 
 */
const ReplaceGfPage: React.FC<ReplacePageProps> = ({ selectedRows, visible, onChange, onClose }) => {

    /*********************************************/
    const { deliveryMode, creativeTemplateId, creativeComponents: { mainJumpInfo } } = selectedRows[0]
    const pageLength: number | undefined = mainJumpInfo?.length
    const [data, setData] = useState<{ adgroupId: number, accountId: number, dynamicCreativeId: number, pageLength: number, pageList: any[] }[]>(selectedRows.map(item => {
        return { adgroupId: item.adgroupId, accountId: item.accountId, dynamicCreativeId: item.dynamicCreativeId, pageList: [], pageLength: item.creativeComponents.mainJumpInfo.length }
    }))
    const [queryForm, setQueryForm] = useState<{ accountId?: number, pageName?: string, ownerUid?: number, pageSize: number, pageNum: number, isSqDownPage: boolean }>({ pageNum: 1, pageSize: 20, isSqDownPage: false })
    const [loading, setLoading] = useState<boolean>(false)
    const [loading1, setLoading1] = useState<boolean>(false)
    const [wXDownPageAuthInfo, setWXDownPageAuthInfo] = useState<any>({})
    const [selectAdz, setSelectAdz] = useState<number>(1)   // 选择创意
    const [selectData, setSelectData] = useState<any>(selectedRows[0])   // 选择创意
    const [tableData, setTableData] = useState<any>({})
    const [adDataInfo, setAdDataInfo] = useState<any>({})

    const batchUpdateDownload = useAjax((params) => batchUpdateDownloadApi(params))
    const getAdqLandingPageOfficialList = useAjax((params) => getAdqLandingPageOfficialListApi(params))
    /*********************************************/

    useEffect(() => {
        if (selectedRows?.length > 0) {
            setLoading(true)
            const accountDataList = [...new Set(selectedRows.map(item => item.accountId))]
            const infoAjax = accountDataList.map(accountId => getWXDownPageAuthInfoListApi(accountId))
            const newData: any = {}
            Promise.all(infoAjax).then(res => {
                res?.forEach((item, index) => {
                    newData[accountDataList[index]] = item?.data || []
                })
                setWXDownPageAuthInfo(newData)
                setLoading(false)
            }).catch(() => setLoading(false))

            const adIdDataList = [...new Set(selectedRows.map(item => item.adgroupId + '_' + item.accountId))]
            const adInfoAjax = adIdDataList.map(item => {
                const [adgroupId, accountId] = item.split('_')
                return getAdgroupDetailApi({ adgroupId: Number(adgroupId), accountId: Number(accountId) })
            })

            const newAdData: any = {}
            Promise.all(adInfoAjax).then(res => {
                res?.forEach((item, index) => {
                    const [adgroupId] = adIdDataList[index].split('_')
                    newAdData[adgroupId] = item?.data || []
                })
                setAdDataInfo(newAdData)
                setLoading1(false)
            }).catch(() => setLoading1(false))
        }
    }, [])

    useEffect(() => {
        if (selectData && selectData.accountId && Object.keys(adDataInfo).length) {
            getList()
        }
    }, [queryForm, selectData, adDataInfo])

    const getList = () => {
        const { marketingGoal, marketingTargetType, marketingCarrierType, siteSet, accountId } = adDataInfo[selectData.adgroupId]
        const params: any = {
            ...queryForm,
            accountId,
            pageStatus: 'NORMAL',
            marketingGoal,
            marketingTargetType,
            marketingCarrierType,
            siteSet: siteSet ? siteSet : ["SITE_SET_CHANNELS", "SITE_SET_MOMENTS", "SITE_SET_WECHAT", "SITE_SET_WECHAT_PLUGIN", "SITE_SET_KANDIAN", "SITE_SET_QQ_MUSIC_GAME", "SITE_SET_TENCENT_NEWS", "SITE_SET_TENCENT_VIDEO", "SITE_SET_MOBILE_UNION"],
            pageType: 'PAGE_TYPE_OFFICIAL',
            creativeTemplateId: creativeTemplateId || 311
        }
        if (params.isSqDownPage) {
            if (!params?.ownerUid) {
                setTableData({ total: 0, records: [] })
                return
            }
        } else {
            delete params?.ownerUid
        }
        delete params.isSqDownPage
        getAdqLandingPageOfficialList.run(params).then(res => {
            setTableData(res || {})
        })
    }

    const handleOk = () => {
        console.log(data)
        if (data.every(item => item.pageList.length === item.pageLength)) {
            batchUpdateDownload.run(data.map(item => {
                return {
                    accountId: item.accountId,
                    dynamicCreativeId: item.dynamicCreativeId,
                    pageId: item.pageList.map((ite: any) => ite.pageId)
                }
            })).then(res => {
                if (res) {
                    message.success('替换成功，结果记录查看')
                    onChange?.()
                }
            })
        } else {
            message.error('请为每个创意选择对应的落地页数量')
        }
    }

    /** 设置选中广告主 */
    const handleSelectAdz = (value: number) => {
        if (value === selectAdz) {
            return
        }
        const accountId = selectedRows[value - 1].accountId
        setSelectData(selectedRows[value - 1])
        setQueryForm({ ...queryForm, pageNum: 1, accountId, ownerUid: wXDownPageAuthInfo[accountId]?.[0]?.accountId })
        setSelectAdz(value)
    }

    /** 一键设置 */
    const setOnekey = () => {
        let newData: { adgroupId: number, accountId: number, dynamicCreativeId: number, pageLength: number, pageList: any[] }[] = JSON.parse(JSON.stringify(data))
        function setPageData(pageIndex: number) {
            const pageList = data[selectAdz - 1]['pageList']
            const count = pageList.length
            const curPageData = pageList[pageIndex]
            const pageName: string = curPageData.pageName

            const hide = message.loading(`正在查找设置《${pageName}》当前第${pageIndex + 1}个...`, 0, () => {
                message.success('设置成功');
            });
            const filterData = newData?.filter(item => item.dynamicCreativeId !== data[selectAdz - 1].dynamicCreativeId)
            const ajax = filterData?.map(item => {
                const { marketingGoal, marketingTargetType, marketingCarrierType, siteSet } = adDataInfo[item.adgroupId]
                const params: any = {
                    ...queryForm,
                    accountId: item.accountId,
                    ownerUid: wXDownPageAuthInfo[item.accountId]?.[0]?.accountId,
                    pageStatus: 'NORMAL',
                    marketingGoal,
                    marketingTargetType,
                    marketingCarrierType,
                    siteSet: siteSet ? siteSet : ["SITE_SET_CHANNELS", "SITE_SET_MOMENTS", "SITE_SET_WECHAT", "SITE_SET_WECHAT_PLUGIN", "SITE_SET_KANDIAN", "SITE_SET_QQ_MUSIC_GAME", "SITE_SET_TENCENT_NEWS", "SITE_SET_TENCENT_VIDEO", "SITE_SET_MOBILE_UNION"],
                    pageType: 'PAGE_TYPE_OFFICIAL',
                    creativeTemplateId: creativeTemplateId || 311
                }
                if (!params.isSqDownPage) {
                    delete params?.ownerUid
                }
                delete params.isSqDownPage
                return getAdqLandingPageOfficialListApi(params)
            })
            Promise.all(ajax).then(res => {
                if (res && Array.isArray(res)) {
                    res.forEach((item: any, index) => {
                        const records = item?.data?.records
                        if (Array.isArray(records) && records?.length > 0) {
                            const record = records.find(item => (item.pageName === pageName && item.disableCode === 0))
                            const filterD = filterData[index]
                            newData = newData.map(item => {
                                if (item.accountId.toString() === filterD.accountId.toString() && record) {
                                    if (pageIndex === 0) {
                                        return { ...item, pageList: [{ ...record, id: record.pageId }] }
                                    } else {
                                        const pageList = item.pageList || []
                                        pageList.push({ ...record, id: record.pageId })
                                        return { ...item, pageList }
                                    }
                                }
                                return item
                            })
                        }
                    })
                    if (count > pageIndex + 1) {
                        setPageData(pageIndex + 1)
                    }
                    if (count === pageIndex + 1) {
                        setData(newData)
                    }
                }
                message.success('设置完成');
                hide()
            })
        }
        setPageData(0)
    }

    return <Modal
        title={<Space>
            <strong>替换官方落地页</strong>
            {data?.length > 1 && <Button style={{ padding: 0, margin: 0 }} disabled={!data[selectAdz - 1]['pageList']?.length} onClick={setOnekey} type="link" loading={getAdqLandingPageOfficialList?.loading || loading || loading1}>
                <Space>
                    <span style={{ fontSize: 12 }}>一键设置</span>
                    <Tooltip color="#FFF" overlayInnerStyle={{ color: '#000' }} title="设置其它有相同名称的落地页为那个账号的落地页（需要落地页名称相同，否则不设置，注意只会根据当前条件去搜索，比如选择了被授权落地页，只会去被授权落地页里找对应落地页）">
                        <QuestionCircleOutlined />
                    </Tooltip>
                </Space>
            </Button>}
        </Space>}
        open={visible}
        onCancel={onClose}
        onOk={handleOk}
        width={1100}
        className={`${style.SelectPackage} modalResetCss`}
        bodyStyle={{ padding: '0 10px 0 10px' }}
        confirmLoading={batchUpdateDownload?.loading}
    >
        <div className={style.content}>
            <div className={style.left} style={{ width: 200 }}>
                <h4 className={style.title}>创意</h4>
                <div className={style.accountIdList}>
                    {data?.map((item, index) => (
                        <div key={item?.accountId + '_' + item.dynamicCreativeId} onClick={() => { if (!loading && !loading1) handleSelectAdz(index + 1) }} className={`${style.accItem} ${selectAdz === index + 1 && style.select} `}>
                            {item.dynamicCreativeId}({item?.accountId})
                            {data[index].pageList?.length === pageLength && <CheckOutlined style={{ color: '#1890ff' }} />}
                        </div>
                    ))}
                </div>
            </div>
            <div className={style.right}>
                <Space style={{ marginBottom: 10 }}>
                    <Checkbox
                        onChange={(e) => {
                            if (e.target.checked && wXDownPageAuthInfo && Object.keys(wXDownPageAuthInfo).length) {
                                setQueryForm({ ...queryForm, pageNum: 1, ownerUid: wXDownPageAuthInfo[data[selectAdz - 1].accountId]?.[0]?.accountId, isSqDownPage: true })
                            } else {
                                setQueryForm({ ...queryForm, pageNum: 1, ownerUid: undefined, isSqDownPage: false })
                            }
                        }}
                        checked={queryForm.isSqDownPage}
                    ><span style={{ fontSize: 12 }}>被授权落地页</span></Checkbox>
                    {queryForm.isSqDownPage && <Select
                        placeholder='选择原生页授权方信息'
                        style={{ width: 210 }}
                        showSearch
                        filterOption={(input: any, option: any) =>
                            (option!.children as unknown as string).toLowerCase().includes(input.toLowerCase())
                        }
                        allowClear
                        onChange={(value) => {
                            setQueryForm({ ...queryForm, pageNum: 1, ownerUid: value })
                        }}
                        value={queryForm?.ownerUid}
                        dropdownMatchSelectWidth={false}
                    >
                        {wXDownPageAuthInfo?.[data[selectAdz - 1].accountId]?.map((item: { accountId: number; accountName: string }) => {
                            return <Select.Option value={item.accountId} key={item.accountId}>{item.accountName}({item.accountId})</Select.Option>
                        })}
                    </Select>}
                    <Input value={queryForm?.pageName} style={{ width: 150 }} allowClear placeholder='请输入落地页名称' onChange={(e) => setQueryForm({ ...queryForm, pageNum: 1, pageName: e.target.value })} />
                    <Button style={{ padding: 0, margin: 0 }} icon={<SyncOutlined />} type='link' loading={batchUpdateDownload?.loading} onClick={() => { batchUpdateDownload?.refresh() }}><span style={{ fontSize: 12 }}>刷新</span></Button>
                </Space>

                <Table
                    columns={columns(2)}
                    dataSource={tableData?.records}
                    size="small"
                    loading={getAdqLandingPageOfficialList?.loading || loading || loading1}
                    scroll={{ y: 400 }}
                    bordered
                    rowKey={'pageId'}
                    pagination={{
                        total: tableData?.total,
                        defaultPageSize: 20,
                        current: tableData?.current,
                        pageSize: tableData?.size
                    }}
                    onChange={(pagination) => {
                        const { current, pageSize } = pagination
                        setQueryForm({ ...queryForm, pageNum: current as number, pageSize: pageSize as number || 20 })
                    }}
                    /**
                     * canvasType
                     * VIDEO
                     * VIDEO_1280_960  横板1280*960
                     * VIDEO_1280_720  横板1280*720
                     * VERTICAL_VIDEO_NEW_916 9:16 视频
                     * COMMON_PAGE 引用外层素材原生页
                     * IMAGE
                     */
                    rowSelection={{
                        type: ([910].includes(creativeTemplateId) || deliveryMode === "DELIVERY_MODE_COMPONENT") ? 'checkbox' : 'radio',
                        getCheckboxProps: (record: any) => {
                            let { disableCode } = record
                            if (disableCode !== 0) {
                                return {
                                    disabled: true
                                }
                            }
                            // 组件化创意
                            if (deliveryMode === "DELIVERY_MODE_COMPONENT") {
                                if (data[selectAdz - 1]?.pageList?.length >= mainJumpInfo?.length) {
                                    return {
                                        disabled: data[selectAdz - 1]?.pageList?.some((item: any) => item?.pageId === record?.pageId) ? false : true
                                    }
                                } else {
                                    return {
                                        disabled: false
                                    }
                                }
                            }
                            return {
                                disabled: false
                            }
                        },
                        selectedRowKeys: data[selectAdz - 1]?.pageList?.map((item: any) => item?.pageId),
                        hideSelectAll: deliveryMode === "DELIVERY_MODE_COMPONENT",
                        onSelect: (record: any, selected: boolean) => {
                            let newData = JSON.parse(JSON.stringify(data))
                            if (([910].includes(creativeTemplateId) || deliveryMode === "DELIVERY_MODE_COMPONENT")) {
                                let selectedRows = newData?.[selectAdz - 1]?.['pageList'] || []
                                if (selected) {
                                    selectedRows.push({ ...record })
                                    newData[selectAdz - 1]['pageList'] = selectedRows
                                } else {
                                    newData[selectAdz - 1]['pageList'] = selectedRows.filter((item: { pageId: number }) => item.pageId !== record.pageId)
                                }
                            } else {
                                newData[selectAdz - 1]['pageList'] = [record]
                            }
                            setData([...newData])
                        },
                        onSelectAll: (selected: boolean, _: any[], changeRows: { pageId: number }[]) => {
                            let newData = JSON.parse(JSON.stringify(data))
                            let selectedRows = newData?.[selectAdz - 1]?.['pageList'] || []
                            if (selected) {
                                let newSelectAccData = [...selectedRows]
                                changeRows.forEach((item: { pageId: number }) => {
                                    let index = newSelectAccData.findIndex((ite: { pageId: number }) => ite.pageId === item.pageId)
                                    if (index === -1) {
                                        let data: any = { ...item }
                                        newSelectAccData.push(data)
                                    }
                                })
                                newData[selectAdz - 1]['pageList'] = newSelectAccData
                            } else {
                                newData[selectAdz - 1]['pageList'] = selectedRows.filter((item: { pageId: number }) => {
                                    let index = changeRows.findIndex((ite: { pageId: number }) => ite.pageId === item.pageId)
                                    if (index !== -1) {
                                        return false
                                    } else {
                                        return true
                                    }
                                })
                            }
                            setData([...newData])
                        }
                    }}
                />
            </div>
            <div className={style.center}>
                <Title level={5}>已选：{data[selectAdz - 1]?.pageList?.length || 0}/{data[selectAdz - 1].pageLength}</Title>
                <div className={style.select_content} style={{ height: 416 }}>
                    {data[selectAdz - 1]?.pageList?.map((item: any) => <div key={item.pageId}>
                        <Text ellipsis={{ tooltip: true }} className={style.marketingAssetName}>{item.pageName}</Text>
                        <CloseOutlined className={style.close} onClick={() => {
                            let newData: { adgroupId: number, accountId: number, dynamicCreativeId: number, pageLength: number, pageList: any[] }[] = JSON.parse(JSON.stringify(data))
                            newData[selectAdz - 1].pageList = newData[selectAdz - 1]?.pageList?.filter((i: any) => i?.pageId !== item.pageId)
                            setData(newData)
                        }} />
                    </div>)}
                </div>
            </div>
        </div>
    </Modal>
}

export default React.memo(ReplaceGfPage)