import { Button, Checkbox, Input, message, Modal, Select, Space, Table, Typography } from "antd";
import React, { useEffect, useState } from "react"
import '../../tencentAdPutIn/index.less'
import style from '../../components/GoodsModal/index.less'
import { getAdqLandingPageListApi, getWXDownPageAuthInfoListApi } from "@/services/adqV3/global"
import { batchUpdateDownloadApi, getAdgroupDetailApi } from "@/services/launchAdq/adqv3";
import { useAjax } from "@/Hook/useAjax";
import { CheckOutlined, CloseOutlined, 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 ReplacePage: React.FC<ReplacePageProps> = ({ selectedRows, visible, onChange, onClose }) => {

    /***********************************************/
    const { deliveryMode, creativeTemplateId, creativeComponents: { mainJumpInfo } } = selectedRows[0]
    const pageLength: number | undefined = mainJumpInfo?.length
    const overrideCanvasHeadOption = mainJumpInfo?.[0]?.value?.pageSpec?.wechatCanvasSpec?.overrideCanvasHeadOption
    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 [selectAdz, setSelectAdz] = useState<number>(1)   // 选择创意
    const [selectData, setSelectData] = useState<any>(selectedRows[0])   // 选择创意
    const [loading, setLoading] = useState<boolean>(false)
    const [loading1, setLoading1] = useState<boolean>(false)
    const [wXDownPageAuthInfo, setWXDownPageAuthInfo] = useState<any>({})
    const [adDataInfo, setAdDataInfo] = useState<any>({})
    const [queryForm, setQueryForm] = useState<{ accountId?: number, pageName?: string, ownerUid?: number, pageSize: number, pageNum: number, isSqDownPage: boolean, isCanvasType?: boolean }>({ pageNum: 1, pageSize: 20, isSqDownPage: false })
    const [tableData, setTableData] = useState<any>({})

    const getAdqLandingPageList = useAjax((params) => getAdqLandingPageListApi(params))
    const batchUpdateDownload = useAjax((params) => batchUpdateDownloadApi(params))
    /***********************************************/

    useEffect(() => {
        if (selectedRows?.length > 0) {
            setLoading(true)
            setLoading1(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 = async () => {
        const { marketingGoal, marketingTargetType, marketingCarrierType, siteSet, accountId } = adDataInfo[selectData.adgroupId]
        let params: any = { ...queryForm, accountId, pageStatus: 'NORMAL', marketingGoal, marketingTargetType, marketingCarrierType, siteSet }
        if (params.isSqDownPage) {
            if (!params?.ownerUid) {
                setTableData({ total: 0, records: [] })
                return
            }
        } else {
            delete params?.ownerUid
        }
        if (params?.isCanvasType) {
            params.canvasType = 'CANVAS_TYPE_COMMON_PAGE'
        }
        delete params?.isCanvasType
        delete params.isSqDownPage
        getAdqLandingPageList.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)
    }

    return <Modal
        title={<strong>替换原生落地页</strong>}
        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) => {
                            setQueryForm({ ...queryForm, pageNum: 1, isCanvasType: e.target.checked })
                        }}
                        checked={queryForm.isCanvasType}
                    ><span style={{ fontSize: 12 }}>展示外换内组件原生页</span></Checkbox>
                    <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={getAdqLandingPageList?.loading} onClick={() => { getAdqLandingPageList?.refresh() }}><span style={{ fontSize: 12 }}>刷新</span></Button>
                </Space>
                <Table
                    columns={columns()}
                    dataSource={tableData?.records}
                    size="small"
                    loading={getAdqLandingPageList?.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 { canvasType, pageElementsSpecList } = record
                            let topData = pageElementsSpecList[0]
                            if ([910].includes(creativeTemplateId) && canvasType === 'COMMON_PAGE') {
                                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
                                    }
                                }
                            }
                            /**
                             * 641 三图 642 4图 643 6图 311 一图
                             * 721 素板视频 9:16 -> VERTICAL_VIDEO_NEW_916  720 722 横板视频 -> VIDEO_1280_960
                             * 618 常规视频 ---> VIDEO
                             * 1708 1707 ---> false
                             */
                            if (overrideCanvasHeadOption === 'CREATIVE_OVERRIDE_CANVAS' || [1708, 1707].includes(creativeTemplateId)) {
                                return {
                                    disabled: false
                                }
                            }
                            if ([721].includes(creativeTemplateId) && canvasType === 'VERTICAL_VIDEO_NEW_916') {
                                return {
                                    disabled: false
                                }
                            } else if ([720, 722].includes(creativeTemplateId) && canvasType === 'VIDEO_1280_960') {
                                return {
                                    disabled: false
                                }
                            } else if ([618].includes(creativeTemplateId) && canvasType === 'VIDEO') {
                                return {
                                    disabled: false
                                }
                            } else if ([311].includes(creativeTemplateId) && canvasType === "IMAGE" && topData.imageSpec.length === 1) {
                                return {
                                    disabled: false
                                }
                            } else if ([641].includes(creativeTemplateId) && canvasType === "IMAGE" && topData.imageSpec.length === 3) {
                                return {
                                    disabled: false
                                }
                            } else if ([642].includes(creativeTemplateId) && canvasType === "IMAGE" && topData.imageSpec.length === 4) {
                                return {
                                    disabled: false
                                }
                            } else if ([643].includes(creativeTemplateId) && canvasType === "IMAGE" && topData.imageSpec.length === 6) {
                                return {
                                    disabled: false
                                }
                            }
                            return {
                                disabled: true
                            }
                        },
                        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(ReplacePage)